blob: 6a6b5ce08f8ba553d57c66dd9bb6a756c98895fb [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);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002010 try {
chengangf2d081c2017-12-27 17:17:32 +08002011 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
2012 Log.e(TAG, "renameAccount failed - account with new name already exists");
2013 return null;
2014 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002015 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(
2194 "uid %s cannot explicitly add accounts of type: %s",
2195 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 try {
tiansiming5330b5a2017-10-13 10:57:25 +08002252 response.onResult(result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002253 } catch (RemoteException e) {
tiansiming5330b5a2017-10-13 10:57:25 +08002254 Slog.e(TAG, "Error calling onResult()", e);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002255 }
2256 }
2257 }
2258 super.onResult(result);
2259 }
2260 }
2261
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002262 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002263 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002264 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002265 }
2266
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002267 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002268 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002269 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002270 if (!userUnlocked) {
2271 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2272 + " is still locked. CE data will be removed later");
2273 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002274 synchronized (accounts.dbLock) {
2275 synchronized (accounts.cacheLock) {
2276 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2277 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002278 List<String> accountRemovedReceivers =
2279 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002280 accounts.accountsDb.beginTransaction();
2281 // Set to a dummy value, this will only be used if the database
2282 // transaction succeeds.
2283 long accountId = -1;
2284 try {
2285 accountId = accounts.accountsDb.findDeAccountId(account);
2286 if (accountId >= 0) {
2287 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002288 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002289 // always delete from CE table if CE storage is available
2290 // DE account could be removed while CE was locked
2291 if (userUnlocked) {
2292 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2293 if (ceAccountId >= 0) {
2294 accounts.accountsDb.deleteCeAccount(ceAccountId);
2295 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002296 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002297 accounts.accountsDb.setTransactionSuccessful();
2298 } finally {
2299 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002300 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002301 if (isChanged) {
2302 removeAccountFromCacheLocked(accounts, account);
2303 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2304 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002305 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2306 || (packageToVisibility.getValue()
2307 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002308 notifyPackage(packageToVisibility.getKey(), accounts);
2309 }
2310 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002311
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002312 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2313 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002314 for (String packageName : accountRemovedReceivers) {
2315 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2316 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002317 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2318 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2319 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2320 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002321 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002322 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002323 long id = Binder.clearCallingIdentity();
2324 try {
2325 int parentUserId = accounts.userId;
2326 if (canHaveProfile(parentUserId)) {
2327 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002328 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002329 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002330 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002331 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002332 }
2333 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002334 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002335 } finally {
2336 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002337 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002338
2339 if (isChanged) {
2340 synchronized (accounts.credentialsPermissionNotificationIds) {
2341 for (Pair<Pair<Account, String>, Integer> key
2342 : accounts.credentialsPermissionNotificationIds.keySet()) {
2343 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002344 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002345 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002346 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002347 account, uid, false));
2348 }
2349 }
2350 }
2351 }
2352
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002353 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002354 }
2355
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002356 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002357 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002358 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002359 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2360 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002361 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2362 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002363 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002364 + ", pid " + Binder.getCallingPid());
2365 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002366 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002367 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002368 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002369 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002370 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002371 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002372 accounts.accountsDb.beginTransaction();
2373 try {
2374 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2375 accounts.accountsDb.setTransactionSuccessful();
2376 } finally {
2377 accounts.accountsDb.endTransaction();
2378 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002379 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002380 for (Pair<Account, String> tokenInfo : deletedTokens) {
2381 Account act = tokenInfo.first;
2382 String tokenType = tokenInfo.second;
2383 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002384 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002385 // wipe out cached token in memory.
2386 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002387 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002388 }
Fred Quintana60307342009-03-24 22:48:12 -07002389 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002390 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002391 }
2392 }
2393
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002394 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002395 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002396 // TODO Move to AccountsDB
2397 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002398 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002399
Fred Quintana33269202009-04-20 16:05:10 -07002400 try {
2401 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002402 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002403 String accountName = cursor.getString(1);
2404 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002405 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002406 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002407 }
Fred Quintana33269202009-04-20 16:05:10 -07002408 } finally {
2409 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002410 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002411 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002412 }
2413
Carlos Valdivia91979be2015-05-22 14:11:35 -07002414 private void saveCachedToken(
2415 UserAccounts accounts,
2416 Account account,
2417 String callerPkg,
2418 byte[] callerSigDigest,
2419 String tokenType,
2420 String token,
2421 long expiryMillis) {
2422
2423 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2424 return;
2425 }
2426 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002427 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002428 synchronized (accounts.cacheLock) {
2429 accounts.accountTokenCaches.put(
2430 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002431 }
2432 }
2433
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2435 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002436 if (account == null || type == null) {
2437 return false;
2438 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002439 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002440 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002441 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002442 accounts.accountsDb.beginTransaction();
2443 boolean updateCache = false;
2444 try {
2445 long accountId = accounts.accountsDb.findDeAccountId(account);
2446 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002447 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002448 }
2449 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2450 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2451 accounts.accountsDb.setTransactionSuccessful();
2452 updateCache = true;
2453 return true;
2454 }
2455 return false;
2456 } finally {
2457 accounts.accountsDb.endTransaction();
2458 if (updateCache) {
2459 synchronized (accounts.cacheLock) {
2460 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2461 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002462 }
Fred Quintana33269202009-04-20 16:05:10 -07002463 }
Fred Quintana60307342009-03-24 22:48:12 -07002464 }
2465 }
2466
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002467 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002468 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002469 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002470 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2471 Log.v(TAG, "peekAuthToken: " + account
2472 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002473 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002474 + ", pid " + Binder.getCallingPid());
2475 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002476 Preconditions.checkNotNull(account, "account cannot be null");
2477 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002478 int userId = UserHandle.getCallingUserId();
2479 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002480 String msg = String.format(
2481 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2482 callingUid,
2483 account.type);
2484 throw new SecurityException(msg);
2485 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002486 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002487 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2488 + callingUid);
2489 return null;
2490 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002491 long identityToken = clearCallingIdentity();
2492 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002493 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002494 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002495 } finally {
2496 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002497 }
Fred Quintana60307342009-03-24 22:48:12 -07002498 }
2499
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002500 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002501 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002502 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2504 Log.v(TAG, "setAuthToken: " + account
2505 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002506 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002507 + ", pid " + Binder.getCallingPid());
2508 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002509 Preconditions.checkNotNull(account, "account cannot be null");
2510 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002511 int userId = UserHandle.getCallingUserId();
2512 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002513 String msg = String.format(
2514 "uid %s cannot set auth tokens associated with accounts of type: %s",
2515 callingUid,
2516 account.type);
2517 throw new SecurityException(msg);
2518 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002519 long identityToken = clearCallingIdentity();
2520 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002521 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002523 } finally {
2524 restoreCallingIdentity(identityToken);
2525 }
Fred Quintana60307342009-03-24 22:48:12 -07002526 }
2527
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002528 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002529 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002530 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002531 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2532 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002533 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002534 + ", pid " + Binder.getCallingPid());
2535 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002536 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002537 int userId = UserHandle.getCallingUserId();
2538 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002539 String msg = String.format(
2540 "uid %s cannot set secrets for accounts of type: %s",
2541 callingUid,
2542 account.type);
2543 throw new SecurityException(msg);
2544 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002545 long identityToken = clearCallingIdentity();
2546 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002547 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002548 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002549 } finally {
2550 restoreCallingIdentity(identityToken);
2551 }
Fred Quintana60307342009-03-24 22:48:12 -07002552 }
2553
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002554 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2555 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002556 if (account == null) {
2557 return;
2558 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002559 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002560 synchronized (accounts.dbLock) {
2561 synchronized (accounts.cacheLock) {
2562 accounts.accountsDb.beginTransaction();
2563 try {
2564 final long accountId = accounts.accountsDb.findDeAccountId(account);
2565 if (accountId >= 0) {
2566 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2567 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2568 accounts.authTokenCache.remove(account);
2569 accounts.accountTokenCaches.remove(account);
2570 accounts.accountsDb.setTransactionSuccessful();
2571 // If there is an account whose password will be updated and the database
2572 // transactions succeed, then we say that a change has occured. Even if the
2573 // new password is the same as the old and there were no authtokens to
2574 // delete.
2575 isChanged = true;
2576 String action = (password == null || password.length() == 0) ?
2577 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2578 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2579 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2580 callingUid);
2581 }
2582 } finally {
2583 accounts.accountsDb.endTransaction();
2584 if (isChanged) {
2585 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2586 sendNotificationAccountUpdated(account, accounts);
2587 sendAccountsChangedBroadcast(accounts.userId);
2588 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002589 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002590 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002591 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002592 }
2593
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002594 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002595 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002596 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002597 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2598 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002599 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002600 + ", pid " + Binder.getCallingPid());
2601 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002602 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002603 int userId = UserHandle.getCallingUserId();
2604 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002605 String msg = String.format(
2606 "uid %s cannot clear passwords for accounts of type: %s",
2607 callingUid,
2608 account.type);
2609 throw new SecurityException(msg);
2610 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002611 long identityToken = clearCallingIdentity();
2612 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002613 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002614 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002615 } finally {
2616 restoreCallingIdentity(identityToken);
2617 }
Fred Quintana60307342009-03-24 22:48:12 -07002618 }
2619
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002620 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002621 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002622 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002623 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2624 Log.v(TAG, "setUserData: " + account
2625 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002626 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002627 + ", pid " + Binder.getCallingPid());
2628 }
Fred Quintana382601f2010-03-25 12:25:10 -07002629 if (key == null) throw new IllegalArgumentException("key is null");
2630 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002631 int userId = UserHandle.getCallingUserId();
2632 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002633 String msg = String.format(
2634 "uid %s cannot set user data for accounts of type: %s",
2635 callingUid,
2636 account.type);
2637 throw new SecurityException(msg);
2638 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002639 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002640 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002641 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002642 if (!accountExistsCache(accounts, account)) {
2643 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002644 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002645 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002646 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002647 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002648 }
2649 }
2650
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002651 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2652 synchronized (accounts.cacheLock) {
2653 if (accounts.accountCache.containsKey(account.type)) {
2654 for (Account acc : accounts.accountCache.get(account.type)) {
2655 if (acc.name.equals(account.name)) {
2656 return true;
2657 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002658 }
2659 }
2660 }
2661 return false;
2662 }
2663
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002664 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002665 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002666 synchronized (accounts.dbLock) {
2667 accounts.accountsDb.beginTransaction();
2668 try {
2669 long accountId = accounts.accountsDb.findDeAccountId(account);
2670 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002671 return;
2672 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002673 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2674 if (extrasId < 0) {
2675 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2676 if (extrasId < 0) {
2677 return;
2678 }
2679 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2680 return;
2681 }
2682 accounts.accountsDb.setTransactionSuccessful();
2683 } finally {
2684 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002685 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002686 synchronized (accounts.cacheLock) {
2687 writeUserDataIntoCacheLocked(accounts, account, key, value);
2688 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002689 }
2690 }
2691
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002692 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002693 if (result == null) {
2694 Log.e(TAG, "the result is unexpectedly null", new Exception());
2695 }
2696 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2697 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2698 + response);
2699 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002700 try {
2701 response.onResult(result);
2702 } catch (RemoteException e) {
2703 // if the caller is dead then there is no one to care about remote
2704 // exceptions
2705 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2706 Log.v(TAG, "failure while notifying response", e);
2707 }
2708 }
2709 }
2710
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002711 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002712 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2713 final String authTokenType)
2714 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002715 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2716 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002717
Fred Quintanad9640ec2012-05-23 12:37:00 -07002718 final int callingUid = getCallingUid();
2719 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002720 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002721 throw new SecurityException("can only call from system");
2722 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002723 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002724 long identityToken = clearCallingIdentity();
2725 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002726 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002727 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2728 false /* stripAuthTokenFromResult */, null /* accountName */,
2729 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002730 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002731 protected String toDebugString(long now) {
2732 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002733 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002734 + ", authTokenType " + authTokenType;
2735 }
2736
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002737 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002738 public void run() throws RemoteException {
2739 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2740 }
2741
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002742 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002743 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002744 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002745 if (result != null) {
2746 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2747 Bundle bundle = new Bundle();
2748 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2749 super.onResult(bundle);
2750 return;
2751 } else {
2752 super.onResult(result);
2753 }
2754 }
2755 }.bind();
2756 } finally {
2757 restoreCallingIdentity(identityToken);
2758 }
2759 }
2760
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002761 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002762 public void getAuthToken(
2763 IAccountManagerResponse response,
2764 final Account account,
2765 final String authTokenType,
2766 final boolean notifyOnAuthFailure,
2767 final boolean expectActivityLaunch,
2768 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002769 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002770 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2771 Log.v(TAG, "getAuthToken: " + account
2772 + ", response " + response
2773 + ", authTokenType " + authTokenType
2774 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2775 + ", expectActivityLaunch " + expectActivityLaunch
2776 + ", caller's uid " + Binder.getCallingUid()
2777 + ", pid " + Binder.getCallingPid());
2778 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002779 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002780 try {
2781 if (account == null) {
2782 Slog.w(TAG, "getAuthToken called with null account");
2783 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2784 return;
2785 }
2786 if (authTokenType == null) {
2787 Slog.w(TAG, "getAuthToken called with null authTokenType");
2788 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2789 return;
2790 }
2791 } catch (RemoteException e) {
2792 Slog.w(TAG, "Failed to report error back to the client." + e);
2793 return;
2794 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002795 int userId = UserHandle.getCallingUserId();
2796 long ident = Binder.clearCallingIdentity();
2797 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002798 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002799 try {
2800 accounts = getUserAccounts(userId);
2801 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2802 AuthenticatorDescription.newKey(account.type), accounts.userId);
2803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002806
Costin Manolachea40c6302010-12-13 14:50:45 -08002807 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002808 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002809
2810 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002811 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002812 final boolean permissionGranted =
2813 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002814
Carlos Valdivia91979be2015-05-22 14:11:35 -07002815 // Get the calling package. We will use it for the purpose of caching.
2816 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002817 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002818 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002819 try {
2820 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2821 } finally {
2822 Binder.restoreCallingIdentity(ident);
2823 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002824 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2825 String msg = String.format(
2826 "Uid %s is attempting to illegally masquerade as package %s!",
2827 callerUid,
2828 callerPkg);
2829 throw new SecurityException(msg);
2830 }
2831
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002832 // let authenticator know the identity of the caller
2833 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2834 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002835
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002836 if (notifyOnAuthFailure) {
2837 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002838 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002839
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002840 long identityToken = clearCallingIdentity();
2841 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002842 // Distill the caller's package signatures into a single digest.
2843 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2844
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002845 // if the caller has permission, do the peek. otherwise go the more expensive
2846 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002847 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002848 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002849 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002850 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002851 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2852 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2853 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002854 onResult(response, result);
2855 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002856 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002857 }
2858
Carlos Valdivia91979be2015-05-22 14:11:35 -07002859 if (customTokens) {
2860 /*
2861 * Look up tokens in the new cache only if the loginOptions don't have parameters
2862 * outside of those expected to be injected by the AccountManager, e.g.
2863 * ANDORID_PACKAGE_NAME.
2864 */
2865 String token = readCachedTokenInternal(
2866 accounts,
2867 account,
2868 authTokenType,
2869 callerPkg,
2870 callerPkgSigDigest);
2871 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002872 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2873 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2874 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002875 Bundle result = new Bundle();
2876 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2877 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2878 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2879 onResult(response, result);
2880 return;
2881 }
2882 }
2883
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002884 new Session(
2885 accounts,
2886 response,
2887 account.type,
2888 expectActivityLaunch,
2889 false /* stripAuthTokenFromResult */,
2890 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002891 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002892 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002893 protected String toDebugString(long now) {
2894 if (loginOptions != null) loginOptions.keySet();
2895 return super.toDebugString(now) + ", getAuthToken"
2896 + ", " + account
2897 + ", authTokenType " + authTokenType
2898 + ", loginOptions " + loginOptions
2899 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2900 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002901
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002902 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002903 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002904 // If the caller doesn't have permission then create and return the
2905 // "grant permission" intent instead of the "getAuthToken" intent.
2906 if (!permissionGranted) {
2907 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2908 } else {
2909 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2910 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002911 }
2912
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002913 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002914 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002915 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002916 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002917 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002918 Intent intent = newGrantCredentialsPermissionIntent(
2919 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002920 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002921 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002922 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002923 authTokenType,
2924 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002925 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002926 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002927 onResult(bundle);
2928 return;
2929 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002930 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002931 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002932 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2933 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002934 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002935 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002936 "the type and name should not be empty");
2937 return;
2938 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002939 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002940 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002941 saveAuthTokenToDatabase(
2942 mAccounts,
2943 resultAccount,
2944 authTokenType,
2945 authToken);
2946 }
2947 long expiryMillis = result.getLong(
2948 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2949 if (customTokens
2950 && expiryMillis > System.currentTimeMillis()) {
2951 saveCachedToken(
2952 mAccounts,
2953 account,
2954 callerPkg,
2955 callerPkgSigDigest,
2956 authTokenType,
2957 authToken,
2958 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002959 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002960 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002961
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002962 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002963 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002964 /*
2965 * Make sure that the supplied intent is owned by the authenticator
2966 * giving it to the system. Otherwise a malicious authenticator could
2967 * have users launching arbitrary activities by tricking users to
2968 * interact with malicious notifications.
2969 */
2970 checkKeyIntent(
2971 Binder.getCallingUid(),
2972 intent);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002973 doNotification(
2974 mAccounts,
2975 account,
2976 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002977 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002978 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002979 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002980 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002981 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002982 }.bind();
2983 } finally {
2984 restoreCallingIdentity(identityToken);
2985 }
Fred Quintana60307342009-03-24 22:48:12 -07002986 }
2987
Carlos Valdivia91979be2015-05-22 14:11:35 -07002988 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2989 MessageDigest digester;
2990 try {
2991 digester = MessageDigest.getInstance("SHA-256");
2992 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2993 callerPkg, PackageManager.GET_SIGNATURES);
2994 for (Signature sig : pkgInfo.signatures) {
2995 digester.update(sig.toByteArray());
2996 }
2997 } catch (NoSuchAlgorithmException x) {
2998 Log.wtf(TAG, "SHA-256 should be available", x);
2999 digester = null;
3000 } catch (NameNotFoundException e) {
3001 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
3002 digester = null;
3003 }
3004 return (digester == null) ? null : digester.digest();
3005 }
3006
Dianne Hackborn41203752012-08-31 14:05:51 -07003007 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003008 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003009 int uid = intent.getIntExtra(
3010 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
3011 String authTokenType = intent.getStringExtra(
3012 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07003013 final String titleAndSubtitle =
3014 mContext.getString(R.string.permission_request_notification_with_subtitle,
3015 account.name);
3016 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003017 String title = titleAndSubtitle;
3018 String subtitle = "";
3019 if (index > 0) {
3020 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003021 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003022 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003023 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003024 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003025 Notification n =
3026 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3027 .setSmallIcon(android.R.drawable.stat_sys_warning)
3028 .setWhen(0)
3029 .setColor(contextForUser.getColor(
3030 com.android.internal.R.color.system_notification_accent_color))
3031 .setContentTitle(title)
3032 .setContentText(subtitle)
3033 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3034 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3035 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003036 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003037 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003038 }
3039
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003040 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3041 int uid, AccountAuthenticatorResponse response, String authTokenType,
3042 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003043
3044 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003045
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003046 if (startInNewTask) {
3047 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3048 // Since it was set in Eclair+ we can't change it without breaking apps using
3049 // the intent from a non-Activity context. This is the default behavior.
3050 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3051 }
Chris Wren717a8812017-03-31 15:34:39 -04003052 intent.addCategory(getCredentialPermissionNotificationId(account,
3053 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003054 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003055 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3056 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003057 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003058
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003059 return intent;
3060 }
3061
Chris Wren717a8812017-03-31 15:34:39 -04003062 private NotificationId getCredentialPermissionNotificationId(Account account,
3063 String authTokenType, int uid) {
3064 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003065 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003066 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003067 final Pair<Pair<Account, String>, Integer> key =
3068 new Pair<Pair<Account, String>, Integer>(
3069 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003070 nId = accounts.credentialsPermissionNotificationIds.get(key);
3071 if (nId == null) {
3072 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3073 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3074 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3075 nId = new NotificationId(tag, id);
3076 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003077 }
3078 }
Chris Wren717a8812017-03-31 15:34:39 -04003079 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003080 }
3081
Chris Wren717a8812017-03-31 15:34:39 -04003082 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3083 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003084 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003085 nId = accounts.signinRequiredNotificationIds.get(account);
3086 if (nId == null) {
3087 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3088 + ":" + account.hashCode();
3089 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3090 nId = new NotificationId(tag, id);
3091 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003092 }
3093 }
Chris Wren717a8812017-03-31 15:34:39 -04003094 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003095 }
3096
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003097 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003098 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003099 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003100 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003101 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003102 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3103 Log.v(TAG, "addAccount: accountType " + accountType
3104 + ", response " + response
3105 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003106 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003107 + ", expectActivityLaunch " + expectActivityLaunch
3108 + ", caller's uid " + Binder.getCallingUid()
3109 + ", pid " + Binder.getCallingPid());
3110 }
Fred Quintana382601f2010-03-25 12:25:10 -07003111 if (response == null) throw new IllegalArgumentException("response is null");
3112 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003113
Amith Yamasani71e6c692013-03-24 17:39:28 -07003114 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003115 final int uid = Binder.getCallingUid();
3116 final int userId = UserHandle.getUserId(uid);
3117 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003118 try {
3119 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3120 "User is not allowed to add an account!");
3121 } catch (RemoteException re) {
3122 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003123 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003124 return;
3125 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003126 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003127 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003128 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3129 "User cannot modify accounts of this type (policy).");
3130 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003131 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003132 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3133 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003134 return;
3135 }
3136
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003137 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003138 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3139 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3140 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3141
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003142 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003143 long identityToken = clearCallingIdentity();
3144 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003145 UserAccounts accounts = getUserAccounts(usrId);
3146 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003147 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3148 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003149 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003150 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003151 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003152 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003153 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003154 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003155 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003156 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003157
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003158 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003159 protected String toDebugString(long now) {
3160 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003161 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003162 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003163 }
3164 }.bind();
3165 } finally {
3166 restoreCallingIdentity(identityToken);
3167 }
Fred Quintana60307342009-03-24 22:48:12 -07003168 }
3169
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003170 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003171 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3172 final String authTokenType, final String[] requiredFeatures,
3173 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003174 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003175 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003176 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3177 Log.v(TAG, "addAccount: accountType " + accountType
3178 + ", response " + response
3179 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003180 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003181 + ", expectActivityLaunch " + expectActivityLaunch
3182 + ", caller's uid " + Binder.getCallingUid()
3183 + ", pid " + Binder.getCallingPid()
3184 + ", for user id " + userId);
3185 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003186 Preconditions.checkArgument(response != null, "response cannot be null");
3187 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003188 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003189 if (isCrossUser(callingUid, userId)) {
3190 throw new SecurityException(
3191 String.format(
3192 "User %s trying to add account for %s" ,
3193 UserHandle.getCallingUserId(),
3194 userId));
3195 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003196
3197 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003198 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003199 try {
3200 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3201 "User is not allowed to add an account!");
3202 } catch (RemoteException re) {
3203 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003204 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003205 return;
3206 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003207 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003208 try {
3209 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3210 "User cannot modify accounts of this type (policy).");
3211 } catch (RemoteException re) {
3212 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003213 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3214 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003215 return;
3216 }
3217
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003218 final int pid = Binder.getCallingPid();
3219 final int uid = Binder.getCallingUid();
3220 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3221 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3222 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3223
3224 long identityToken = clearCallingIdentity();
3225 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003226 UserAccounts accounts = getUserAccounts(userId);
3227 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003228 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3229 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003230 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003231 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003232 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003233 @Override
3234 public void run() throws RemoteException {
3235 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3236 options);
3237 }
3238
3239 @Override
3240 protected String toDebugString(long now) {
3241 return super.toDebugString(now) + ", addAccount"
3242 + ", accountType " + accountType
3243 + ", requiredFeatures "
3244 + (requiredFeatures != null
3245 ? TextUtils.join(",", requiredFeatures)
3246 : null);
3247 }
3248 }.bind();
3249 } finally {
3250 restoreCallingIdentity(identityToken);
3251 }
3252 }
3253
Sandra Kwan78812282015-11-04 11:19:47 -08003254 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003255 public void startAddAccountSession(
3256 final IAccountManagerResponse response,
3257 final String accountType,
3258 final String authTokenType,
3259 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003260 final boolean expectActivityLaunch,
3261 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003262 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003263 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3264 Log.v(TAG,
3265 "startAddAccountSession: accountType " + accountType
3266 + ", response " + response
3267 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003268 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003269 + ", expectActivityLaunch " + expectActivityLaunch
3270 + ", caller's uid " + Binder.getCallingUid()
3271 + ", pid " + Binder.getCallingPid());
3272 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003273 Preconditions.checkArgument(response != null, "response cannot be null");
3274 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003275
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003276 final int uid = Binder.getCallingUid();
3277 final int userId = UserHandle.getUserId(uid);
3278 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003279 try {
3280 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3281 "User is not allowed to add an account!");
3282 } catch (RemoteException re) {
3283 }
3284 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3285 return;
3286 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003287 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003288 try {
3289 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3290 "User cannot modify accounts of this type (policy).");
3291 } catch (RemoteException re) {
3292 }
3293 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3294 userId);
3295 return;
3296 }
Sandra Kwan78812282015-11-04 11:19:47 -08003297 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003298 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3299 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3300 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3301
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003302 // Check to see if the Password should be included to the caller.
3303 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3304 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003305 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003306
Sandra Kwan78812282015-11-04 11:19:47 -08003307 long identityToken = clearCallingIdentity();
3308 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003309 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003310 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3311 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003312 new StartAccountSession(
3313 accounts,
3314 response,
3315 accountType,
3316 expectActivityLaunch,
3317 null /* accountName */,
3318 false /* authDetailsRequired */,
3319 true /* updateLastAuthenticationTime */,
3320 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003321 @Override
3322 public void run() throws RemoteException {
3323 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3324 requiredFeatures, options);
3325 }
3326
3327 @Override
3328 protected String toDebugString(long now) {
3329 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3330 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3331 + accountType + ", requiredFeatures "
3332 + (requiredFeatures != null ? requiredFeaturesStr : null);
3333 }
3334 }.bind();
3335 } finally {
3336 restoreCallingIdentity(identityToken);
3337 }
3338 }
3339
3340 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3341 private abstract class StartAccountSession extends Session {
3342
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003343 private final boolean mIsPasswordForwardingAllowed;
3344
3345 public StartAccountSession(
3346 UserAccounts accounts,
3347 IAccountManagerResponse response,
3348 String accountType,
3349 boolean expectActivityLaunch,
3350 String accountName,
3351 boolean authDetailsRequired,
3352 boolean updateLastAuthenticationTime,
3353 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003354 super(accounts, response, accountType, expectActivityLaunch,
3355 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3356 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003357 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003358 }
3359
3360 @Override
3361 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003362 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003363 mNumResults++;
3364 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003365 if (result != null
3366 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003367 checkKeyIntent(
3368 Binder.getCallingUid(),
3369 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003370 }
Sandra Kwan78812282015-11-04 11:19:47 -08003371 IAccountManagerResponse response;
3372 if (mExpectActivityLaunch && result != null
3373 && result.containsKey(AccountManager.KEY_INTENT)) {
3374 response = mResponse;
3375 } else {
3376 response = getResponseAndClose();
3377 }
3378 if (response == null) {
3379 return;
3380 }
3381 if (result == null) {
3382 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3383 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3384 + response);
3385 }
3386 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3387 "null bundle returned");
3388 return;
3389 }
3390
3391 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3392 // All AccountManager error codes are greater
3393 // than 0
3394 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3395 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3396 return;
3397 }
3398
Hongming Jin368aa192016-07-29 14:29:54 -07003399 // Omit passwords if the caller isn't permitted to see them.
3400 if (!mIsPasswordForwardingAllowed) {
3401 result.remove(AccountManager.KEY_PASSWORD);
3402 }
3403
Sandra Kwan78812282015-11-04 11:19:47 -08003404 // Strip auth token from result.
3405 result.remove(AccountManager.KEY_AUTHTOKEN);
3406
3407 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3408 Log.v(TAG,
3409 getClass().getSimpleName() + " calling onResult() on response " + response);
3410 }
3411
3412 // Get the session bundle created by authenticator. The
3413 // bundle contains data necessary for finishing the session
3414 // later. The session bundle will be encrypted here and
3415 // decrypted later when trying to finish the session.
3416 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3417 if (sessionBundle != null) {
3418 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3419 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003420 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003421 Log.w(TAG, "Account type in session bundle doesn't match request.");
3422 }
3423 // Add accountType info to session bundle. This will
3424 // override any value set by authenticator.
3425 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3426
3427 // Encrypt session bundle before returning to caller.
3428 try {
3429 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3430 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3431 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3432 } catch (GeneralSecurityException e) {
3433 if (Log.isLoggable(TAG, Log.DEBUG)) {
3434 Log.v(TAG, "Failed to encrypt session bundle!", e);
3435 }
3436 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3437 "failed to encrypt session bundle");
3438 return;
3439 }
3440 }
3441
3442 sendResponse(response, result);
3443 }
3444 }
3445
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003446 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003447 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003448 @NonNull Bundle sessionBundle,
3449 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003450 Bundle appInfo,
3451 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003452 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003453 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003454 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3455 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003456 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003457 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003458 + ", caller's uid " + callingUid
3459 + ", caller's user id " + UserHandle.getCallingUserId()
3460 + ", pid " + Binder.getCallingPid()
3461 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003462 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003463 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003464 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3465 // Account type is added to it before encryption.
3466 if (sessionBundle == null || sessionBundle.size() == 0) {
3467 throw new IllegalArgumentException("sessionBundle is empty");
3468 }
3469
Dmitry Dementyev52745472016-12-02 10:27:45 -08003470 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003471 if (isCrossUser(callingUid, userId)) {
3472 throw new SecurityException(
3473 String.format(
3474 "User %s trying to finish session for %s without cross user permission",
3475 UserHandle.getCallingUserId(),
3476 userId));
3477 }
3478
Sandra Kwan0b84b452016-01-20 15:25:42 -08003479 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003480 sendErrorResponse(response,
3481 AccountManager.ERROR_CODE_USER_RESTRICTED,
3482 "User is not allowed to add an account!");
3483 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3484 return;
3485 }
3486
3487 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003488 final Bundle decryptedBundle;
3489 final String accountType;
3490 // First decrypt session bundle to get account type for checking permission.
3491 try {
3492 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3493 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3494 if (decryptedBundle == null) {
3495 sendErrorResponse(
3496 response,
3497 AccountManager.ERROR_CODE_BAD_REQUEST,
3498 "failed to decrypt session bundle");
3499 return;
3500 }
3501 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3502 // Account type cannot be null. This should not happen if session bundle was created
3503 // properly by #StartAccountSession.
3504 if (TextUtils.isEmpty(accountType)) {
3505 sendErrorResponse(
3506 response,
3507 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3508 "accountType is empty");
3509 return;
3510 }
3511
3512 // If by any chances, decryptedBundle contains colliding keys with
3513 // system info
3514 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3515 // update credentials flow, we should replace with the new values of the current call.
3516 if (appInfo != null) {
3517 decryptedBundle.putAll(appInfo);
3518 }
3519
3520 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003521 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003522 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3523 } catch (GeneralSecurityException e) {
3524 if (Log.isLoggable(TAG, Log.DEBUG)) {
3525 Log.v(TAG, "Failed to decrypt session bundle!", e);
3526 }
3527 sendErrorResponse(
3528 response,
3529 AccountManager.ERROR_CODE_BAD_REQUEST,
3530 "failed to decrypt session bundle");
3531 return;
3532 }
3533
Sandra Kwan0b84b452016-01-20 15:25:42 -08003534 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003535 sendErrorResponse(
3536 response,
3537 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3538 "User cannot modify accounts of this type (policy).");
3539 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3540 userId);
3541 return;
3542 }
3543
3544 long identityToken = clearCallingIdentity();
3545 try {
3546 UserAccounts accounts = getUserAccounts(userId);
3547 logRecordWithUid(
3548 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003549 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3550 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003551 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003552 new Session(
3553 accounts,
3554 response,
3555 accountType,
3556 expectActivityLaunch,
3557 true /* stripAuthTokenFromResult */,
3558 null /* accountName */,
3559 false /* authDetailsRequired */,
3560 true /* updateLastAuthenticationTime */) {
3561 @Override
3562 public void run() throws RemoteException {
3563 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3564 }
3565
3566 @Override
3567 protected String toDebugString(long now) {
3568 return super.toDebugString(now)
3569 + ", finishSession"
3570 + ", accountType " + accountType;
3571 }
3572 }.bind();
3573 } finally {
3574 restoreCallingIdentity(identityToken);
3575 }
3576 }
3577
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003578 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003579 final DevicePolicyManagerInternal dpmi =
3580 LocalServices.getService(DevicePolicyManagerInternal.class);
3581 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003582 if (dpmi == null) {
3583 intent = getDefaultCantAddAccountIntent(errorCode);
3584 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003585 intent = dpmi.createUserRestrictionSupportIntent(userId,
3586 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3587 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3588 intent = dpmi.createShowAdminSupportIntent(userId, false);
3589 }
3590 if (intent == null) {
3591 intent = getDefaultCantAddAccountIntent(errorCode);
3592 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003593 long identityToken = clearCallingIdentity();
3594 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003595 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003596 } finally {
3597 restoreCallingIdentity(identityToken);
3598 }
3599 }
3600
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003601 /**
3602 * Called when we don't know precisely who is preventing us from adding an account.
3603 */
3604 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3605 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3606 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3607 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3608 return cantAddAccount;
3609 }
3610
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003611 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003612 public void confirmCredentialsAsUser(
3613 IAccountManagerResponse response,
3614 final Account account,
3615 final Bundle options,
3616 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003617 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003618 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003619 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003620 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3621 Log.v(TAG, "confirmCredentials: " + account
3622 + ", response " + response
3623 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003624 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003625 + ", pid " + Binder.getCallingPid());
3626 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003627 // Only allow the system process to read accounts of other users
3628 if (isCrossUser(callingUid, userId)) {
3629 throw new SecurityException(
3630 String.format(
3631 "User %s trying to confirm account credentials for %s" ,
3632 UserHandle.getCallingUserId(),
3633 userId));
3634 }
Fred Quintana382601f2010-03-25 12:25:10 -07003635 if (response == null) throw new IllegalArgumentException("response is null");
3636 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003637 long identityToken = clearCallingIdentity();
3638 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003639 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003640 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003641 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003642 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003643 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003644 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003645 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003646 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003647 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003648 protected String toDebugString(long now) {
3649 return super.toDebugString(now) + ", confirmCredentials"
3650 + ", " + account;
3651 }
3652 }.bind();
3653 } finally {
3654 restoreCallingIdentity(identityToken);
3655 }
Fred Quintana60307342009-03-24 22:48:12 -07003656 }
3657
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003658 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003659 public void updateCredentials(IAccountManagerResponse response, final Account account,
3660 final String authTokenType, final boolean expectActivityLaunch,
3661 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003662 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3664 Log.v(TAG, "updateCredentials: " + account
3665 + ", response " + response
3666 + ", authTokenType " + authTokenType
3667 + ", expectActivityLaunch " + expectActivityLaunch
3668 + ", caller's uid " + Binder.getCallingUid()
3669 + ", pid " + Binder.getCallingPid());
3670 }
Fred Quintana382601f2010-03-25 12:25:10 -07003671 if (response == null) throw new IllegalArgumentException("response is null");
3672 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003673 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003674 long identityToken = clearCallingIdentity();
3675 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003676 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003677 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003678 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003679 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003680 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003681 public void run() throws RemoteException {
3682 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3683 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003684 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003685 protected String toDebugString(long now) {
3686 if (loginOptions != null) loginOptions.keySet();
3687 return super.toDebugString(now) + ", updateCredentials"
3688 + ", " + account
3689 + ", authTokenType " + authTokenType
3690 + ", loginOptions " + loginOptions;
3691 }
3692 }.bind();
3693 } finally {
3694 restoreCallingIdentity(identityToken);
3695 }
Fred Quintana60307342009-03-24 22:48:12 -07003696 }
3697
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003698 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003699 public void startUpdateCredentialsSession(
3700 IAccountManagerResponse response,
3701 final Account account,
3702 final String authTokenType,
3703 final boolean expectActivityLaunch,
3704 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003705 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003706 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3707 Log.v(TAG,
3708 "startUpdateCredentialsSession: " + account + ", response " + response
3709 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3710 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3711 + ", pid " + Binder.getCallingPid());
3712 }
3713 if (response == null) {
3714 throw new IllegalArgumentException("response is null");
3715 }
3716 if (account == null) {
3717 throw new IllegalArgumentException("account is null");
3718 }
Sandra Kwana578d112015-12-16 16:01:43 -08003719
3720 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003721 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003722
3723 // Check to see if the Password should be included to the caller.
3724 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3725 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003726 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003727
Sandra Kwane68c37e2015-11-12 17:11:49 -08003728 long identityToken = clearCallingIdentity();
3729 try {
3730 UserAccounts accounts = getUserAccounts(userId);
3731 new StartAccountSession(
3732 accounts,
3733 response,
3734 account.type,
3735 expectActivityLaunch,
3736 account.name,
3737 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003738 true /* updateLastCredentialTime */,
3739 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003740 @Override
3741 public void run() throws RemoteException {
3742 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3743 loginOptions);
3744 }
3745
3746 @Override
3747 protected String toDebugString(long now) {
3748 if (loginOptions != null)
3749 loginOptions.keySet();
3750 return super.toDebugString(now)
3751 + ", startUpdateCredentialsSession"
3752 + ", " + account
3753 + ", authTokenType " + authTokenType
3754 + ", loginOptions " + loginOptions;
3755 }
3756 }.bind();
3757 } finally {
3758 restoreCallingIdentity(identityToken);
3759 }
3760 }
3761
3762 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003763 public void isCredentialsUpdateSuggested(
3764 IAccountManagerResponse response,
3765 final Account account,
3766 final String statusToken) {
3767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3768 Log.v(TAG,
3769 "isCredentialsUpdateSuggested: " + account + ", response " + response
3770 + ", caller's uid " + Binder.getCallingUid()
3771 + ", pid " + Binder.getCallingPid());
3772 }
3773 if (response == null) {
3774 throw new IllegalArgumentException("response is null");
3775 }
3776 if (account == null) {
3777 throw new IllegalArgumentException("account is null");
3778 }
3779 if (TextUtils.isEmpty(statusToken)) {
3780 throw new IllegalArgumentException("status token is empty");
3781 }
3782
Sandra Kwan390c9d22016-01-12 14:13:37 -08003783 int usrId = UserHandle.getCallingUserId();
3784 long identityToken = clearCallingIdentity();
3785 try {
3786 UserAccounts accounts = getUserAccounts(usrId);
3787 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3788 false /* stripAuthTokenFromResult */, account.name,
3789 false /* authDetailsRequired */) {
3790 @Override
3791 protected String toDebugString(long now) {
3792 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3793 + ", " + account;
3794 }
3795
3796 @Override
3797 public void run() throws RemoteException {
3798 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3799 }
3800
3801 @Override
3802 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003803 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003804 IAccountManagerResponse response = getResponseAndClose();
3805 if (response == null) {
3806 return;
3807 }
3808
3809 if (result == null) {
3810 sendErrorResponse(
3811 response,
3812 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3813 "null bundle");
3814 return;
3815 }
3816
3817 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3818 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3819 + response);
3820 }
3821 // Check to see if an error occurred. We know if an error occurred because all
3822 // error codes are greater than 0.
3823 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3824 sendErrorResponse(response,
3825 result.getInt(AccountManager.KEY_ERROR_CODE),
3826 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3827 return;
3828 }
3829 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3830 sendErrorResponse(
3831 response,
3832 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3833 "no result in response");
3834 return;
3835 }
3836 final Bundle newResult = new Bundle();
3837 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3838 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3839 sendResponse(response, newResult);
3840 }
3841 }.bind();
3842 } finally {
3843 restoreCallingIdentity(identityToken);
3844 }
3845 }
3846
3847 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003848 public void editProperties(IAccountManagerResponse response, final String accountType,
3849 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003850 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3852 Log.v(TAG, "editProperties: accountType " + accountType
3853 + ", response " + response
3854 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003855 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003856 + ", pid " + Binder.getCallingPid());
3857 }
Fred Quintana382601f2010-03-25 12:25:10 -07003858 if (response == null) throw new IllegalArgumentException("response is null");
3859 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003860 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003861 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3862 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003863 String msg = String.format(
3864 "uid %s cannot edit authenticator properites for account type: %s",
3865 callingUid,
3866 accountType);
3867 throw new SecurityException(msg);
3868 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003869 long identityToken = clearCallingIdentity();
3870 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003871 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003872 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003873 true /* stripAuthTokenFromResult */, null /* accountName */,
3874 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003875 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003876 public void run() throws RemoteException {
3877 mAuthenticator.editProperties(this, mAccountType);
3878 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003879 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003880 protected String toDebugString(long now) {
3881 return super.toDebugString(now) + ", editProperties"
3882 + ", accountType " + accountType;
3883 }
3884 }.bind();
3885 } finally {
3886 restoreCallingIdentity(identityToken);
3887 }
Fred Quintana60307342009-03-24 22:48:12 -07003888 }
3889
Amith Yamasani12747872015-12-07 14:19:49 -08003890 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003891 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3892 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003893 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003894 throw new SecurityException("Can be called only by system UID");
3895 }
3896 Preconditions.checkNotNull(account, "account cannot be null");
3897 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3898 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3899
3900 final int userId = userHandle.getIdentifier();
3901
3902 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3903
3904 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003905 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003906 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003907 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003908 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003909 return false;
3910 }
3911 }
3912
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003913 // Returns package with oldest target SDK for given UID.
3914 private String getPackageNameForUid(int uid) {
3915 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3916 if (ArrayUtils.isEmpty(packageNames)) {
3917 return null;
3918 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003919 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003920 if (packageNames.length == 1) {
3921 return packageName;
3922 }
3923 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003924 int oldestVersion = Integer.MAX_VALUE;
3925 for (String name : packageNames) {
3926 try {
3927 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3928 if (applicationInfo != null) {
3929 int version = applicationInfo.targetSdkVersion;
3930 if (version < oldestVersion) {
3931 oldestVersion = version;
3932 packageName = name;
3933 }
3934 }
3935 } catch (NameNotFoundException e) {
3936 // skip
3937 }
3938 }
3939 return packageName;
3940 }
3941
Svet Ganovf6d424f12016-09-20 20:18:53 -07003942 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3943 int uid) {
3944 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003945 packageName = getPackageNameForUid(uid);
3946 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003947 return false;
3948 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003949 }
3950
3951 // Use null token which means any token. Having a token means the package
3952 // is trusted by the authenticator, hence it is fine to access the account.
3953 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3954 return true;
3955 }
3956 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003957 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003958
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003959 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003960 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003961 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003962 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003963 }
3964
3965 @Override
3966 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3967 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003968 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003969 throw new SecurityException("Can be called only by system UID");
3970 }
3971
3972 Preconditions.checkNotNull(account, "account cannot be null");
3973 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3974 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3975
3976 final int userId = userHandle.getIdentifier();
3977
3978 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3979
3980 final int uid;
3981 try {
3982 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3983 } catch (NameNotFoundException e) {
3984 Slog.e(TAG, "Unknown package " + packageName);
3985 return null;
3986 }
3987
3988 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3989
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003990 final long identity = Binder.clearCallingIdentity();
3991 try {
3992 return PendingIntent.getActivityAsUser(
3993 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3994 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3995 null, new UserHandle(userId)).getIntentSender();
3996 } finally {
3997 Binder.restoreCallingIdentity(identity);
3998 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003999 }
4000
4001 private Intent newRequestAccountAccessIntent(Account account, String packageName,
4002 int uid, RemoteCallback callback) {
4003 return newGrantCredentialsPermissionIntent(account, packageName, uid,
4004 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
4005 @Override
4006 public void onResult(Bundle value) throws RemoteException {
4007 handleAuthenticatorResponse(true);
4008 }
4009
4010 @Override
4011 public void onRequestContinued() {
4012 /* ignore */
4013 }
4014
4015 @Override
4016 public void onError(int errorCode, String errorMessage) throws RemoteException {
4017 handleAuthenticatorResponse(false);
4018 }
4019
4020 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4021 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004022 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004023 UserHandle.getUserHandleForUid(uid));
4024 if (callback != null) {
4025 Bundle result = new Bundle();
4026 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4027 callback.sendResult(result);
4028 }
4029 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004030 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004031 }
4032
4033 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004034 public boolean someUserHasAccount(@NonNull final Account account) {
4035 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4036 throw new SecurityException("Only system can check for accounts across users");
4037 }
4038 final long token = Binder.clearCallingIdentity();
4039 try {
4040 AccountAndUser[] allAccounts = getAllAccounts();
4041 for (int i = allAccounts.length - 1; i >= 0; i--) {
4042 if (allAccounts[i].account.equals(account)) {
4043 return true;
4044 }
4045 }
4046 return false;
4047 } finally {
4048 Binder.restoreCallingIdentity(token);
4049 }
4050 }
4051
Fred Quintana33269202009-04-20 16:05:10 -07004052 private class GetAccountsByTypeAndFeatureSession extends Session {
4053 private final String[] mFeatures;
4054 private volatile Account[] mAccountsOfType = null;
4055 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4056 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004057 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004058 private final String mPackageName;
sunjianf29d5492017-05-11 15:42:31 -07004059 private final boolean mIncludeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004060
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004061 public GetAccountsByTypeAndFeatureSession(
4062 UserAccounts accounts,
4063 IAccountManagerResponse response,
4064 String type,
4065 String[] features,
4066 int callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004067 String packageName,
4068 boolean includeManagedNotVisible) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004069 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004070 true /* stripAuthTokenFromResult */, null /* accountName */,
4071 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004072 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004073 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004074 mPackageName = packageName;
sunjianf29d5492017-05-11 15:42:31 -07004075 mIncludeManagedNotVisible = includeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004076 }
4077
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004078 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004079 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004080 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
sunjianf29d5492017-05-11 15:42:31 -07004081 mCallingUid, mPackageName, mIncludeManagedNotVisible);
Fred Quintana33269202009-04-20 16:05:10 -07004082 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004083 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004084 mCurrentAccount = 0;
4085
4086 checkAccount();
4087 }
4088
4089 public void checkAccount() {
4090 if (mCurrentAccount >= mAccountsOfType.length) {
4091 sendResult();
4092 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004093 }
Fred Quintana33269202009-04-20 16:05:10 -07004094
Fred Quintana29e94b82010-03-10 12:11:51 -08004095 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4096 if (accountAuthenticator == null) {
4097 // It is possible that the authenticator has died, which is indicated by
4098 // mAuthenticator being set to null. If this happens then just abort.
4099 // There is no need to send back a result or error in this case since
4100 // that already happened when mAuthenticator was cleared.
4101 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4102 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4103 + " connected to the authenticator, " + toDebugString());
4104 }
4105 return;
4106 }
Fred Quintana33269202009-04-20 16:05:10 -07004107 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004108 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004109 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004110 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004111 }
4112 }
4113
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004114 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004115 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004116 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004117 mNumResults++;
4118 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004119 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004120 return;
4121 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004122 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004123 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4124 }
4125 mCurrentAccount++;
4126 checkAccount();
4127 }
4128
4129 public void sendResult() {
4130 IAccountManagerResponse response = getResponseAndClose();
4131 if (response != null) {
4132 try {
4133 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4134 for (int i = 0; i < accounts.length; i++) {
4135 accounts[i] = mAccountsWithFeatures.get(i);
4136 }
Fred Quintana56285a62010-12-02 14:20:51 -08004137 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4138 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4139 + response);
4140 }
Fred Quintana33269202009-04-20 16:05:10 -07004141 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004142 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004143 response.onResult(result);
4144 } catch (RemoteException e) {
4145 // if the caller is dead then there is no one to care about remote exceptions
4146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4147 Log.v(TAG, "failure while notifying response", e);
4148 }
4149 }
4150 }
4151 }
4152
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004153 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004154 protected String toDebugString(long now) {
4155 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4156 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4157 }
4158 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004159
Amith Yamasani04e0d262012-02-14 11:50:53 -08004160 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004161 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004162 * @hide
4163 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004164 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004165 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004166 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004167 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004168 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4169 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004170 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004171 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004172 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004173 long identityToken = clearCallingIdentity();
4174 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004175 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004176 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004177 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004178 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004179 opPackageName,
4180 visibleAccountTypes,
4181 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004182 } finally {
4183 restoreCallingIdentity(identityToken);
4184 }
4185 }
4186
Amith Yamasanif29f2362012-04-05 18:29:52 -07004187 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004188 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004189 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004190 * @hide
4191 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004192 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004193 public AccountAndUser[] getRunningAccounts() {
4194 final int[] runningUserIds;
4195 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004196 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004197 } catch (RemoteException e) {
4198 // Running in system_server; should never happen
4199 throw new RuntimeException(e);
4200 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004201 return getAccounts(runningUserIds);
4202 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004203
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004204 /**
4205 * Returns accounts for all users, ignores visibility values.
4206 *
4207 * @hide
4208 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004209 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004210 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004211 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004212 final int[] userIds = new int[users.size()];
4213 for (int i = 0; i < userIds.length; i++) {
4214 userIds[i] = users.get(i).id;
4215 }
4216 return getAccounts(userIds);
4217 }
4218
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004219 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004220 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004221 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004222 for (int userId : userIds) {
4223 UserAccounts userAccounts = getUserAccounts(userId);
4224 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004225 Account[] accounts = getAccountsFromCache(
4226 userAccounts,
4227 null /* type */,
4228 Binder.getCallingUid(),
4229 null /* packageName */,
4230 false /* include managed not visible*/);
4231 for (Account account : accounts) {
4232 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004233 }
4234 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004235
4236 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4237 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004238 }
4239
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004240 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004241 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004242 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004243 int callingUid = Binder.getCallingUid();
4244 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004245 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004246 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004247 }
4248
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004249 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004250 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004251 String type,
4252 int userId,
4253 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004254 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004255 String opPackageName,
4256 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004257 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004258 // Only allow the system process to read accounts of other users
4259 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004260 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004261 && mContext.checkCallingOrSelfPermission(
4262 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4263 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004264 throw new SecurityException("User " + UserHandle.getCallingUserId()
4265 + " trying to get account for " + userId);
4266 }
4267
Fred Quintana56285a62010-12-02 14:20:51 -08004268 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4269 Log.v(TAG, "getAccounts: accountType " + type
4270 + ", caller's uid " + Binder.getCallingUid()
4271 + ", pid " + Binder.getCallingPid());
4272 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004273
4274 // If the original calling app was using account choosing activity
4275 // provided by the framework or authenticator we'll passing in
4276 // the original caller's uid here, which is what should be used for filtering.
4277 List<String> managedTypes =
4278 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4279 if (packageUid != -1 &&
4280 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4281 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004282 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004283 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004284 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004285 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4286 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004287 if (visibleAccountTypes.isEmpty()
4288 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004289 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004290 } else if (visibleAccountTypes.contains(type)) {
4291 // Prune the list down to just the requested type.
4292 visibleAccountTypes = new ArrayList<>();
4293 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004294 } // else aggregate all the visible accounts (it won't matter if the
4295 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004296
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004297 long identityToken = clearCallingIdentity();
4298 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004299 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004300 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004301 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004302 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004303 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004304 visibleAccountTypes,
4305 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004306 } finally {
4307 restoreCallingIdentity(identityToken);
4308 }
4309 }
4310
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004311 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004312 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004313 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004314 int callingUid,
4315 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004316 List<String> visibleAccountTypes,
4317 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004318 ArrayList<Account> visibleAccounts = new ArrayList<>();
4319 for (String visibleType : visibleAccountTypes) {
4320 Account[] accountsForType = getAccountsFromCache(
4321 userAccounts, visibleType, callingUid, callingPackage,
4322 includeUserManagedNotVisible);
4323 if (accountsForType != null) {
4324 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004325 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004326 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004327 Account[] result = new Account[visibleAccounts.size()];
4328 for (int i = 0; i < visibleAccounts.size(); i++) {
4329 result[i] = visibleAccounts.get(i);
4330 }
4331 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004332 }
4333
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004334 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004335 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4336 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004337 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004338 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004339 for (Account account : accounts) {
4340 addSharedAccountAsUser(account, userId);
4341 }
4342 }
4343
4344 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004345 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004346 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004347 accounts.accountsDb.deleteSharedAccount(account);
4348 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004349 if (accountId < 0) {
4350 Log.w(TAG, "insertAccountIntoDatabase: " + account
4351 + ", skipping the DB insert failed");
4352 return false;
4353 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004354 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4355 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004356 return true;
4357 }
4358
4359 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004360 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4361 userId = handleIncomingUser(userId);
4362 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004363 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4364 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004365 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004366 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004367 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004368 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004369 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004370 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004371 }
4372 return r > 0;
4373 }
4374
4375 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004376 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004377 return removeSharedAccountAsUser(account, userId, getCallingUid());
4378 }
4379
4380 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004381 userId = handleIncomingUser(userId);
4382 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004383 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4384 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004385 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004386 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004387 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004388 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004389 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004390 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004391 }
4392
4393 @Override
4394 public Account[] getSharedAccountsAsUser(int userId) {
4395 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004396 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004397 synchronized (accounts.dbLock) {
4398 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4399 Account[] accountArray = new Account[accountList.size()];
4400 accountList.toArray(accountArray);
4401 return accountArray;
4402 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004403 }
4404
4405 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004406 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004407 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004408 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004409 }
4410
Amith Yamasani27db4682013-03-30 17:07:47 -07004411 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004412 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004413 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004414 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004415 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004416 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004417 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4418 + callingUid + " with uid=" + uid);
4419 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004420 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004421 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004422 }
4423
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004424 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004425 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004426 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4427 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004428 int callingUid = Binder.getCallingUid();
4429 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004430 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004431 int packageUid = -1;
4432 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004433 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4434 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004435 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004436 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004437 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004438 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004439 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4440 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004441 }
sunjiand62dc392017-06-01 12:05:59 -07004442 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && type == null) {
4443 return getAccountsAsUserForPackage(type, userId,
4444 packageName, packageUid, opPackageName, false /* includeUserManagedNotVisible */);
4445 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004446 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004447 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004448 }
4449
sunjianf29d5492017-05-11 15:42:31 -07004450 private boolean needToStartChooseAccountActivity(Account[] accounts, String callingPackage) {
4451 if (accounts.length < 1) return false;
4452 if (accounts.length > 1) return true;
4453 Account account = accounts[0];
4454 UserAccounts userAccounts = getUserAccounts(UserHandle.getCallingUserId());
4455 int visibility = resolveAccountVisibility(account, callingPackage, userAccounts);
4456 if (visibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) return true;
4457 return false;
4458 }
4459
4460 private void startChooseAccountActivityWithAccounts(
sunjianbdabd402017-06-06 17:54:07 -07004461 IAccountManagerResponse response, Account[] accounts, String callingPackage) {
sunjianf29d5492017-05-11 15:42:31 -07004462 Intent intent = new Intent(mContext, ChooseAccountActivity.class);
4463 intent.putExtra(AccountManager.KEY_ACCOUNTS, accounts);
4464 intent.putExtra(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE,
4465 new AccountManagerResponse(response));
sunjianbdabd402017-06-06 17:54:07 -07004466 intent.putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004467
4468 mContext.startActivityAsUser(intent, UserHandle.of(UserHandle.getCallingUserId()));
4469 }
4470
4471 private void handleGetAccountsResult(
4472 IAccountManagerResponse response,
4473 Account[] accounts,
4474 String callingPackage) {
4475
4476 if (needToStartChooseAccountActivity(accounts, callingPackage)) {
sunjianbdabd402017-06-06 17:54:07 -07004477 startChooseAccountActivityWithAccounts(response, accounts, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004478 return;
4479 }
4480 if (accounts.length == 1) {
4481 Bundle bundle = new Bundle();
4482 bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accounts[0].name);
4483 bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accounts[0].type);
4484 onResult(response, bundle);
4485 return;
4486 }
4487 // No qualified account exists, return an empty Bundle.
4488 onResult(response, new Bundle());
4489 }
4490
4491 @Override
4492 public void getAccountByTypeAndFeatures(
4493 IAccountManagerResponse response,
4494 String accountType,
4495 String[] features,
4496 String opPackageName) {
4497
4498 int callingUid = Binder.getCallingUid();
4499 mAppOpsManager.checkPackage(callingUid, opPackageName);
4500 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4501 Log.v(TAG, "getAccount: accountType " + accountType
4502 + ", response " + response
4503 + ", features " + Arrays.toString(features)
4504 + ", caller's uid " + callingUid
4505 + ", pid " + Binder.getCallingPid());
4506 }
4507 if (response == null) throw new IllegalArgumentException("response is null");
4508 if (accountType == null) throw new IllegalArgumentException("accountType is null");
4509
4510 int userId = UserHandle.getCallingUserId();
4511
4512 long identityToken = clearCallingIdentity();
4513 try {
4514 UserAccounts userAccounts = getUserAccounts(userId);
4515 if (ArrayUtils.isEmpty(features)) {
4516 Account[] accountsWithManagedNotVisible = getAccountsFromCache(
4517 userAccounts, accountType, callingUid, opPackageName,
4518 true /* include managed not visible */);
4519 handleGetAccountsResult(
4520 response, accountsWithManagedNotVisible, opPackageName);
4521 return;
4522 }
4523
4524 IAccountManagerResponse retrieveAccountsResponse =
4525 new IAccountManagerResponse.Stub() {
4526 @Override
4527 public void onResult(Bundle value) throws RemoteException {
4528 Parcelable[] parcelables = value.getParcelableArray(
4529 AccountManager.KEY_ACCOUNTS);
4530 Account[] accounts = new Account[parcelables.length];
4531 for (int i = 0; i < parcelables.length; i++) {
4532 accounts[i] = (Account) parcelables[i];
4533 }
4534 handleGetAccountsResult(
4535 response, accounts, opPackageName);
4536 }
4537
4538 @Override
4539 public void onError(int errorCode, String errorMessage)
4540 throws RemoteException {
4541 // Will not be called in this case.
4542 }
4543 };
4544 new GetAccountsByTypeAndFeatureSession(
4545 userAccounts,
4546 retrieveAccountsResponse,
4547 accountType,
4548 features,
4549 callingUid,
4550 opPackageName,
4551 true /* include managed not visible */).bind();
4552 } finally {
4553 restoreCallingIdentity(identityToken);
4554 }
4555 }
4556
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004557 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004558 public void getAccountsByFeatures(
4559 IAccountManagerResponse response,
4560 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004561 String[] features,
4562 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004563 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004564 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004565 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4566 Log.v(TAG, "getAccounts: accountType " + type
4567 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004568 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004569 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004570 + ", pid " + Binder.getCallingPid());
4571 }
Fred Quintana382601f2010-03-25 12:25:10 -07004572 if (response == null) throw new IllegalArgumentException("response is null");
4573 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004574 int userId = UserHandle.getCallingUserId();
4575
Svetoslavf3f02ac2015-09-08 14:36:35 -07004576 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4577 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004578 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004579 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004580 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004581 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004582 try {
4583 response.onResult(result);
4584 } catch (RemoteException e) {
4585 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4586 }
4587 return;
4588 }
sunjianf29d5492017-05-11 15:42:31 -07004589
Fred Quintana33269202009-04-20 16:05:10 -07004590 long identityToken = clearCallingIdentity();
4591 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004592 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004593 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004594 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4595 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004596 Bundle result = new Bundle();
4597 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4598 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004599 return;
4600 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004601 new GetAccountsByTypeAndFeatureSession(
4602 userAccounts,
4603 response,
4604 type,
4605 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004606 callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004607 opPackageName,
4608 false /* include managed not visible */).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004609 } finally {
4610 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004611 }
4612 }
4613
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004614 @Override
4615 public void onAccountAccessed(String token) throws RemoteException {
4616 final int uid = Binder.getCallingUid();
4617 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4618 return;
4619 }
4620 final int userId = UserHandle.getCallingUserId();
4621 final long identity = Binder.clearCallingIdentity();
4622 try {
4623 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4624 if (Objects.equals(account.getAccessId(), token)) {
4625 // An app just accessed the account. At this point it knows about
4626 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004627 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004628 if (!hasAccountAccess(account, null, uid)) {
4629 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4630 uid, true);
4631 }
4632 }
4633 }
4634 } finally {
4635 Binder.restoreCallingIdentity(identity);
4636 }
4637 }
4638
Fred Quintanaa698f422009-04-08 19:14:54 -07004639 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004640 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004641 IAccountManagerResponse mResponse;
4642 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004643 final boolean mExpectActivityLaunch;
4644 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004645 final String mAccountName;
4646 // Indicates if we need to add auth details(like last credential time)
4647 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004648 // If set, we need to update the last authenticated time. This is
4649 // currently
4650 // used on
4651 // successful confirming credentials.
4652 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004653
Fred Quintana33269202009-04-20 16:05:10 -07004654 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004655 private int mNumRequestContinued = 0;
4656 private int mNumErrors = 0;
4657
Fred Quintana60307342009-03-24 22:48:12 -07004658 IAccountAuthenticator mAuthenticator = null;
4659
Fred Quintana8570f742010-02-18 10:32:54 -08004660 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004661 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004662
Amith Yamasani04e0d262012-02-14 11:50:53 -08004663 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004664 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4665 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004666 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4667 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4668 }
4669
4670 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4671 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4672 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004673 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004674 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004675 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004676 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004677 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004678 mResponse = response;
4679 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004680 mExpectActivityLaunch = expectActivityLaunch;
4681 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004682 mAccountName = accountName;
4683 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004684 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004685
Fred Quintanaa698f422009-04-08 19:14:54 -07004686 synchronized (mSessions) {
4687 mSessions.put(toString(), this);
4688 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004689 if (response != null) {
4690 try {
4691 response.asBinder().linkToDeath(this, 0 /* flags */);
4692 } catch (RemoteException e) {
4693 mResponse = null;
4694 binderDied();
4695 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004696 }
Fred Quintana60307342009-03-24 22:48:12 -07004697 }
4698
Fred Quintanaa698f422009-04-08 19:14:54 -07004699 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004700 if (mResponse == null) {
4701 // this session has already been closed
4702 return null;
4703 }
Fred Quintana60307342009-03-24 22:48:12 -07004704 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004705 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004706 return response;
4707 }
4708
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004709 /**
4710 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4711 * security policy.
4712 *
4713 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004714 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004715 * supplied entries in the system Settings app.
4716 */
4717 protected void checkKeyIntent(
4718 int authUid,
4719 Intent intent) throws SecurityException {
Jeff Sharkeyd722e782017-06-12 17:33:07 -06004720 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
4721 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
4722 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4723 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004724 long bid = Binder.clearCallingIdentity();
4725 try {
4726 PackageManager pm = mContext.getPackageManager();
4727 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4728 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4729 int targetUid = targetActivityInfo.applicationInfo.uid;
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004730 if (!isExportedSystemActivity(targetActivityInfo)
4731 && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4732 targetUid))) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004733 String pkgName = targetActivityInfo.packageName;
4734 String activityName = targetActivityInfo.name;
4735 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4736 + "does not share a signature with the supplying authenticator (%s).";
4737 throw new SecurityException(
4738 String.format(tmpl, activityName, pkgName, mAccountType));
4739 }
4740 } finally {
4741 Binder.restoreCallingIdentity(bid);
4742 }
4743 }
4744
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004745 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4746 String className = activityInfo.name;
4747 return "android".equals(activityInfo.packageName) &&
4748 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4749 || CantAddAccountActivity.class.getName().equals(className));
4750 }
4751
Fred Quintanaa698f422009-04-08 19:14:54 -07004752 private void close() {
4753 synchronized (mSessions) {
4754 if (mSessions.remove(toString()) == null) {
4755 // the session was already closed, so bail out now
4756 return;
4757 }
4758 }
4759 if (mResponse != null) {
4760 // stop listening for response deaths
4761 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4762
4763 // clear this so that we don't accidentally send any further results
4764 mResponse = null;
4765 }
4766 cancelTimeout();
4767 unbind();
4768 }
4769
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004770 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004771 public void binderDied() {
4772 mResponse = null;
4773 close();
4774 }
4775
4776 protected String toDebugString() {
4777 return toDebugString(SystemClock.elapsedRealtime());
4778 }
4779
4780 protected String toDebugString(long now) {
4781 return "Session: expectLaunch " + mExpectActivityLaunch
4782 + ", connected " + (mAuthenticator != null)
4783 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4784 + "/" + mNumErrors + ")"
4785 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4786 }
4787
Fred Quintana60307342009-03-24 22:48:12 -07004788 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004789 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4790 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4791 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004792 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004793 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004794 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004795 }
4796 }
4797
4798 private void unbind() {
4799 if (mAuthenticator != null) {
4800 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004801 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004802 }
4803 }
4804
Fred Quintana60307342009-03-24 22:48:12 -07004805 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004806 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004807 }
4808
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004809 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004810 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004811 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004812 try {
4813 run();
4814 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004815 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004816 "remote exception");
4817 }
Fred Quintana60307342009-03-24 22:48:12 -07004818 }
4819
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004820 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004821 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004822 mAuthenticator = null;
4823 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004824 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004825 try {
4826 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4827 "disconnected");
4828 } catch (RemoteException e) {
4829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4830 Log.v(TAG, "Session.onServiceDisconnected: "
4831 + "caught RemoteException while responding", e);
4832 }
4833 }
Fred Quintana60307342009-03-24 22:48:12 -07004834 }
4835 }
4836
Fred Quintanab839afc2009-10-14 15:57:28 -07004837 public abstract void run() throws RemoteException;
4838
Fred Quintana60307342009-03-24 22:48:12 -07004839 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004840 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004841 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004842 try {
4843 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4844 "timeout");
4845 } catch (RemoteException e) {
4846 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4847 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4848 e);
4849 }
4850 }
Fred Quintana60307342009-03-24 22:48:12 -07004851 }
4852 }
4853
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004854 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004855 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004856 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004857 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004858 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004859 if (result != null) {
4860 boolean isSuccessfulConfirmCreds = result.getBoolean(
4861 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004862 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004863 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4864 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004865 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004866 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4867 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004868 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004869 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004870 if (needUpdate || mAuthDetailsRequired) {
4871 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4872 if (needUpdate && accountPresent) {
4873 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4874 }
4875 if (mAuthDetailsRequired) {
4876 long lastAuthenticatedTime = -1;
4877 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004878 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004879 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004880 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004881 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004882 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004883 lastAuthenticatedTime);
4884 }
4885 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004886 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004887 if (result != null
4888 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004889 checkKeyIntent(
4890 Binder.getCallingUid(),
4891 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004892 }
4893 if (result != null
4894 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004895 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4896 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004897 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4898 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004899 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4900 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004901 }
Fred Quintana60307342009-03-24 22:48:12 -07004902 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004903 IAccountManagerResponse response;
4904 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004905 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004906 response = mResponse;
4907 } else {
4908 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004909 }
Fred Quintana60307342009-03-24 22:48:12 -07004910 if (response != null) {
4911 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004912 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004913 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4914 Log.v(TAG, getClass().getSimpleName()
4915 + " calling onError() on response " + response);
4916 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004917 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004918 "null bundle returned");
4919 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004920 if (mStripAuthTokenFromResult) {
4921 result.remove(AccountManager.KEY_AUTHTOKEN);
4922 }
Fred Quintana56285a62010-12-02 14:20:51 -08004923 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4924 Log.v(TAG, getClass().getSimpleName()
4925 + " calling onResult() on response " + response);
4926 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004927 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4928 (intent == null)) {
4929 // All AccountManager error codes are greater than 0
4930 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4931 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4932 } else {
4933 response.onResult(result);
4934 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004935 }
Fred Quintana60307342009-03-24 22:48:12 -07004936 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004937 // if the caller is dead then there is no one to care about remote exceptions
4938 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4939 Log.v(TAG, "failure while notifying response", e);
4940 }
Fred Quintana60307342009-03-24 22:48:12 -07004941 }
4942 }
4943 }
Fred Quintana60307342009-03-24 22:48:12 -07004944
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004945 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004946 public void onRequestContinued() {
4947 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004948 }
4949
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004950 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004951 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004952 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004953 IAccountManagerResponse response = getResponseAndClose();
4954 if (response != null) {
4955 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004956 Log.v(TAG, getClass().getSimpleName()
4957 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004958 }
4959 try {
4960 response.onError(errorCode, errorMessage);
4961 } catch (RemoteException e) {
4962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4963 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4964 }
4965 }
4966 } else {
4967 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4968 Log.v(TAG, "Session.onError: already closed");
4969 }
Fred Quintana60307342009-03-24 22:48:12 -07004970 }
4971 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004972
4973 /**
4974 * find the component name for the authenticator and initiate a bind
4975 * if no authenticator or the bind fails then return false, otherwise return true
4976 */
4977 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004978 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4979 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4980 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004981 if (authenticatorInfo == null) {
4982 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4983 Log.v(TAG, "there is no authenticator for " + authenticatorType
4984 + ", bailing out");
4985 }
4986 return false;
4987 }
4988
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004989 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004990 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004991 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4992 + " which isn't encryption aware");
4993 return false;
4994 }
4995
Fred Quintanab839afc2009-10-14 15:57:28 -07004996 Intent intent = new Intent();
4997 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4998 intent.setComponent(authenticatorInfo.componentName);
4999 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5000 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
5001 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08005002 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005003 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07005004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5005 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
5006 }
5007 return false;
5008 }
5009
Fred Quintanab839afc2009-10-14 15:57:28 -07005010 return true;
5011 }
Fred Quintana60307342009-03-24 22:48:12 -07005012 }
5013
Svet Ganov5d09c992016-09-07 09:57:41 -07005014 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07005015 MessageHandler(Looper looper) {
5016 super(looper);
5017 }
Costin Manolache3348f142009-09-29 18:58:36 -07005018
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07005019 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005020 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07005021 switch (msg.what) {
5022 case MESSAGE_TIMED_OUT:
5023 Session session = (Session)msg.obj;
5024 session.onTimedOut();
5025 break;
5026
Amith Yamasani5be347b2013-03-31 17:44:31 -07005027 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00005028 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07005029 break;
5030
Fred Quintana60307342009-03-24 22:48:12 -07005031 default:
5032 throw new IllegalStateException("unhandled message: " + msg.what);
5033 }
5034 }
5035 }
5036
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005037 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005038 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005039 }
5040
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005041 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005042 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005043 }
5044
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005045 /*
5046 * This function receives an opened writable database.
5047 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005048 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005049 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005050 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005051 }
5052
5053 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005054 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005055 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005056 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005057 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005058
5059 class LogRecordTask implements Runnable {
5060 private final String action;
5061 private final String tableName;
5062 private final long accountId;
5063 private final UserAccounts userAccount;
5064 private final int callingUid;
5065 private final long userDebugDbInsertionPoint;
5066
5067 LogRecordTask(final String action,
5068 final String tableName,
5069 final long accountId,
5070 final UserAccounts userAccount,
5071 final int callingUid,
5072 final long userDebugDbInsertionPoint) {
5073 this.action = action;
5074 this.tableName = tableName;
5075 this.accountId = accountId;
5076 this.userAccount = userAccount;
5077 this.callingUid = callingUid;
5078 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
5079 }
5080
Andrew Scullc7770d62017-05-22 17:49:58 +01005081 @Override
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005082 public void run() {
5083 SQLiteStatement logStatement = userAccount.statementForLogging;
5084 logStatement.bindLong(1, accountId);
5085 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005086 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005087 logStatement.bindLong(4, callingUid);
5088 logStatement.bindString(5, tableName);
5089 logStatement.bindLong(6, userDebugDbInsertionPoint);
Tetsutoki Shiozawabe2d96a2017-10-24 18:44:00 +09005090 try {
5091 logStatement.execute();
5092 } catch (IllegalStateException e) {
5093 // Guard against crash, DB can already be closed
5094 // since this statement is executed on a handler thread
5095 Slog.w(TAG, "Failed to insert a log record. accountId=" + accountId
5096 + " action=" + action + " tableName=" + tableName + " Error: " + e);
5097 } finally {
5098 logStatement.clearBindings();
5099 }
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005100 }
5101 }
5102
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005103 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
5104 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005105 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005106 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005107 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005108 }
5109
5110 /*
5111 * This should only be called once to compile the sql statement for logging
5112 * and to find the insertion point.
5113 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005114 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
5115 userAccount.debugDbInsertionPoint = userAccount.accountsDb
5116 .calculateDebugTableInsertionPoint();
5117 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005118 }
5119
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005120 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005121 return asBinder();
5122 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005123
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005124 /**
5125 * Searches array of arguments for the specified string
5126 * @param args array of argument strings
5127 * @param value value to search for
5128 * @return true if the value is contained in the array
5129 */
5130 private static boolean scanArgs(String[] args, String value) {
5131 if (args != null) {
5132 for (String arg : args) {
5133 if (value.equals(arg)) {
5134 return true;
5135 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005136 }
5137 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005138 return false;
5139 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005140
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005141 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005142 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005143 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005144 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005145 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005146
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005147 final List<UserInfo> users = getUserManager().getUsers();
5148 for (UserInfo user : users) {
5149 ipw.println("User " + user + ":");
5150 ipw.increaseIndent();
5151 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5152 ipw.println();
5153 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005154 }
5155 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005156
Amith Yamasani04e0d262012-02-14 11:50:53 -08005157 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5158 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005159 if (isCheckinRequest) {
5160 // This is a checkin request. *Only* upload the account types and the count of
5161 // each.
5162 synchronized (userAccounts.dbLock) {
5163 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5164 }
5165 } else {
5166 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5167 Process.SYSTEM_UID, null /* packageName */, false);
5168 fout.println("Accounts: " + accounts.length);
5169 for (Account account : accounts) {
5170 fout.println(" " + account);
5171 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005172
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005173 // Add debug information.
5174 fout.println();
5175 synchronized (userAccounts.dbLock) {
5176 userAccounts.accountsDb.dumpDebugTable(fout);
5177 }
5178 fout.println();
5179 synchronized (mSessions) {
5180 final long now = SystemClock.elapsedRealtime();
5181 fout.println("Active Sessions: " + mSessions.size());
5182 for (Session session : mSessions.values()) {
5183 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005184 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005185 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005186
5187 fout.println();
5188 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Tony Mak6d14d772017-07-13 17:49:46 +08005189
5190 boolean isUserUnlocked;
5191 synchronized (mUsers) {
5192 isUserUnlocked = isLocalUnlockedUser(userAccounts.userId);
5193 }
5194 // Following logs are printed only when user is unlocked.
5195 if (!isUserUnlocked) {
5196 return;
5197 }
5198 fout.println();
5199 synchronized (userAccounts.dbLock) {
5200 Map<Account, Map<String, Integer>> allVisibilityValues =
5201 userAccounts.accountsDb.findAllVisibilityValues();
5202 fout.println("Account visibility:");
5203 for (Account account : allVisibilityValues.keySet()) {
5204 fout.println(" " + account.name);
5205 Map<String, Integer> visibilities = allVisibilityValues.get(account);
5206 for (Entry<String, Integer> entry : visibilities.entrySet()) {
5207 fout.println(" " + entry.getKey() + ", " + entry.getValue());
5208 }
5209 }
5210 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005211 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005212 }
5213
Amith Yamasani04e0d262012-02-14 11:50:53 -08005214 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005215 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005216 long identityToken = clearCallingIdentity();
5217 try {
5218 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5219 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5220 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005221
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005222 if (intent.getComponent() != null &&
5223 GrantCredentialsPermissionActivity.class.getName().equals(
5224 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005225 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005226 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005227 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005228 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5229 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005230
Fred Quintana33f889a2009-09-14 17:31:26 -07005231 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005232 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005233 Notification n =
5234 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005235 .setWhen(0)
5236 .setSmallIcon(android.R.drawable.stat_sys_warning)
5237 .setColor(contextForUser.getColor(
5238 com.android.internal.R.color.system_notification_accent_color))
5239 .setContentTitle(String.format(notificationTitleFormat, account.name))
5240 .setContentText(message)
5241 .setContentIntent(PendingIntent.getActivityAsUser(
5242 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005243 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005244 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005245 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005246 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005247 } finally {
5248 restoreCallingIdentity(identityToken);
5249 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005250 }
5251
Chris Wren717a8812017-03-31 15:34:39 -04005252 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005253 String packageName, int userId) {
5254 final long token = clearCallingIdentity();
5255 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005256 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005257 try {
Chris Wren717a8812017-03-31 15:34:39 -04005258 notificationManager.enqueueNotificationWithTag(packageName, packageName,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005259 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005260 } catch (RemoteException e) {
5261 /* ignore - local call */
5262 }
5263 } finally {
5264 Binder.restoreCallingIdentity(token);
5265 }
Fred Quintana56285a62010-12-02 14:20:51 -08005266 }
5267
Chris Wren717a8812017-03-31 15:34:39 -04005268 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005269 cancelNotification(id, mContext.getPackageName(), user);
5270 }
5271
Chris Wren717a8812017-03-31 15:34:39 -04005272 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005273 long identityToken = clearCallingIdentity();
5274 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005275 INotificationManager service = mInjector.getNotificationManager();
Chris Wren717a8812017-03-31 15:34:39 -04005276 service.cancelNotificationWithTag(packageName, id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005277 } catch (RemoteException e) {
5278 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005279 } finally {
5280 restoreCallingIdentity(identityToken);
5281 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005282 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005283
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005284 private boolean isPermittedForPackage(String packageName, int uid, int userId,
5285 String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005286 final long identity = Binder.clearCallingIdentity();
5287 try {
5288 IPackageManager pm = ActivityThread.getPackageManager();
5289 for (String perm : permissions) {
5290 if (pm.checkPermission(perm, packageName, userId)
5291 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005292 // Checks runtime permission revocation.
5293 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005294 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005295 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5296 return true;
5297 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005298 }
5299 }
5300 } catch (RemoteException e) {
5301 /* ignore - local call */
5302 } finally {
5303 Binder.restoreCallingIdentity(identity);
5304 }
5305 return false;
5306 }
5307
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005308 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5309 for (String perm : permissions) {
5310 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5312 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5313 }
5314 final int opCode = AppOpsManager.permissionToOpCode(perm);
Tony Mak58f28152017-09-20 21:23:48 +01005315 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005316 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5317 return true;
5318 }
5319 }
5320 }
5321 return false;
5322 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005323
Amith Yamasani67df64b2012-12-14 12:09:36 -08005324 private int handleIncomingUser(int userId) {
5325 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005326 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005327 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5328 } catch (RemoteException re) {
5329 // Shouldn't happen, local.
5330 }
5331 return userId;
5332 }
5333
Christopher Tateccbf84f2013-05-08 15:25:41 -07005334 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005335 String[] packages;
5336 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005337 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005338 packages = mPackageManager.getPackagesForUid(callingUid);
sunjian9ae597b62017-08-14 15:45:04 -07005339 if (packages == null) {
5340 Log.d(TAG, "No packages for callingUid " + callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005341 return false;
5342 }
sunjian9ae597b62017-08-14 15:45:04 -07005343 for (String name : packages) {
5344 try {
5345 PackageInfo packageInfo =
5346 mPackageManager.getPackageInfo(name, 0 /* flags */);
5347 if (packageInfo != null
5348 && (packageInfo.applicationInfo.privateFlags
5349 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5350 return true;
5351 }
5352 } catch (PackageManager.NameNotFoundException e) {
5353 Log.d(TAG, "Package not found " + e.getMessage());
5354 }
5355 }
5356 } finally {
5357 Binder.restoreCallingIdentity(identityToken);
Fred Quintana7be59642009-08-24 18:29:25 -07005358 }
5359 return false;
5360 }
5361
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005362 private boolean permissionIsGranted(
5363 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005364 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5365 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5366 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5367 }
5368 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005369 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005370
5371 if (isPrivileged(callerUid)) {
5372 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5373 Log.v(TAG, "Access to " + account + " granted calling uid "
5374 + callerUid + " privileged");
5375 }
5376 return true;
5377 }
5378 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5379 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5380 Log.v(TAG, "Access to " + account + " granted calling uid "
5381 + callerUid + " manages the account");
5382 }
5383 return true;
5384 }
5385 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5386 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5387 Log.v(TAG, "Access to " + account + " granted calling uid "
5388 + callerUid + " user granted access");
5389 }
5390 return true;
5391 }
5392
5393 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5394 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5395 }
5396
5397 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005398 }
5399
Svetoslavf3f02ac2015-09-08 14:36:35 -07005400 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5401 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005402 if (accountType == null) {
5403 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005404 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005405 return getTypesVisibleToCaller(callingUid, userId,
5406 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005407 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005408 }
5409
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005410 // Method checks visibility for applications targeing API level below {@link
5411 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005412 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005413 private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
5414 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005415 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5416 }
5417
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005418 private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
5419 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
5420 }
5421
5422 // Heuristic to check that account type may be associated with some contacts data and
5423 // therefore READ_CONTACTS permission grants the access to account by default.
5424 private boolean accountTypeManagesContacts(String accountType, int userId) {
5425 if (accountType == null) {
5426 return false;
5427 }
5428 long identityToken = Binder.clearCallingIdentity();
5429 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5430 try {
5431 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5432 } finally {
5433 Binder.restoreCallingIdentity(identityToken);
5434 }
5435 // Check contacts related permissions for authenticator.
5436 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5437 : serviceInfos) {
5438 if (accountType.equals(serviceInfo.type.type)) {
5439 return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
5440 Manifest.permission.WRITE_CONTACTS);
5441 }
5442 }
5443 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005444 }
5445
5446 /**
5447 * Method checks package uid and signature with Authenticator which manages accountType.
5448 *
5449 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5450 * SIGNATURE_CHECK_MISMATCH otherwise.
5451 */
5452 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5453 if (accountType == null) {
5454 return SIGNATURE_CHECK_MISMATCH;
5455 }
5456
5457 long identityToken = Binder.clearCallingIdentity();
5458 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5459 try {
5460 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5461 } finally {
5462 Binder.restoreCallingIdentity(identityToken);
5463 }
5464 // Check for signature match with Authenticator.
5465 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5466 : serviceInfos) {
5467 if (accountType.equals(serviceInfo.type.type)) {
5468 if (serviceInfo.uid == callingUid) {
5469 return SIGNATURE_CHECK_UID_MATCH;
5470 }
5471 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5472 if (sigChk == PackageManager.SIGNATURE_MATCH) {
5473 return SIGNATURE_CHECK_MATCH;
5474 }
5475 }
5476 }
5477 return SIGNATURE_CHECK_MISMATCH;
5478 }
5479
5480 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005481 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5482 if (accountType == null) {
5483 return false;
5484 } else {
5485 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5486 }
5487 }
5488
Svetoslavf3f02ac2015-09-08 14:36:35 -07005489 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5490 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005491 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005492 }
5493
5494 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005495 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005496 }
5497
5498 private List<String> getTypesForCaller(
5499 int callingUid, int userId, boolean isOtherwisePermitted) {
5500 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005501 long identityToken = Binder.clearCallingIdentity();
5502 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5503 try {
5504 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5505 } finally {
5506 Binder.restoreCallingIdentity(identityToken);
5507 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005508 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005509 serviceInfos) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005510 if (isOtherwisePermitted || (mPackageManager.checkSignatures(serviceInfo.uid,
5511 callingUid) == PackageManager.SIGNATURE_MATCH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005512 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005513 }
5514 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005515 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005516 }
5517
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005518 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5519 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5520 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5521 if (account.name.equals(accountName)) {
5522 return true;
5523 }
5524 }
5525 }
5526 return false;
5527 }
5528
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005529 private static void checkManageUsersPermission(String message) {
5530 if (ActivityManager.checkComponentPermission(
5531 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5532 != PackageManager.PERMISSION_GRANTED) {
5533 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5534 }
5535 }
5536
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005537 private static void checkManageOrCreateUsersPermission(String message) {
5538 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5539 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5540 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5541 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5542 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5543 + message);
5544 }
5545 }
5546
Amith Yamasani04e0d262012-02-14 11:50:53 -08005547 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5548 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005549 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005550 return true;
5551 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005552 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005553 synchronized (accounts.dbLock) {
5554 synchronized (accounts.cacheLock) {
5555 long grantsCount;
5556 if (authTokenType != null) {
5557 grantsCount = accounts.accountsDb
5558 .findMatchingGrantsCount(callerUid, authTokenType, account);
5559 } else {
5560 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5561 account);
5562 }
5563 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005564
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005565 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5566 // TODO: Skip this check when running automated tests. Replace this
5567 // with a more general solution.
5568 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5569 + authTokenType + " by uid " + callerUid
5570 + " but ignoring since device is in test harness.");
5571 return true;
5572 }
5573 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005574 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005575 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005576 }
5577
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005578 private boolean isSystemUid(int callingUid) {
5579 String[] packages = null;
5580 long ident = Binder.clearCallingIdentity();
5581 try {
5582 packages = mPackageManager.getPackagesForUid(callingUid);
5583 } finally {
5584 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005585 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005586 if (packages != null) {
5587 for (String name : packages) {
5588 try {
5589 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5590 if (packageInfo != null
5591 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5592 != 0) {
5593 return true;
5594 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005595 } catch (NameNotFoundException e) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005596 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5597 }
5598 }
5599 } else {
5600 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005601 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005602 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005603 }
5604
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005605 /** Succeeds if any of the specified permissions are granted. */
5606 private void checkReadAccountsPermitted(
5607 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005608 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005609 int userId,
5610 String opPackageName) {
5611 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005612 String msg = String.format(
5613 "caller uid %s cannot access %s accounts",
5614 callingUid,
5615 accountType);
5616 Log.w(TAG, " " + msg);
5617 throw new SecurityException(msg);
5618 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005619 }
5620
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005621 private boolean canUserModifyAccounts(int userId, int callingUid) {
5622 // the managing app can always modify accounts
5623 if (isProfileOwner(callingUid)) {
5624 return true;
5625 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005626 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5627 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5628 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005629 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005630 return true;
5631 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005632
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005633 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5634 // the managing app can always modify accounts
5635 if (isProfileOwner(callingUid)) {
5636 return true;
5637 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005638 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5639 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005640 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005641 if (typesArray == null) {
5642 return true;
5643 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005644 for (String forbiddenType : typesArray) {
5645 if (forbiddenType.equals(accountType)) {
5646 return false;
5647 }
5648 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005649 return true;
5650 }
5651
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005652 private boolean isProfileOwner(int uid) {
5653 final DevicePolicyManagerInternal dpmi =
5654 LocalServices.getService(DevicePolicyManagerInternal.class);
5655 return (dpmi != null)
5656 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5657 }
5658
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005659 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005660 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5661 throws RemoteException {
5662 final int callingUid = getCallingUid();
5663
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005664 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005665 throw new SecurityException();
5666 }
5667
5668 if (value) {
5669 grantAppPermission(account, authTokenType, uid);
5670 } else {
5671 revokeAppPermission(account, authTokenType, uid);
5672 }
5673 }
5674
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005675 /**
5676 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5677 * <p>
5678 * Although this is public it can only be accessed via the AccountManagerService object
5679 * which is in the system. This means we don't need to protect it with permissions.
5680 * @hide
5681 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005682 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005683 if (account == null || authTokenType == null) {
5684 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005685 return;
5686 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005687 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005688 synchronized (accounts.dbLock) {
5689 synchronized (accounts.cacheLock) {
5690 long accountId = accounts.accountsDb.findDeAccountId(account);
5691 if (accountId >= 0) {
5692 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5693 }
5694 cancelNotification(
5695 getCredentialPermissionNotificationId(account, authTokenType, uid),
5696 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005697
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005698 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5699 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005700 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005701
5702 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5703 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5704 : mAppPermissionChangeListeners) {
5705 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5706 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005707 }
5708
5709 /**
5710 * Don't allow callers with the given uid permission to get credentials for
5711 * account/authTokenType.
5712 * <p>
5713 * Although this is public it can only be accessed via the AccountManagerService object
5714 * which is in the system. This means we don't need to protect it with permissions.
5715 * @hide
5716 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005717 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005718 if (account == null || authTokenType == null) {
5719 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005720 return;
5721 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005722 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005723 synchronized (accounts.dbLock) {
5724 synchronized (accounts.cacheLock) {
5725 accounts.accountsDb.beginTransaction();
5726 try {
5727 long accountId = accounts.accountsDb.findDeAccountId(account);
5728 if (accountId >= 0) {
5729 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5730 accountId, authTokenType, uid);
5731 accounts.accountsDb.setTransactionSuccessful();
5732 }
5733 } finally {
5734 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005735 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005736
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005737 cancelNotification(
5738 getCredentialPermissionNotificationId(account, authTokenType, uid),
5739 UserHandle.of(accounts.userId));
5740 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005741 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005742
5743 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5744 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5745 : mAppPermissionChangeListeners) {
5746 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5747 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005748 }
Fred Quintana56285a62010-12-02 14:20:51 -08005749
Amith Yamasani04e0d262012-02-14 11:50:53 -08005750 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5751 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005752 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005753 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005754 for (Account curAccount : oldAccountsForType) {
5755 if (!curAccount.equals(account)) {
5756 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005757 }
5758 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005759 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005760 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005761 } else {
5762 Account[] newAccountsForType = new Account[newAccountsList.size()];
5763 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005764 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005765 }
Fred Quintana56285a62010-12-02 14:20:51 -08005766 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005767 accounts.userDataCache.remove(account);
5768 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005769 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005770 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005771 }
5772
5773 /**
5774 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005775 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5776 * processes and if you will return this account to apps you should return the result.
5777 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005778 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005779 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005780 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005781 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5782 Account[] newAccountsForType = new Account[oldLength + 1];
5783 if (accountsForType != null) {
5784 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005785 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005786 String token = account.getAccessId() != null ? account.getAccessId()
5787 : UUID.randomUUID().toString();
5788 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005789 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005790 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005791 }
5792
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005793 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005794 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005795 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005796 String visibilityFilterPackage = callingPackage;
5797 if (visibilityFilterPackage == null) {
5798 visibilityFilterPackage = getPackageNameForUid(callingUid);
5799 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005800 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005801 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005802 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005803 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5804 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5805 || (includeManagedNotVisible
5806 && (visibility
5807 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5808 firstPass.put(account, visibility);
5809 }
5810 }
5811 Map<Account, Integer> secondPass =
5812 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5813
5814 Account[] filtered = new Account[secondPass.size()];
5815 filtered = secondPass.keySet().toArray(filtered);
5816 return filtered;
5817 }
5818
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005819 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005820 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005821 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005822 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005823 // first part is to filter shared accounts.
5824 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005825 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005826 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005827 return unfiltered;
5828 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005829 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005830 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005831 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005832 if (packages == null) {
5833 packages = new String[] {};
5834 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005835 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005836 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005837 // This might be a temporary way to specify a visible list
5838 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005839 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5840 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005841 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005842 return unfiltered;
5843 }
5844 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005845 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005846 if (ArrayUtils.isEmpty(sharedAccounts)) {
5847 return unfiltered;
5848 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005849 String requiredAccountType = "";
5850 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005851 // If there's an explicit callingPackage specified, check if that package
5852 // opted in to see restricted accounts.
5853 if (callingPackage != null) {
5854 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005855 if (pi != null && pi.restrictedAccountType != null) {
5856 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005857 }
5858 } else {
5859 // Otherwise check if the callingUid has a package that has opted in
5860 for (String packageName : packages) {
5861 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5862 if (pi != null && pi.restrictedAccountType != null) {
5863 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005864 break;
5865 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005866 }
5867 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005868 } catch (NameNotFoundException e) {
5869 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005870 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005871 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005872 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5873 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005874 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005875 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005876 } else {
5877 boolean found = false;
5878 for (Account shared : sharedAccounts) {
5879 if (shared.equals(account)) {
5880 found = true;
5881 break;
5882 }
5883 }
5884 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005885 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005886 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005887 }
5888 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005889 return filtered;
5890 } else {
5891 return unfiltered;
5892 }
5893 }
5894
Amith Yamasani27db4682013-03-30 17:07:47 -07005895 /*
5896 * packageName can be null. If not null, it should be used to filter out restricted accounts
5897 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005898 *
5899 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5900 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005901 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005902 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005903 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005904 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005905 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5906 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005907 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005908 Account[] accounts;
5909 synchronized (userAccounts.cacheLock) {
5910 accounts = userAccounts.accountCache.get(accountType);
5911 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005912 if (accounts == null) {
5913 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005914 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005915 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5916 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005917 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005918 } else {
5919 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005920 Account[] accountsArray;
5921 synchronized (userAccounts.cacheLock) {
5922 for (Account[] accounts : userAccounts.accountCache.values()) {
5923 totalLength += accounts.length;
5924 }
5925 if (totalLength == 0) {
5926 return EMPTY_ACCOUNT_ARRAY;
5927 }
5928 accountsArray = new Account[totalLength];
5929 totalLength = 0;
5930 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5931 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5932 accountsOfType.length);
5933 totalLength += accountsOfType.length;
5934 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005935 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005936 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005937 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005938 }
5939 }
5940
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005941 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005942 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005943 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005944 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005945 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005946 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005947 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005948 }
5949 if (value == null) {
5950 userDataForAccount.remove(key);
5951 } else {
5952 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005953 }
5954 }
5955
Carlos Valdivia91979be2015-05-22 14:11:35 -07005956 protected String readCachedTokenInternal(
5957 UserAccounts accounts,
5958 Account account,
5959 String tokenType,
5960 String callingPackage,
5961 byte[] pkgSigDigest) {
Dmitry Dementyev18f0ca92017-06-12 17:56:47 -07005962 synchronized (accounts.cacheLock) {
5963 return accounts.accountTokenCaches.get(
5964 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005965 }
5966 }
5967
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005968 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005969 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005970 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005971 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005972 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005973 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005974 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005975 }
5976 if (value == null) {
5977 authTokensForAccount.remove(key);
5978 } else {
5979 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005980 }
5981 }
5982
Amith Yamasani04e0d262012-02-14 11:50:53 -08005983 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5984 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005985 // Fast path - check if account is already cached
5986 synchronized (accounts.cacheLock) {
5987 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5988 if (authTokensForAccount != null) {
5989 return authTokensForAccount.get(authTokenType);
5990 }
5991 }
5992 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005993 synchronized (accounts.dbLock) {
5994 synchronized (accounts.cacheLock) {
5995 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5996 if (authTokensForAccount == null) {
5997 // need to populate the cache for this account
5998 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
5999 accounts.authTokenCache.put(account, authTokensForAccount);
6000 }
6001 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08006002 }
Fred Quintana56285a62010-12-02 14:20:51 -08006003 }
6004 }
6005
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006006 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
6007 Map<String, String> userDataForAccount;
6008 // Fast path - check if data is already cached
6009 synchronized (accounts.cacheLock) {
6010 userDataForAccount = accounts.userDataCache.get(account);
6011 }
6012 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00006013 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006014 synchronized (accounts.dbLock) {
6015 synchronized (accounts.cacheLock) {
6016 userDataForAccount = accounts.userDataCache.get(account);
6017 if (userDataForAccount == null) {
6018 // need to populate the cache for this account
6019 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
6020 accounts.userDataCache.put(account, userDataForAccount);
6021 }
6022 }
6023 }
Fred Quintana56285a62010-12-02 14:20:51 -08006024 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00006025 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08006026 }
6027
Kenny Guy07ad8dc2014-09-01 20:56:12 +01006028 private Context getContextForUser(UserHandle user) {
6029 try {
6030 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
6031 } catch (NameNotFoundException e) {
6032 // Default to mContext, not finding the package system is running as is unlikely.
6033 return mContext;
6034 }
6035 }
Sandra Kwan78812282015-11-04 11:19:47 -08006036
6037 private void sendResponse(IAccountManagerResponse response, Bundle result) {
6038 try {
6039 response.onResult(result);
6040 } catch (RemoteException e) {
6041 // if the caller is dead then there is no one to care about remote
6042 // exceptions
6043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6044 Log.v(TAG, "failure while notifying response", e);
6045 }
6046 }
6047 }
6048
6049 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
6050 String errorMessage) {
6051 try {
6052 response.onError(errorCode, errorMessage);
6053 } catch (RemoteException e) {
6054 // if the caller is dead then there is no one to care about remote
6055 // exceptions
6056 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6057 Log.v(TAG, "failure while notifying response", e);
6058 }
6059 }
6060 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006061
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006062 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07006063 private final Object mLock = new Object();
6064
6065 @GuardedBy("mLock")
6066 private AccountManagerBackupHelper mBackupHelper;
6067
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006068 @Override
6069 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
6070 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
6071 if (account == null) {
6072 Slog.w(TAG, "account cannot be null");
6073 return;
6074 }
6075 if (packageName == null) {
6076 Slog.w(TAG, "packageName cannot be null");
6077 return;
6078 }
6079 if (userId < UserHandle.USER_SYSTEM) {
6080 Slog.w(TAG, "user id must be concrete");
6081 return;
6082 }
6083 if (callback == null) {
6084 Slog.w(TAG, "callback cannot be null");
6085 return;
6086 }
6087
Dmitry Dementyev7b3ea132017-05-10 12:45:02 -07006088 int visibility =
6089 resolveAccountVisibility(account, packageName, getUserAccounts(userId));
6090 if (visibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
6091 Slog.w(TAG, "requestAccountAccess: account is hidden");
6092 return;
6093 }
6094
Svet Ganovf6d424f12016-09-20 20:18:53 -07006095 if (AccountManagerService.this.hasAccountAccess(account, packageName,
6096 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006097 Bundle result = new Bundle();
6098 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
6099 callback.sendResult(result);
6100 return;
6101 }
6102
6103 final int uid;
6104 try {
6105 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
6106 } catch (NameNotFoundException e) {
6107 Slog.e(TAG, "Unknown package " + packageName);
6108 return;
6109 }
6110
6111 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006112 final UserAccounts userAccounts;
6113 synchronized (mUsers) {
6114 userAccounts = mUsers.get(userId);
6115 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04006116 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006117 doNotification(userAccounts, account, null, intent, packageName, userId);
6118 }
6119
6120 @Override
6121 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
6122 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
6123 mAppPermissionChangeListeners.add(listener);
6124 }
6125
6126 @Override
6127 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
6128 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006129 }
Svet Ganov5d09c992016-09-07 09:57:41 -07006130
6131 @Override
6132 public byte[] backupAccountAccessPermissions(int userId) {
6133 synchronized (mLock) {
6134 if (mBackupHelper == null) {
6135 mBackupHelper = new AccountManagerBackupHelper(
6136 AccountManagerService.this, this);
6137 }
6138 return mBackupHelper.backupAccountAccessPermissions(userId);
6139 }
6140 }
6141
6142 @Override
6143 public void restoreAccountAccessPermissions(byte[] data, int userId) {
6144 synchronized (mLock) {
6145 if (mBackupHelper == null) {
6146 mBackupHelper = new AccountManagerBackupHelper(
6147 AccountManagerService.this, this);
6148 }
6149 mBackupHelper.restoreAccountAccessPermissions(data, userId);
6150 }
6151 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006152 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07006153
6154 @VisibleForTesting
6155 static class Injector {
6156 private final Context mContext;
6157
6158 public Injector(Context context) {
6159 mContext = context;
6160 }
6161
6162 Looper getMessageHandlerLooper() {
6163 ServiceThread serviceThread = new ServiceThread(TAG,
6164 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
6165 serviceThread.start();
6166 return serviceThread.getLooper();
6167 }
6168
6169 Context getContext() {
6170 return mContext;
6171 }
6172
6173 void addLocalService(AccountManagerInternal service) {
6174 LocalServices.addService(AccountManagerInternal.class, service);
6175 }
6176
6177 String getDeDatabaseName(int userId) {
6178 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6179 AccountsDb.DE_DATABASE_NAME);
6180 return databaseFile.getPath();
6181 }
6182
6183 String getCeDatabaseName(int userId) {
6184 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6185 AccountsDb.CE_DATABASE_NAME);
6186 return databaseFile.getPath();
6187 }
6188
6189 String getPreNDatabaseName(int userId) {
6190 File systemDir = Environment.getDataSystemDirectory();
6191 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6192 PRE_N_DATABASE_NAME);
6193 if (userId == 0) {
6194 // Migrate old file, if it exists, to the new location.
6195 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006196 // accidentally created in the old location,
6197 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006198 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6199 if (oldFile.exists() && !databaseFile.exists()) {
6200 // Check for use directory; create if it doesn't exist, else renameTo will fail
6201 File userDir = Environment.getUserSystemDirectory(userId);
6202 if (!userDir.exists()) {
6203 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006204 throw new IllegalStateException(
6205 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006206 }
6207 }
6208 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006209 throw new IllegalStateException(
6210 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006211 }
6212 }
6213 }
6214 return databaseFile.getPath();
6215 }
6216
6217 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6218 return new AccountAuthenticatorCache(mContext);
6219 }
6220
6221 INotificationManager getNotificationManager() {
6222 return NotificationManager.getService();
6223 }
6224 }
Chris Wren717a8812017-03-31 15:34:39 -04006225
Andrew Scullc7770d62017-05-22 17:49:58 +01006226 private static class NotificationId {
Chris Wren717a8812017-03-31 15:34:39 -04006227 final String mTag;
6228 private final int mId;
6229
6230 NotificationId(String tag, int type) {
6231 mTag = tag;
6232 mId = type;
6233 }
6234 }
Fred Quintana60307342009-03-24 22:48:12 -07006235}