blob: 5055562ed9b07c0bc77b5dce842b66b47f750586 [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;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070027import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080028import android.accounts.GrantCredentialsPermissionActivity;
29import android.accounts.IAccountAuthenticator;
30import android.accounts.IAccountAuthenticatorResponse;
31import android.accounts.IAccountManager;
32import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070033import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070034import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080035import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070036import android.app.ActivityManagerNative;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070037import android.app.ActivityThread;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070038import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070039import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070040import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070041import android.app.Notification;
42import android.app.NotificationManager;
43import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000044import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010045import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000046import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070047import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070048import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070049import android.content.ContentValues;
50import 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;
67import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070068import android.database.sqlite.SQLiteDatabase;
69import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070070import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070071import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070072import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080073import android.os.Environment;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070074import android.os.FileUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070076import android.os.IBinder;
77import android.os.Looper;
78import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070079import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070080import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070081import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070082import android.os.RemoteException;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070083import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070084import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070085import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070086import android.os.UserManager;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070087import android.os.storage.StorageManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070088import android.service.notification.StatusBarNotification;
Fred Quintanaa698f422009-04-08 19:14:54 -070089import android.text.TextUtils;
90import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070091import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070092import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080093import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070094import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070095
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070096import com.android.internal.R;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070097import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070098import com.android.internal.content.PackageMonitor;
Amith Yamasani67df64b2012-12-14 12:09:36 -080099import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800100import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700101import com.android.internal.util.Preconditions;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700102import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000103import com.android.server.LocalServices;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600104import com.android.server.SystemService;
105
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700106import com.google.android.collect.Lists;
107import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700108
Oscar Montemayora8529f62009-11-18 10:14:20 -0800109import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700110import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700111import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -0700112import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800113import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700114import java.security.MessageDigest;
115import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700116import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700117import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800118import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700119import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700120import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700121import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700122import java.util.HashSet;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800123import java.util.Iterator;
Fred Quintana56285a62010-12-02 14:20:51 -0800124import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700125import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800126import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800127import java.util.Map.Entry;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700128import java.util.concurrent.atomic.AtomicInteger;
129import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700130
Fred Quintana60307342009-03-24 22:48:12 -0700131/**
132 * A system service that provides account, password, and authtoken management for all
133 * accounts on the device. Some of these calls are implemented with the help of the corresponding
134 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
135 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700136 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700137 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700138 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700139public class AccountManagerService
140 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800141 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700142 private static final String TAG = "AccountManagerService";
143
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600144 public static class Lifecycle extends SystemService {
145 private AccountManagerService mService;
146
147 public Lifecycle(Context context) {
148 super(context);
149 }
150
151 @Override
152 public void onStart() {
153 mService = new AccountManagerService(getContext());
154 publishBinderService(Context.ACCOUNT_SERVICE, mService);
155 }
156
157 @Override
158 public void onBootPhase(int phase) {
159 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
160 mService.systemReady();
161 }
162 }
163
164 @Override
165 public void onUnlockUser(int userHandle) {
166 mService.onUnlockUser(userHandle);
167 }
168 }
169
Fred Quintana60307342009-03-24 22:48:12 -0700170 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700171 private static final int PRE_N_DATABASE_VERSION = 9;
172 private static final int CE_DATABASE_VERSION = 10;
173 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700174
175 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700176
177 private final Context mContext;
178
Fred Quintana56285a62010-12-02 14:20:51 -0800179 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700180 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700181 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800182
Fred Quintana60307342009-03-24 22:48:12 -0700183 private final MessageHandler mMessageHandler;
184
185 // Messages that can be sent on mHandler
186 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700187 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700188
Fred Quintana56285a62010-12-02 14:20:51 -0800189 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700190
191 private static final String TABLE_ACCOUNTS = "accounts";
192 private static final String ACCOUNTS_ID = "_id";
193 private static final String ACCOUNTS_NAME = "name";
194 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700195 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700196 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700197 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800198 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
199 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700200
201 private static final String TABLE_AUTHTOKENS = "authtokens";
202 private static final String AUTHTOKENS_ID = "_id";
203 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
204 private static final String AUTHTOKENS_TYPE = "type";
205 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
206
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700207 private static final String TABLE_GRANTS = "grants";
208 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
209 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
210 private static final String GRANTS_GRANTEE_UID = "uid";
211
Fred Quintana60307342009-03-24 22:48:12 -0700212 private static final String TABLE_EXTRAS = "extras";
213 private static final String EXTRAS_ID = "_id";
214 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
215 private static final String EXTRAS_KEY = "key";
216 private static final String EXTRAS_VALUE = "value";
217
218 private static final String TABLE_META = "meta";
219 private static final String META_KEY = "key";
220 private static final String META_VALUE = "value";
221
Amith Yamasani67df64b2012-12-14 12:09:36 -0800222 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700223 private static final String SHARED_ACCOUNTS_ID = "_id";
224
225 private static final String PRE_N_DATABASE_NAME = "accounts.db";
226 private static final String CE_DATABASE_NAME = "accounts_ce.db";
227 private static final String DE_DATABASE_NAME = "accounts_de.db";
228 private static final String CE_DB_PREFIX = "ceDb.";
229 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
230 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
231 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800232
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700233 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
234 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700235 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800236
Carlos Valdivia91979be2015-05-22 14:11:35 -0700237 static {
238 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
239 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
240 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700241
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700242 private static final String COUNT_OF_MATCHING_GRANTS = ""
243 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
244 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
245 + " AND " + GRANTS_GRANTEE_UID + "=?"
246 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
247 + " AND " + ACCOUNTS_NAME + "=?"
248 + " AND " + ACCOUNTS_TYPE + "=?";
249
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700250 private static final String COUNT_OF_MATCHING_GRANTS_ANY_TOKEN = ""
251 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
252 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
253 + " AND " + GRANTS_GRANTEE_UID + "=?"
254 + " AND " + ACCOUNTS_NAME + "=?"
255 + " AND " + ACCOUNTS_TYPE + "=?";
256
Fred Quintana56285a62010-12-02 14:20:51 -0800257 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
258 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700259
Fred Quintana56285a62010-12-02 14:20:51 -0800260 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
261 AUTHTOKENS_AUTHTOKEN};
262
263 private static final String SELECTION_USERDATA_BY_ACCOUNT =
264 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
265 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
266
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800267 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
268 "auth_uid_for_type:";
269 private static final String META_KEY_DELIMITER = ":";
270 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
271
Fred Quintanaa698f422009-04-08 19:14:54 -0700272 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700273 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
274
Amith Yamasani04e0d262012-02-14 11:50:53 -0800275 static class UserAccounts {
276 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700277 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
279 credentialsPermissionNotificationIds =
280 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
281 private final HashMap<Account, Integer> signinRequiredNotificationIds =
282 new HashMap<Account, Integer>();
283 private final Object cacheLock = new Object();
284 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700285 private final HashMap<String, Account[]> accountCache =
286 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800287 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800288 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800289 new HashMap<Account, HashMap<String, String>>();
290 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800291 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800292 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700293
294 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700295 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700296
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700297 /**
298 * protected by the {@link #cacheLock}
299 *
300 * Caches the previous names associated with an account. Previous names
301 * should be cached because we expect that when an Account is renamed,
302 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
303 * want to know if the accounts they care about have been renamed.
304 *
305 * The previous names are wrapped in an {@link AtomicReference} so that
306 * we can distinguish between those accounts with no previous names and
307 * those whose previous names haven't been cached (yet).
308 */
309 private final HashMap<Account, AtomicReference<String>> previousNameCache =
310 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800311
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700312 private int debugDbInsertionPoint = -1;
313 private SQLiteStatement statementForLogging;
314
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700315 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800316 this.userId = userId;
317 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700318 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800319 }
320 }
321 }
322
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700323 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600324 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700326 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700327 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700328
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700329 /**
330 * This should only be called by system code. One should only call this after the service
331 * has started.
332 * @return a reference to the AccountManagerService instance
333 * @hide
334 */
335 public static AccountManagerService getSingleton() {
336 return sThis.get();
337 }
Fred Quintana60307342009-03-24 22:48:12 -0700338
Fred Quintana56285a62010-12-02 14:20:51 -0800339 public AccountManagerService(Context context) {
340 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700341 }
342
Fred Quintana56285a62010-12-02 14:20:51 -0800343 public AccountManagerService(Context context, PackageManager packageManager,
344 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700345 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800346 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700347 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700348
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700349 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700350
Fred Quintana56285a62010-12-02 14:20:51 -0800351 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800352 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700353
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700354 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800355
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800356 IntentFilter intentFilter = new IntentFilter();
357 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
358 intentFilter.addDataScheme("package");
359 mContext.registerReceiver(new BroadcastReceiver() {
360 @Override
361 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700362 // Don't delete accounts when updating a authenticator's
363 // package.
364 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700365 /* Purging data requires file io, don't block the main thread. This is probably
366 * less than ideal because we are introducing a race condition where old grants
367 * could be exercised until they are purged. But that race condition existed
368 * anyway with the broadcast receiver.
369 *
370 * Ideally, we would completely clear the cache, purge data from the database,
371 * and then rebuild the cache. All under the cache lock. But that change is too
372 * large at this point.
373 */
374 Runnable r = new Runnable() {
375 @Override
376 public void run() {
377 purgeOldGrantsAll();
378 }
379 };
380 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700381 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800382 }
383 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800384
Amith Yamasani13593602012-03-22 16:16:17 -0700385 IntentFilter userFilter = new IntentFilter();
386 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800387 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700388 @Override
389 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800390 String action = intent.getAction();
391 if (Intent.ACTION_USER_REMOVED.equals(action)) {
392 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800393 }
Amith Yamasani13593602012-03-22 16:16:17 -0700394 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800395 }, UserHandle.ALL, userFilter, null, null);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700396
397 LocalServices.addService(AccountManagerInternal.class, new AccountManagerInternalImpl());
398
399 // Need to cancel account request notifications if the update/install can access the account
400 new PackageMonitor() {
401 @Override
402 public void onPackageAdded(String packageName, int uid) {
403 // Called on a handler, and running as the system
404 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
405 }
406
407 @Override
408 public void onPackageUpdateFinished(String packageName, int uid) {
409 // Called on a handler, and running as the system
410 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
411 }
412 }.register(mContext, mMessageHandler.getLooper(), UserHandle.ALL, true);
413
414 // Cancel account request notification if an app op was preventing the account access
415 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
416 new AppOpsManager.OnOpChangedInternalListener() {
417 @Override
418 public void onOpChanged(int op, String packageName) {
419 try {
420 final int userId = ActivityManager.getCurrentUser();
421 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
422 final int mode = mAppOpsManager.checkOpNoThrow(
423 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
424 if (mode == AppOpsManager.MODE_ALLOWED) {
425 final long identity = Binder.clearCallingIdentity();
426 try {
427 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
428 } finally {
429 Binder.restoreCallingIdentity(identity);
430 }
431 }
432 } catch (NameNotFoundException e) {
433 /* ignore */
434 }
435 }
436 });
437
438 // Cancel account request notification if a permission was preventing the account access
439 mPackageManager.addOnPermissionsChangeListener(
440 (int uid) -> {
441 Account[] accounts = null;
442 String[] packageNames = mPackageManager.getPackagesForUid(uid);
443 if (packageNames != null) {
444 final int userId = UserHandle.getUserId(uid);
445 final long identity = Binder.clearCallingIdentity();
446 try {
447 for (String packageName : packageNames) {
448 if (mContext.getPackageManager().checkPermission(
449 Manifest.permission.GET_ACCOUNTS, packageName)
450 != PackageManager.PERMISSION_GRANTED) {
451 continue;
452 }
453
454 if (accounts == null) {
455 accounts = getAccountsAsUser(null, userId, "android");
456 if (ArrayUtils.isEmpty(accounts)) {
457 return;
458 }
459 }
460
461 for (Account account : accounts) {
462 cancelAccountAccessRequestNotificationIfNeeded(
463 account, uid, packageName, true);
464 }
465 }
466 } finally {
467 Binder.restoreCallingIdentity(identity);
468 }
469 }
470 });
471 }
472
473 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
474 boolean checkAccess) {
475 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
476 for (Account account : accounts) {
477 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
478 }
479 }
480
481 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
482 boolean checkAccess) {
483 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
484 for (Account account : accounts) {
485 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
486 }
487 }
488
489 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
490 boolean checkAccess) {
491 String[] packageNames = mPackageManager.getPackagesForUid(uid);
492 if (packageNames != null) {
493 for (String packageName : packageNames) {
494 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
495 packageName, checkAccess);
496 }
497 }
498 }
499
500 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
501 int uid, String packageName, boolean checkAccess) {
502 if (!checkAccess || hasAccountAccess(account, packageName,
503 UserHandle.getUserHandleForUid(uid))) {
504 cancelNotification(getCredentialPermissionNotificationId(account,
505 AccountManager.ACCOUNT_ACCESS_TOKEN, uid), packageName,
506 UserHandle.getUserHandleForUid(uid));
507 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800508 }
509
Dianne Hackborn164371f2013-10-01 19:10:13 -0700510 @Override
511 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
512 throws RemoteException {
513 try {
514 return super.onTransact(code, data, reply, flags);
515 } catch (RuntimeException e) {
516 // The account manager only throws security exceptions, so let's
517 // log all others.
518 if (!(e instanceof SecurityException)) {
519 Slog.wtf(TAG, "Account Manager Crash", e);
520 }
521 throw e;
522 }
523 }
524
Kenny Root26ff6622012-07-30 12:58:03 -0700525 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700526 }
527
Amith Yamasani258848d2012-08-10 17:06:33 -0700528 private UserManager getUserManager() {
529 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700530 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700531 }
532 return mUserManager;
533 }
534
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700535 /**
536 * Validate internal set of accounts against installed authenticators for
537 * given user. Clears cached authenticators before validating.
538 */
539 public void validateAccounts(int userId) {
540 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700541 // Invalidate user-specific cache to make sure we catch any
542 // removed authenticators.
543 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
544 }
545
546 /**
547 * Validate internal set of accounts against installed authenticators for
548 * given user. Clear cached authenticators before validating when requested.
549 */
550 private void validateAccountsInternal(
551 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700552 if (Log.isLoggable(TAG, Log.DEBUG)) {
553 Log.d(TAG, "validateAccountsInternal " + accounts.userId
554 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600555 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700556 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700557
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700558 if (invalidateAuthenticatorCache) {
559 mAuthenticatorCache.invalidateCache(accounts.userId);
560 }
561
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700562 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
563 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700564 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700565
Amith Yamasani04e0d262012-02-14 11:50:53 -0800566 synchronized (accounts.cacheLock) {
567 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800568 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800569
570 // Get a list of stored authenticator type and UID
571 Cursor metaCursor = db.query(
572 TABLE_META,
573 new String[] {META_KEY, META_VALUE},
574 SELECTION_META_BY_AUTHENTICATOR_TYPE,
575 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
576 null /* groupBy */,
577 null /* having */,
578 META_KEY);
579 // Create a list of authenticator type whose previous uid no longer exists
580 HashSet<String> obsoleteAuthType = Sets.newHashSet();
581 try {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700582 SparseBooleanArray knownUids = null;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800583 while (metaCursor.moveToNext()) {
584 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
585 String uid = metaCursor.getString(1);
586 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
587 // Should never happen.
588 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
589 + ", uid empty: " + TextUtils.isEmpty(uid));
590 continue;
591 }
592 Integer knownUid = knownAuth.get(type);
593 if (knownUid != null && uid.equals(knownUid.toString())) {
594 // Remove it from the knownAuth list if it's unchanged.
595 knownAuth.remove(type);
596 } else {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700597 /*
598 * The authenticator is presently not cached and should only be triggered
599 * when we think an authenticator has been removed (or is being updated).
600 * But we still want to check if any data with the associated uid is
601 * around. This is an (imperfect) signal that the package may be updating.
602 *
603 * A side effect of this is that an authenticator sharing a uid with
604 * multiple apps won't get its credentials wiped as long as some app with
605 * that uid is still on the device. But I suspect that this is a rare case.
606 * And it isn't clear to me how an attacker could really exploit that
607 * feature.
608 *
609 * The upshot is that we don't have to worry about accounts getting
610 * uninstalled while the authenticator's package is being updated.
611 *
612 */
613 if (knownUids == null) {
614 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
615 }
616 if (!knownUids.get(Integer.parseInt(uid))) {
617 // The authenticator is not presently available to the cache. And the
618 // package no longer has a data directory (so we surmise it isn't updating).
619 // So purge its data from the account databases.
620 obsoleteAuthType.add(type);
621 // And delete it from the TABLE_META
622 db.delete(
623 TABLE_META,
624 META_KEY + "=? AND " + META_VALUE + "=?",
625 new String[] {
626 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
627 uid}
628 );
629 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800630 }
631 }
632 } finally {
633 metaCursor.close();
634 }
635
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700636 // Add the newly registered authenticator to TABLE_META. If old authenticators have
637 // been renabled (after being updated for example), then we just overwrite the old
638 // values.
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800639 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
640 while (iterator.hasNext()) {
641 Entry<String, Integer> entry = iterator.next();
642 ContentValues values = new ContentValues();
643 values.put(META_KEY,
644 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
645 values.put(META_VALUE, entry.getValue());
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700646 db.insertWithOnConflict(TABLE_META, null, values, SQLiteDatabase.CONFLICT_REPLACE);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800647 }
648
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800649 Cursor cursor = db.query(TABLE_ACCOUNTS,
650 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800651 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800652 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800653 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700654 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800655 while (cursor.moveToNext()) {
656 final long accountId = cursor.getLong(0);
657 final String accountType = cursor.getString(1);
658 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700659
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800660 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700661 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800662 + accountType + "'s registered authenticator no longer exist.");
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700663 db.beginTransaction();
664 try {
665 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
666 // Also delete from CE table if user is unlocked; if user is currently
667 // locked the account will be removed later by syncDeCeAccountsLocked
668 if (userUnlocked) {
669 db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
670 }
671 db.setTransactionSuccessful();
672 } finally {
673 db.endTransaction();
674 }
Fred Quintana56285a62010-12-02 14:20:51 -0800675 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700676
677 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
678 accountId, accounts);
679
Fred Quintana56285a62010-12-02 14:20:51 -0800680 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800681 accounts.userDataCache.remove(account);
682 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700683 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800684 } else {
685 ArrayList<String> accountNames = accountNamesByType.get(accountType);
686 if (accountNames == null) {
687 accountNames = new ArrayList<String>();
688 accountNamesByType.put(accountType, accountNames);
689 }
690 accountNames.add(accountName);
691 }
692 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700693 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800694 final String accountType = cur.getKey();
695 final ArrayList<String> accountNames = cur.getValue();
696 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700697 for (int i = 0; i < accountsForType.length; i++) {
698 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800699 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800700 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800702 } finally {
703 cursor.close();
704 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800705 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800706 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800707 }
708 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700709 }
710
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700711 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
712 // Get the UIDs of all apps that might have data on the device. We want
713 // to preserve user data if the app might otherwise be storing data.
714 List<PackageInfo> pkgsWithData =
715 mPackageManager.getInstalledPackagesAsUser(
716 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
717 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
718 for (PackageInfo pkgInfo : pkgsWithData) {
719 if (pkgInfo.applicationInfo != null
720 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
721 knownUids.put(pkgInfo.applicationInfo.uid, true);
722 }
723 }
724 return knownUids;
725 }
726
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800727 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
728 Context context,
729 int userId) {
730 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700731 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
732 }
733
734 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
735 IAccountAuthenticatorCache authCache,
736 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800737 HashMap<String, Integer> knownAuth = new HashMap<>();
738 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
739 .getAllServices(userId)) {
740 knownAuth.put(service.type.type, service.uid);
741 }
742 return knownAuth;
743 }
744
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700746 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800747 }
748
749 protected UserAccounts getUserAccounts(int userId) {
750 synchronized (mUsers) {
751 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700752 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800753 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700754 File preNDbFile = new File(getPreNDatabaseName(userId));
755 File deDbFile = new File(getDeDatabaseName(userId));
756 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700757 initializeDebugDbSizeAndCompileSqlStatementForLogging(
758 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800759 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700760 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700761 validateAccounts = true;
762 }
763 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600764 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700765 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
766 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700767 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
768 File ceDatabaseFile = new File(getCeDatabaseName(userId));
769 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
770 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700771 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700772 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700773 }
774 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700775 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800776 }
777 return accounts;
778 }
779 }
780
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700781 private void syncDeCeAccountsLocked(UserAccounts accounts) {
782 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
783 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
784 List<Account> accountsToRemove = CeDatabaseHelper.findCeAccountsNotInDe(db);
785 if (!accountsToRemove.isEmpty()) {
786 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
787 + accounts.userId + " was locked. Removing accounts from CE tables");
788 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
789
790 for (Account account : accountsToRemove) {
791 removeAccountInternal(accounts, account, Process.myUid());
792 }
793 }
794 }
795
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700796 private void purgeOldGrantsAll() {
797 synchronized (mUsers) {
798 for (int i = 0; i < mUsers.size(); i++) {
799 purgeOldGrants(mUsers.valueAt(i));
800 }
801 }
802 }
803
804 private void purgeOldGrants(UserAccounts accounts) {
805 synchronized (accounts.cacheLock) {
806 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
807 final Cursor cursor = db.query(TABLE_GRANTS,
808 new String[]{GRANTS_GRANTEE_UID},
809 null, null, GRANTS_GRANTEE_UID, null, null);
810 try {
811 while (cursor.moveToNext()) {
812 final int uid = cursor.getInt(0);
813 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
814 if (packageExists) {
815 continue;
816 }
817 Log.d(TAG, "deleting grants for UID " + uid
818 + " because its package is no longer installed");
819 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
820 new String[]{Integer.toString(uid)});
821 }
822 } finally {
823 cursor.close();
824 }
825 }
826 }
827
Amith Yamasani13593602012-03-22 16:16:17 -0700828 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700829 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700830 if (userId < 1) return;
831
832 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700833 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700834 synchronized (mUsers) {
835 accounts = mUsers.get(userId);
836 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600837 userUnlocked = mLocalUnlockedUsers.get(userId);
838 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700839 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700840 if (accounts != null) {
841 synchronized (accounts.cacheLock) {
842 accounts.openHelper.close();
843 }
Amith Yamasani13593602012-03-22 16:16:17 -0700844 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700845 Log.i(TAG, "Removing database files for user " + userId);
846 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700847
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700848 deleteDbFileWarnIfFailed(dbFile);
849 // Remove CE file if user is unlocked, or FBE is not enabled
850 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
851 if (!fbeEnabled || userUnlocked) {
852 File ceDb = new File(getCeDatabaseName(userId));
853 if (ceDb.exists()) {
854 deleteDbFileWarnIfFailed(ceDb);
855 }
856 }
857 }
858
859 private static void deleteDbFileWarnIfFailed(File dbFile) {
860 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
861 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700862 }
863 }
864
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700865 @VisibleForTesting
866 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600867 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
868 }
869
870 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700871 if (Log.isLoggable(TAG, Log.VERBOSE)) {
872 Log.v(TAG, "onUserUnlocked " + userId);
873 }
874 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600875 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700876 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800877 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700878 syncSharedAccounts(userId);
879 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800880
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700881 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800882 // Check if there's a shared account that needs to be created as an account
883 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
884 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700885 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700886 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700887 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700888 : UserHandle.USER_SYSTEM;
889 if (parentUserId < 0) {
890 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
891 return;
892 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800893 for (Account sa : sharedAccounts) {
894 if (ArrayUtils.contains(accounts, sa)) continue;
895 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700896 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800897 }
898 }
899
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700900 @Override
901 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700902 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700903 }
904
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800905 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700906 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700907 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800908 if (Log.isLoggable(TAG, Log.VERBOSE)) {
909 Log.v(TAG, "getPassword: " + account
910 + ", caller's uid " + Binder.getCallingUid()
911 + ", pid " + Binder.getCallingPid());
912 }
Fred Quintana382601f2010-03-25 12:25:10 -0700913 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000914 int userId = UserHandle.getCallingUserId();
915 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700916 String msg = String.format(
917 "uid %s cannot get secrets for accounts of type: %s",
918 callingUid,
919 account.type);
920 throw new SecurityException(msg);
921 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700922 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700923 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700924 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800925 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700926 } finally {
927 restoreCallingIdentity(identityToken);
928 }
929 }
930
Amith Yamasani04e0d262012-02-14 11:50:53 -0800931 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700932 if (account == null) {
933 return null;
934 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600935 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700936 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
937 return null;
938 }
Fred Quintana31957f12009-10-21 13:43:10 -0700939
Amith Yamasani04e0d262012-02-14 11:50:53 -0800940 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700941 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
942 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
943 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700944 }
945 }
946
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800947 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700948 public String getPreviousName(Account account) {
949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
950 Log.v(TAG, "getPreviousName: " + account
951 + ", caller's uid " + Binder.getCallingUid()
952 + ", pid " + Binder.getCallingPid());
953 }
954 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700955 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700956 long identityToken = clearCallingIdentity();
957 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700958 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700959 return readPreviousNameInternal(accounts, account);
960 } finally {
961 restoreCallingIdentity(identityToken);
962 }
963 }
964
965 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
966 if (account == null) {
967 return null;
968 }
969 synchronized (accounts.cacheLock) {
970 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
971 if (previousNameRef == null) {
972 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
973 Cursor cursor = db.query(
974 TABLE_ACCOUNTS,
975 new String[]{ ACCOUNTS_PREVIOUS_NAME },
976 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
977 new String[] { account.name, account.type },
978 null,
979 null,
980 null);
981 try {
982 if (cursor.moveToNext()) {
983 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700984 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700985 accounts.previousNameCache.put(account, previousNameRef);
986 return previousName;
987 } else {
988 return null;
989 }
990 } finally {
991 cursor.close();
992 }
993 } else {
994 return previousNameRef.get();
995 }
996 }
997 }
998
999 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001000 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001001 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001002 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001003 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1004 account, key, callingUid, Binder.getCallingPid());
1005 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001006 }
Fred Quintana382601f2010-03-25 12:25:10 -07001007 if (account == null) throw new IllegalArgumentException("account is null");
1008 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001009 int userId = UserHandle.getCallingUserId();
1010 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001011 String msg = String.format(
1012 "uid %s cannot get user data for accounts of type: %s",
1013 callingUid,
1014 account.type);
1015 throw new SecurityException(msg);
1016 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001017 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001018 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1019 return null;
1020 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001021 long identityToken = clearCallingIdentity();
1022 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001023 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001024 synchronized (accounts.cacheLock) {
1025 if (!accountExistsCacheLocked(accounts, account)) {
1026 return null;
1027 }
1028 return readUserDataInternalLocked(accounts, account, key);
1029 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001030 } finally {
1031 restoreCallingIdentity(identityToken);
1032 }
1033 }
1034
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001035 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001036 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001037 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001038 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1039 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001040 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001041 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001042 + ", pid " + Binder.getCallingPid());
1043 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001044 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001045 if (isCrossUser(callingUid, userId)) {
1046 throw new SecurityException(
1047 String.format(
1048 "User %s tying to get authenticator types for %s" ,
1049 UserHandle.getCallingUserId(),
1050 userId));
1051 }
1052
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001053 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001054 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001055 return getAuthenticatorTypesInternal(userId);
1056
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001057 } finally {
1058 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001059 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001060 }
1061
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001062 /**
1063 * Should only be called inside of a clearCallingIdentity block.
1064 */
1065 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
1066 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1067 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1068 AuthenticatorDescription[] types =
1069 new AuthenticatorDescription[authenticatorCollection.size()];
1070 int i = 0;
1071 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1072 : authenticatorCollection) {
1073 types[i] = authenticator.type;
1074 i++;
1075 }
1076 return types;
1077 }
1078
1079
1080
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001081 private boolean isCrossUser(int callingUid, int userId) {
1082 return (userId != UserHandle.getCallingUserId()
1083 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001084 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001085 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1086 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001087 }
1088
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001089 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001090 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001091 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001092 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001093 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001094 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001095 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001096 + ", pid " + Binder.getCallingPid());
1097 }
Fred Quintana382601f2010-03-25 12:25:10 -07001098 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001099 int userId = UserHandle.getCallingUserId();
1100 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001101 String msg = String.format(
1102 "uid %s cannot explicitly add accounts of type: %s",
1103 callingUid,
1104 account.type);
1105 throw new SecurityException(msg);
1106 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001107 /*
1108 * Child users are not allowed to add accounts. Only the accounts that are
1109 * shared by the parent profile can be added to child profile.
1110 *
1111 * TODO: Only allow accounts that were shared to be added by
1112 * a limited user.
1113 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001114
Fred Quintana60307342009-03-24 22:48:12 -07001115 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001116 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001117 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001118 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001119 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -07001120 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001121 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001122 }
1123 }
1124
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001125 @Override
1126 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001127 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001128 int callingUid = Binder.getCallingUid();
1129 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1130 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001131 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001132 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001133 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1134 final UserAccounts toAccounts = getUserAccounts(userTo);
1135 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001136 if (response != null) {
1137 Bundle result = new Bundle();
1138 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1139 try {
1140 response.onResult(result);
1141 } catch (RemoteException e) {
1142 Slog.w(TAG, "Failed to report error back to the client." + e);
1143 }
1144 }
1145 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001146 }
1147
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001148 Slog.d(TAG, "Copying account " + account.name
1149 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001150 long identityToken = clearCallingIdentity();
1151 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001152 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001153 false /* stripAuthTokenFromResult */, account.name,
1154 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001155 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001156 protected String toDebugString(long now) {
1157 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1158 + ", " + account.type;
1159 }
1160
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001161 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001162 public void run() throws RemoteException {
1163 mAuthenticator.getAccountCredentialsForCloning(this, account);
1164 }
1165
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001166 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001167 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001168 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001169 if (result != null
1170 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1171 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001172 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001173 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001174 super.onResult(result);
1175 }
1176 }
1177 }.bind();
1178 } finally {
1179 restoreCallingIdentity(identityToken);
1180 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001181 }
1182
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001183 @Override
1184 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001185 final int callingUid = Binder.getCallingUid();
1186 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1187 String msg = String.format(
1188 "accountAuthenticated( account: %s, callerUid: %s)",
1189 account,
1190 callingUid);
1191 Log.v(TAG, msg);
1192 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001193 if (account == null) {
1194 throw new IllegalArgumentException("account is null");
1195 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001196 int userId = UserHandle.getCallingUserId();
1197 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001198 String msg = String.format(
1199 "uid %s cannot notify authentication for accounts of type: %s",
1200 callingUid,
1201 account.type);
1202 throw new SecurityException(msg);
1203 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001204
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001205 if (!canUserModifyAccounts(userId, callingUid) ||
1206 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001207 return false;
1208 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001209
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001210 long identityToken = clearCallingIdentity();
1211 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001212 UserAccounts accounts = getUserAccounts(userId);
1213 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001214 } finally {
1215 restoreCallingIdentity(identityToken);
1216 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001217 }
1218
1219 private boolean updateLastAuthenticatedTime(Account account) {
1220 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001221 synchronized (accounts.cacheLock) {
1222 final ContentValues values = new ContentValues();
1223 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1224 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1225 int i = db.update(
1226 TABLE_ACCOUNTS,
1227 values,
1228 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1229 new String[] {
1230 account.name, account.type
1231 });
1232 if (i > 0) {
1233 return true;
1234 }
1235 }
1236 return false;
1237 }
1238
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001239 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001240 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1241 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001242 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001243 long id = clearCallingIdentity();
1244 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001245 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001246 false /* stripAuthTokenFromResult */, account.name,
1247 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001248 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001249 protected String toDebugString(long now) {
1250 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1251 + ", " + account.type;
1252 }
1253
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001254 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001255 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001256 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001257 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001258 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001259 for (Account acc : getAccounts(parentUserId,
1260 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001261 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001262 mAuthenticator.addAccountFromCredentials(
1263 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001264 break;
1265 }
1266 }
1267 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001268 }
1269
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001270 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001271 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001272 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001273 // TODO: Anything to do if if succedded?
1274 // TODO: If it failed: Show error notification? Should we remove the shadow
1275 // account to avoid retries?
1276 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001277 }
1278
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001279 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001280 public void onError(int errorCode, String errorMessage) {
1281 super.onError(errorCode, errorMessage);
1282 // TODO: Show error notification to user
1283 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1284 }
1285
1286 }.bind();
1287 } finally {
1288 restoreCallingIdentity(id);
1289 }
1290 }
1291
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001293 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001294 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001295 if (account == null) {
1296 return false;
1297 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001298 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001299 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1300 + " is locked. callingUid=" + callingUid);
1301 return false;
1302 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001303 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001304 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001305 db.beginTransaction();
1306 try {
1307 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001308 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001309 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1310 new String[]{account.name, account.type});
1311 if (numMatches > 0) {
1312 Log.w(TAG, "insertAccountIntoDatabase: " + account
1313 + ", skipping since the account already exists");
1314 return false;
1315 }
1316 ContentValues values = new ContentValues();
1317 values.put(ACCOUNTS_NAME, account.name);
1318 values.put(ACCOUNTS_TYPE, account.type);
1319 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001320 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001321 if (accountId < 0) {
1322 Log.w(TAG, "insertAccountIntoDatabase: " + account
1323 + ", skipping the DB insert failed");
1324 return false;
1325 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001326 // Insert into DE table
1327 values = new ContentValues();
1328 values.put(ACCOUNTS_ID, accountId);
1329 values.put(ACCOUNTS_NAME, account.name);
1330 values.put(ACCOUNTS_TYPE, account.type);
1331 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1332 System.currentTimeMillis());
1333 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1334 Log.w(TAG, "insertAccountIntoDatabase: " + account
1335 + ", skipping the DB insert failed");
1336 return false;
1337 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001338 if (extras != null) {
1339 for (String key : extras.keySet()) {
1340 final String value = extras.getString(key);
1341 if (insertExtraLocked(db, accountId, key, value) < 0) {
1342 Log.w(TAG, "insertAccountIntoDatabase: " + account
1343 + ", skipping since insertExtra failed for key " + key);
1344 return false;
1345 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001346 }
1347 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001348 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001349
1350 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1351 accounts, callingUid);
1352
Amith Yamasani04e0d262012-02-14 11:50:53 -08001353 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001354 } finally {
1355 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001356 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001357 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001358 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1359 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001360 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001361
1362 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1363 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001364 return true;
1365 }
1366
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001367 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001368 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001369 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001370 }
1371 }
1372
Amith Yamasani5be347b2013-03-31 17:44:31 -07001373 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001374 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001375 * running, then clone the account too.
1376 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001377 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001378 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001379 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001380 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001381 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001382 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001383 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001384 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001385 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1386 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001387 }
1388 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001389 }
1390 }
1391
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001392 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001393 ContentValues values = new ContentValues();
1394 values.put(EXTRAS_KEY, key);
1395 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1396 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001397 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001398 }
1399
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001400 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001401 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001402 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001403 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001404 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1405 Log.v(TAG, "hasFeatures: " + account
1406 + ", response " + response
1407 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001408 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001409 + ", pid " + Binder.getCallingPid());
1410 }
Fred Quintana382601f2010-03-25 12:25:10 -07001411 if (response == null) throw new IllegalArgumentException("response is null");
1412 if (account == null) throw new IllegalArgumentException("account is null");
1413 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001414 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001415 checkReadAccountsPermitted(callingUid, account.type, userId,
1416 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001417
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001418 long identityToken = clearCallingIdentity();
1419 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001420 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001422 } finally {
1423 restoreCallingIdentity(identityToken);
1424 }
1425 }
1426
1427 private class TestFeaturesSession extends Session {
1428 private final String[] mFeatures;
1429 private final Account mAccount;
1430
Amith Yamasani04e0d262012-02-14 11:50:53 -08001431 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001432 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001433 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001434 true /* stripAuthTokenFromResult */, account.name,
1435 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001436 mFeatures = features;
1437 mAccount = account;
1438 }
1439
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001440 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001441 public void run() throws RemoteException {
1442 try {
1443 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1444 } catch (RemoteException e) {
1445 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1446 }
1447 }
1448
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001449 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001450 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001451 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001452 IAccountManagerResponse response = getResponseAndClose();
1453 if (response != null) {
1454 try {
1455 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001456 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001457 return;
1458 }
Fred Quintana56285a62010-12-02 14:20:51 -08001459 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1460 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1461 + response);
1462 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001463 final Bundle newResult = new Bundle();
1464 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1465 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1466 response.onResult(newResult);
1467 } catch (RemoteException e) {
1468 // if the caller is dead then there is no one to care about remote exceptions
1469 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1470 Log.v(TAG, "failure while notifying response", e);
1471 }
1472 }
1473 }
1474 }
1475
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001476 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001477 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001478 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001479 + ", " + mAccount
1480 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1481 }
1482 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001483
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001484 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001485 public void renameAccount(
1486 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001487 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1489 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001490 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001491 + ", pid " + Binder.getCallingPid());
1492 }
1493 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001494 int userId = UserHandle.getCallingUserId();
1495 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001496 String msg = String.format(
1497 "uid %s cannot rename accounts of type: %s",
1498 callingUid,
1499 accountToRename.type);
1500 throw new SecurityException(msg);
1501 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001502 long identityToken = clearCallingIdentity();
1503 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001504 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001505 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001506 Bundle result = new Bundle();
1507 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1508 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1509 try {
1510 response.onResult(result);
1511 } catch (RemoteException e) {
1512 Log.w(TAG, e.getMessage());
1513 }
1514 } finally {
1515 restoreCallingIdentity(identityToken);
1516 }
1517 }
1518
1519 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001520 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001521 Account resultAccount = null;
1522 /*
1523 * Cancel existing notifications. Let authenticators
1524 * re-post notifications as required. But we don't know if
1525 * the authenticators have bound their notifications to
1526 * now stale account name data.
1527 *
1528 * With a rename api, we might not need to do this anymore but it
1529 * shouldn't hurt.
1530 */
1531 cancelNotification(
1532 getSigninRequiredNotificationId(accounts, accountToRename),
1533 new UserHandle(accounts.userId));
1534 synchronized(accounts.credentialsPermissionNotificationIds) {
1535 for (Pair<Pair<Account, String>, Integer> pair:
1536 accounts.credentialsPermissionNotificationIds.keySet()) {
1537 if (accountToRename.equals(pair.first.first)) {
1538 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1539 cancelNotification(id, new UserHandle(accounts.userId));
1540 }
1541 }
1542 }
1543 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001544 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001545 db.beginTransaction();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001546 Account renamedAccount = new Account(newName, accountToRename.type);
1547 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001548 final long accountId = getAccountIdLocked(db, accountToRename);
1549 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001550 final ContentValues values = new ContentValues();
1551 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001552 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001553 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1554 // Update NAME/PREVIOUS_NAME in DE accounts table
1555 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001556 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1557 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001558 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1559 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001560 }
1561 } finally {
1562 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001563 }
1564 /*
1565 * Database transaction was successful. Clean up cached
1566 * data associated with the account in the user profile.
1567 */
1568 insertAccountIntoCacheLocked(accounts, renamedAccount);
1569 /*
1570 * Extract the data and token caches before removing the
1571 * old account to preserve the user data associated with
1572 * the account.
1573 */
1574 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1575 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1576 removeAccountFromCacheLocked(accounts, accountToRename);
1577 /*
1578 * Update the cached data associated with the renamed
1579 * account.
1580 */
1581 accounts.userDataCache.put(renamedAccount, tmpData);
1582 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1583 accounts.previousNameCache.put(
1584 renamedAccount,
1585 new AtomicReference<String>(accountToRename.name));
1586 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001587
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001588 int parentUserId = accounts.userId;
1589 if (canHaveProfile(parentUserId)) {
1590 /*
1591 * Owner or system user account was renamed, rename the account for
1592 * those users with which the account was shared.
1593 */
1594 List<UserInfo> users = getUserManager().getUsers(true);
1595 for (UserInfo user : users) {
1596 if (user.isRestricted()
1597 && (user.restrictedProfileParentId == parentUserId)) {
1598 renameSharedAccountAsUser(accountToRename, newName, user.id);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001599 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001600 }
1601 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001602 sendAccountsChangedBroadcast(accounts.userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001603 }
1604 return resultAccount;
1605 }
1606
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001607 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001608 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001609 return userInfo != null && userInfo.canHaveProfile();
1610 }
1611
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001612 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001613 public void removeAccount(IAccountManagerResponse response, Account account,
1614 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001615 removeAccountAsUser(
1616 response,
1617 account,
1618 expectActivityLaunch,
1619 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001620 }
1621
1622 @Override
1623 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001624 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001625 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001626 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1627 Log.v(TAG, "removeAccount: " + account
1628 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001629 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001630 + ", pid " + Binder.getCallingPid()
1631 + ", for user id " + userId);
1632 }
1633 if (response == null) throw new IllegalArgumentException("response is null");
1634 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001635 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001636 if (isCrossUser(callingUid, userId)) {
1637 throw new SecurityException(
1638 String.format(
1639 "User %s tying remove account for %s" ,
1640 UserHandle.getCallingUserId(),
1641 userId));
1642 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001643 /*
1644 * Only the system or authenticator should be allowed to remove accounts for that
1645 * authenticator. This will let users remove accounts (via Settings in the system) but not
1646 * arbitrary applications (like competing authenticators).
1647 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001648 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001649 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1650 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001651 String msg = String.format(
1652 "uid %s cannot remove accounts of type: %s",
1653 callingUid,
1654 account.type);
1655 throw new SecurityException(msg);
1656 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001657 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001658 try {
1659 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1660 "User cannot modify accounts");
1661 } catch (RemoteException re) {
1662 }
1663 return;
1664 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001665 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001666 try {
1667 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1668 "User cannot modify accounts of this type (policy).");
1669 } catch (RemoteException re) {
1670 }
1671 return;
1672 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001673 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001674 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001675 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001676 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001677 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001678 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001679 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001680 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001681 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001682 }
1683 }
1684 }
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07001685 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
1686 final long accountId = getAccountIdLocked(db, account);
1687 logRecord(
1688 db,
1689 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
1690 TABLE_ACCOUNTS,
1691 accountId,
1692 accounts,
1693 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001694 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001695 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1696 } finally {
1697 restoreCallingIdentity(identityToken);
1698 }
1699 }
1700
1701 @Override
1702 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001703 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001704 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1705 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001706 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001707 + ", pid " + Binder.getCallingPid());
1708 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001709 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001710 if (account == null) {
1711 /*
1712 * Null accounts should result in returning false, as per
1713 * AccountManage.addAccountExplicitly(...) java doc.
1714 */
1715 Log.e(TAG, "account is null");
1716 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001717 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001718 String msg = String.format(
1719 "uid %s cannot explicitly add accounts of type: %s",
1720 callingUid,
1721 account.type);
1722 throw new SecurityException(msg);
1723 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001724 UserAccounts accounts = getUserAccountsForCaller();
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07001725 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
1726 final long accountId = getAccountIdLocked(db, account);
1727 logRecord(
1728 db,
1729 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
1730 TABLE_ACCOUNTS,
1731 accountId,
1732 accounts,
1733 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001734 long identityToken = clearCallingIdentity();
1735 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001736 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001737 } finally {
1738 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001739 }
Fred Quintana60307342009-03-24 22:48:12 -07001740 }
1741
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001742 private class RemoveAccountSession extends Session {
1743 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001744 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001745 Account account, boolean expectActivityLaunch) {
1746 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001747 true /* stripAuthTokenFromResult */, account.name,
1748 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001749 mAccount = account;
1750 }
1751
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001752 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001753 protected String toDebugString(long now) {
1754 return super.toDebugString(now) + ", removeAccount"
1755 + ", account " + mAccount;
1756 }
1757
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001758 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001759 public void run() throws RemoteException {
1760 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1761 }
1762
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001763 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001764 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001765 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001766 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1767 && !result.containsKey(AccountManager.KEY_INTENT)) {
1768 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001769 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001770 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001771 }
1772 IAccountManagerResponse response = getResponseAndClose();
1773 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1775 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1776 + response);
1777 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001778 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001779 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001780 try {
1781 response.onResult(result2);
1782 } catch (RemoteException e) {
1783 // ignore
1784 }
1785 }
1786 }
1787 super.onResult(result);
1788 }
1789 }
1790
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001791 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001792 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001793 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001794 }
1795
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001796 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001797 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001798 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001799 if (!userUnlocked) {
1800 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
1801 + " is still locked. CE data will be removed later");
1802 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001803 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001804 final SQLiteDatabase db = userUnlocked
1805 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
1806 : accounts.openHelper.getWritableDatabase();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001807 db.beginTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001808 // Set to a dummy value, this will only be used if the database
1809 // transaction succeeds.
1810 long accountId = -1;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001811 try {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001812 accountId = getAccountIdLocked(db, account);
1813 if (accountId >= 0) {
1814 db.delete(
1815 TABLE_ACCOUNTS,
1816 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1817 new String[]{ account.name, account.type });
1818 if (userUnlocked) {
1819 // Delete from CE table
1820 db.delete(
1821 CE_TABLE_ACCOUNTS,
1822 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1823 new String[]{ account.name, account.type });
1824 }
1825 db.setTransactionSuccessful();
1826 isChanged = true;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001827 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001828 } finally {
1829 db.endTransaction();
1830 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001831 if (isChanged) {
1832 removeAccountFromCacheLocked(accounts, account);
1833 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occured.
1834 sendAccountsChangedBroadcast(accounts.userId);
1835 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
1836 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
1837 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
1838 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001839 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001840 long id = Binder.clearCallingIdentity();
1841 try {
1842 int parentUserId = accounts.userId;
1843 if (canHaveProfile(parentUserId)) {
1844 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001845 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001846 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001847 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001848 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001849 }
1850 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001851 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001852 } finally {
1853 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001854 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07001855
1856 if (isChanged) {
1857 synchronized (accounts.credentialsPermissionNotificationIds) {
1858 for (Pair<Pair<Account, String>, Integer> key
1859 : accounts.credentialsPermissionNotificationIds.keySet()) {
1860 if (account.equals(key.first.first)
1861 && AccountManager.ACCOUNT_ACCESS_TOKEN.equals(key.first.second)) {
1862 final int uid = (Integer) key.second;
1863 mMessageHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
1864 account, uid, false));
1865 }
1866 }
1867 }
1868 }
1869
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001870 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001871 }
1872
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001873 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001874 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001875 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001876 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1877 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001878 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001879 + ", pid " + Binder.getCallingPid());
1880 }
Fred Quintana382601f2010-03-25 12:25:10 -07001881 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1882 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001883 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001884 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001885 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001886 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001887 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001888 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001889 db.beginTransaction();
1890 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001891 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001892 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001893 db.setTransactionSuccessful();
1894 } finally {
1895 db.endTransaction();
1896 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001897 }
Fred Quintana60307342009-03-24 22:48:12 -07001898 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001899 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001900 }
1901 }
1902
Carlos Valdivia91979be2015-05-22 14:11:35 -07001903 private void invalidateCustomTokenLocked(
1904 UserAccounts accounts,
1905 String accountType,
1906 String authToken) {
1907 if (authToken == null || accountType == null) {
1908 return;
1909 }
1910 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001911 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001912 }
1913
Amith Yamasani04e0d262012-02-14 11:50:53 -08001914 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1915 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001916 if (authToken == null || accountType == null) {
1917 return;
1918 }
Fred Quintana33269202009-04-20 16:05:10 -07001919 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001920 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1921 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1922 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1923 + " FROM " + CE_TABLE_ACCOUNTS
1924 + " JOIN " + CE_TABLE_AUTHTOKENS
1925 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1926 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1927 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1928 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001929 new String[]{authToken, accountType});
1930 try {
1931 while (cursor.moveToNext()) {
1932 long authTokenId = cursor.getLong(0);
1933 String accountName = cursor.getString(1);
1934 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001935 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001936 writeAuthTokenIntoCacheLocked(
1937 accounts,
1938 db,
1939 new Account(accountName, accountType),
1940 authTokenType,
1941 null);
Fred Quintana60307342009-03-24 22:48:12 -07001942 }
Fred Quintana33269202009-04-20 16:05:10 -07001943 } finally {
1944 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001945 }
1946 }
1947
Carlos Valdivia91979be2015-05-22 14:11:35 -07001948 private void saveCachedToken(
1949 UserAccounts accounts,
1950 Account account,
1951 String callerPkg,
1952 byte[] callerSigDigest,
1953 String tokenType,
1954 String token,
1955 long expiryMillis) {
1956
1957 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1958 return;
1959 }
1960 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001961 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001962 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001963 accounts.accountTokenCaches.put(
1964 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001965 }
1966 }
1967
Amith Yamasani04e0d262012-02-14 11:50:53 -08001968 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1969 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001970 if (account == null || type == null) {
1971 return false;
1972 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001973 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001974 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001975 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001976 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001977 db.beginTransaction();
1978 try {
1979 long accountId = getAccountIdLocked(db, account);
1980 if (accountId < 0) {
1981 return false;
1982 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001983 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001984 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1985 new String[]{type});
1986 ContentValues values = new ContentValues();
1987 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1988 values.put(AUTHTOKENS_TYPE, type);
1989 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001990 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001991 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001992 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001993 return true;
1994 }
Fred Quintana33269202009-04-20 16:05:10 -07001995 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001996 } finally {
1997 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001998 }
Fred Quintana60307342009-03-24 22:48:12 -07001999 }
2000 }
2001
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002002 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002003 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002004 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002005 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2006 Log.v(TAG, "peekAuthToken: " + account
2007 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002008 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002009 + ", pid " + Binder.getCallingPid());
2010 }
Fred Quintana382601f2010-03-25 12:25:10 -07002011 if (account == null) throw new IllegalArgumentException("account is null");
2012 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002013 int userId = UserHandle.getCallingUserId();
2014 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002015 String msg = String.format(
2016 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2017 callingUid,
2018 account.type);
2019 throw new SecurityException(msg);
2020 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002021 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002022 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2023 + callingUid);
2024 return null;
2025 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002026 long identityToken = clearCallingIdentity();
2027 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002028 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002029 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002030 } finally {
2031 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002032 }
Fred Quintana60307342009-03-24 22:48:12 -07002033 }
2034
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002035 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002036 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002037 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002038 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2039 Log.v(TAG, "setAuthToken: " + account
2040 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002041 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002042 + ", pid " + Binder.getCallingPid());
2043 }
Fred Quintana382601f2010-03-25 12:25:10 -07002044 if (account == null) throw new IllegalArgumentException("account is null");
2045 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002046 int userId = UserHandle.getCallingUserId();
2047 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002048 String msg = String.format(
2049 "uid %s cannot set auth tokens associated with accounts of type: %s",
2050 callingUid,
2051 account.type);
2052 throw new SecurityException(msg);
2053 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002054 long identityToken = clearCallingIdentity();
2055 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002056 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002057 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002058 } finally {
2059 restoreCallingIdentity(identityToken);
2060 }
Fred Quintana60307342009-03-24 22:48:12 -07002061 }
2062
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002063 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002064 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002065 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002066 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2067 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002068 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002069 + ", pid " + Binder.getCallingPid());
2070 }
Fred Quintana382601f2010-03-25 12:25:10 -07002071 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002072 int userId = UserHandle.getCallingUserId();
2073 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002074 String msg = String.format(
2075 "uid %s cannot set secrets for accounts of type: %s",
2076 callingUid,
2077 account.type);
2078 throw new SecurityException(msg);
2079 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002080 long identityToken = clearCallingIdentity();
2081 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002082 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002083 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002084 } finally {
2085 restoreCallingIdentity(identityToken);
2086 }
Fred Quintana60307342009-03-24 22:48:12 -07002087 }
2088
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002089 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2090 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002091 if (account == null) {
2092 return;
2093 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002094 boolean isChanged = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002095 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002096 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002097 db.beginTransaction();
2098 try {
2099 final ContentValues values = new ContentValues();
2100 values.put(ACCOUNTS_PASSWORD, password);
2101 final long accountId = getAccountIdLocked(db, account);
2102 if (accountId >= 0) {
2103 final String[] argsAccountId = {String.valueOf(accountId)};
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002104 db.update(
2105 CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
2106 db.delete(
2107 CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002108 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002109 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002110 db.setTransactionSuccessful();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002111 // If there is an account whose password will be updated and the database
2112 // transactions succeed, then we say that a change has occured. Even if the
2113 // new password is the same as the old and there were no authtokens to delete.
2114 isChanged = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002115 String action = (password == null || password.length() == 0) ?
2116 DebugDbHelper.ACTION_CLEAR_PASSWORD
2117 : DebugDbHelper.ACTION_SET_PASSWORD;
2118 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08002119 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002120 } finally {
2121 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002122 if (isChanged) {
2123 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2124 sendAccountsChangedBroadcast(accounts.userId);
2125 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002126 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002127 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002128 }
2129
Amith Yamasani04e0d262012-02-14 11:50:53 -08002130 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08002131 Log.i(TAG, "the accounts changed, sending broadcast of "
2132 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07002133 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07002134 }
2135
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002136 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002137 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002138 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002139 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2140 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002141 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002142 + ", pid " + Binder.getCallingPid());
2143 }
Fred Quintana382601f2010-03-25 12:25:10 -07002144 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002145 int userId = UserHandle.getCallingUserId();
2146 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002147 String msg = String.format(
2148 "uid %s cannot clear passwords for accounts of type: %s",
2149 callingUid,
2150 account.type);
2151 throw new SecurityException(msg);
2152 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002153 long identityToken = clearCallingIdentity();
2154 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002155 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002156 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002157 } finally {
2158 restoreCallingIdentity(identityToken);
2159 }
Fred Quintana60307342009-03-24 22:48:12 -07002160 }
2161
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002162 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002163 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002164 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002165 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2166 Log.v(TAG, "setUserData: " + account
2167 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002168 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002169 + ", pid " + Binder.getCallingPid());
2170 }
Fred Quintana382601f2010-03-25 12:25:10 -07002171 if (key == null) throw new IllegalArgumentException("key is null");
2172 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002173 int userId = UserHandle.getCallingUserId();
2174 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002175 String msg = String.format(
2176 "uid %s cannot set user data for accounts of type: %s",
2177 callingUid,
2178 account.type);
2179 throw new SecurityException(msg);
2180 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002181 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002182 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002183 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002184 synchronized (accounts.cacheLock) {
2185 if (!accountExistsCacheLocked(accounts, account)) {
2186 return;
2187 }
2188 setUserdataInternalLocked(accounts, account, key, value);
2189 }
Fred Quintana60307342009-03-24 22:48:12 -07002190 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002191 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002192 }
2193 }
2194
Simranjit Kohli858511c2016-03-10 18:36:11 +00002195 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2196 if (accounts.accountCache.containsKey(account.type)) {
2197 for (Account acc : accounts.accountCache.get(account.type)) {
2198 if (acc.name.equals(account.name)) {
2199 return true;
2200 }
2201 }
2202 }
2203 return false;
2204 }
2205
2206 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002207 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002208 if (account == null || key == null) {
2209 return;
2210 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002211 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2212 db.beginTransaction();
2213 try {
2214 long accountId = getAccountIdLocked(db, account);
2215 if (accountId < 0) {
2216 return;
2217 }
2218 long extrasId = getExtrasIdLocked(db, accountId, key);
2219 if (extrasId < 0) {
2220 extrasId = insertExtraLocked(db, accountId, key, value);
2221 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002222 return;
2223 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002224 } else {
2225 ContentValues values = new ContentValues();
2226 values.put(EXTRAS_VALUE, value);
2227 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
2228 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00002229 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002230 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002231 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2232 db.setTransactionSuccessful();
2233 } finally {
2234 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002235 }
2236 }
2237
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002238 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002239 if (result == null) {
2240 Log.e(TAG, "the result is unexpectedly null", new Exception());
2241 }
2242 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2243 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2244 + response);
2245 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002246 try {
2247 response.onResult(result);
2248 } catch (RemoteException e) {
2249 // if the caller is dead then there is no one to care about remote
2250 // exceptions
2251 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2252 Log.v(TAG, "failure while notifying response", e);
2253 }
2254 }
2255 }
2256
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002257 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002258 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2259 final String authTokenType)
2260 throws RemoteException {
2261 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002262 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2263
Fred Quintanad9640ec2012-05-23 12:37:00 -07002264 final int callingUid = getCallingUid();
2265 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002266 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002267 throw new SecurityException("can only call from system");
2268 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002269 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002270 long identityToken = clearCallingIdentity();
2271 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002272 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002273 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2274 false /* stripAuthTokenFromResult */, null /* accountName */,
2275 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002276 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002277 protected String toDebugString(long now) {
2278 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002279 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002280 + ", authTokenType " + authTokenType;
2281 }
2282
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002283 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002284 public void run() throws RemoteException {
2285 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2286 }
2287
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002288 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002289 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002290 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002291 if (result != null) {
2292 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2293 Bundle bundle = new Bundle();
2294 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2295 super.onResult(bundle);
2296 return;
2297 } else {
2298 super.onResult(result);
2299 }
2300 }
2301 }.bind();
2302 } finally {
2303 restoreCallingIdentity(identityToken);
2304 }
2305 }
2306
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002307 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002308 public void getAuthToken(
2309 IAccountManagerResponse response,
2310 final Account account,
2311 final String authTokenType,
2312 final boolean notifyOnAuthFailure,
2313 final boolean expectActivityLaunch,
2314 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002315 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002316 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2317 Log.v(TAG, "getAuthToken: " + account
2318 + ", response " + response
2319 + ", authTokenType " + authTokenType
2320 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2321 + ", expectActivityLaunch " + expectActivityLaunch
2322 + ", caller's uid " + Binder.getCallingUid()
2323 + ", pid " + Binder.getCallingPid());
2324 }
Fred Quintana382601f2010-03-25 12:25:10 -07002325 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002326 try {
2327 if (account == null) {
2328 Slog.w(TAG, "getAuthToken called with null account");
2329 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2330 return;
2331 }
2332 if (authTokenType == null) {
2333 Slog.w(TAG, "getAuthToken called with null authTokenType");
2334 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2335 return;
2336 }
2337 } catch (RemoteException e) {
2338 Slog.w(TAG, "Failed to report error back to the client." + e);
2339 return;
2340 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002341 int userId = UserHandle.getCallingUserId();
2342 long ident = Binder.clearCallingIdentity();
2343 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002344 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002345 try {
2346 accounts = getUserAccounts(userId);
2347 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2348 AuthenticatorDescription.newKey(account.type), accounts.userId);
2349 } finally {
2350 Binder.restoreCallingIdentity(ident);
2351 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002352
Costin Manolachea40c6302010-12-13 14:50:45 -08002353 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002354 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002355
2356 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002357 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002358 final boolean permissionGranted =
2359 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002360
Carlos Valdivia91979be2015-05-22 14:11:35 -07002361 // Get the calling package. We will use it for the purpose of caching.
2362 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002363 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002364 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002365 try {
2366 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2367 } finally {
2368 Binder.restoreCallingIdentity(ident);
2369 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002370 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2371 String msg = String.format(
2372 "Uid %s is attempting to illegally masquerade as package %s!",
2373 callerUid,
2374 callerPkg);
2375 throw new SecurityException(msg);
2376 }
2377
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002378 // let authenticator know the identity of the caller
2379 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2380 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002381
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002382 if (notifyOnAuthFailure) {
2383 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002384 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002385
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002386 long identityToken = clearCallingIdentity();
2387 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002388 // Distill the caller's package signatures into a single digest.
2389 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2390
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002391 // if the caller has permission, do the peek. otherwise go the more expensive
2392 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002393 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002394 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002395 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002396 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002397 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2398 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2399 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002400 onResult(response, result);
2401 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002402 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002403 }
2404
Carlos Valdivia91979be2015-05-22 14:11:35 -07002405 if (customTokens) {
2406 /*
2407 * Look up tokens in the new cache only if the loginOptions don't have parameters
2408 * outside of those expected to be injected by the AccountManager, e.g.
2409 * ANDORID_PACKAGE_NAME.
2410 */
2411 String token = readCachedTokenInternal(
2412 accounts,
2413 account,
2414 authTokenType,
2415 callerPkg,
2416 callerPkgSigDigest);
2417 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002418 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2419 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2420 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002421 Bundle result = new Bundle();
2422 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2423 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2424 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2425 onResult(response, result);
2426 return;
2427 }
2428 }
2429
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002430 new Session(
2431 accounts,
2432 response,
2433 account.type,
2434 expectActivityLaunch,
2435 false /* stripAuthTokenFromResult */,
2436 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002437 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002438 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002439 protected String toDebugString(long now) {
2440 if (loginOptions != null) loginOptions.keySet();
2441 return super.toDebugString(now) + ", getAuthToken"
2442 + ", " + account
2443 + ", authTokenType " + authTokenType
2444 + ", loginOptions " + loginOptions
2445 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2446 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002447
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002448 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002449 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002450 // If the caller doesn't have permission then create and return the
2451 // "grant permission" intent instead of the "getAuthToken" intent.
2452 if (!permissionGranted) {
2453 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2454 } else {
2455 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2456 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002457 }
2458
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002459 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002460 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002461 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002462 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002463 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002464 Intent intent = newGrantCredentialsPermissionIntent(
2465 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002466 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002467 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002468 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002469 authTokenType,
2470 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002471 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002472 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002473 onResult(bundle);
2474 return;
2475 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002476 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002477 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002478 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2479 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002480 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002481 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002482 "the type and name should not be empty");
2483 return;
2484 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002485 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002486 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002487 saveAuthTokenToDatabase(
2488 mAccounts,
2489 resultAccount,
2490 authTokenType,
2491 authToken);
2492 }
2493 long expiryMillis = result.getLong(
2494 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2495 if (customTokens
2496 && expiryMillis > System.currentTimeMillis()) {
2497 saveCachedToken(
2498 mAccounts,
2499 account,
2500 callerPkg,
2501 callerPkgSigDigest,
2502 authTokenType,
2503 authToken,
2504 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002505 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002506 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002507
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002508 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002509 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002510 /*
2511 * Make sure that the supplied intent is owned by the authenticator
2512 * giving it to the system. Otherwise a malicious authenticator could
2513 * have users launching arbitrary activities by tricking users to
2514 * interact with malicious notifications.
2515 */
2516 checkKeyIntent(
2517 Binder.getCallingUid(),
2518 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002519 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002520 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002521 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002522 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002523 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002524 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002525 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002526 }.bind();
2527 } finally {
2528 restoreCallingIdentity(identityToken);
2529 }
Fred Quintana60307342009-03-24 22:48:12 -07002530 }
2531
Carlos Valdivia91979be2015-05-22 14:11:35 -07002532 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2533 MessageDigest digester;
2534 try {
2535 digester = MessageDigest.getInstance("SHA-256");
2536 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2537 callerPkg, PackageManager.GET_SIGNATURES);
2538 for (Signature sig : pkgInfo.signatures) {
2539 digester.update(sig.toByteArray());
2540 }
2541 } catch (NoSuchAlgorithmException x) {
2542 Log.wtf(TAG, "SHA-256 should be available", x);
2543 digester = null;
2544 } catch (NameNotFoundException e) {
2545 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2546 digester = null;
2547 }
2548 return (digester == null) ? null : digester.digest();
2549 }
2550
Dianne Hackborn41203752012-08-31 14:05:51 -07002551 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002552 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002553 int uid = intent.getIntExtra(
2554 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2555 String authTokenType = intent.getStringExtra(
2556 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002557 final String titleAndSubtitle =
2558 mContext.getString(R.string.permission_request_notification_with_subtitle,
2559 account.name);
2560 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002561 String title = titleAndSubtitle;
2562 String subtitle = "";
2563 if (index > 0) {
2564 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002565 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002566 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002567 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002568 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002569 Notification n = new Notification.Builder(contextForUser)
2570 .setSmallIcon(android.R.drawable.stat_sys_warning)
2571 .setWhen(0)
2572 .setColor(contextForUser.getColor(
2573 com.android.internal.R.color.system_notification_accent_color))
2574 .setContentTitle(title)
2575 .setContentText(subtitle)
2576 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2577 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2578 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002579 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002580 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002581 }
2582
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002583 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
2584 int uid, AccountAuthenticatorResponse response, String authTokenType,
2585 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002586
2587 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002588
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002589 if (startInNewTask) {
2590 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
2591 // Since it was set in Eclair+ we can't change it without breaking apps using
2592 // the intent from a non-Activity context. This is the default behavior.
2593 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2594 }
2595 intent.addCategory(String.valueOf(getCredentialPermissionNotificationId(account,
2596 authTokenType, uid) + (packageName != null ? packageName : "")));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002597 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002598 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2599 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002600 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002601
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002602 return intent;
2603 }
2604
2605 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2606 int uid) {
2607 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002608 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002609 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002610 final Pair<Pair<Account, String>, Integer> key =
2611 new Pair<Pair<Account, String>, Integer>(
2612 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002613 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002614 if (id == null) {
2615 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002616 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002617 }
2618 }
2619 return id;
2620 }
2621
Amith Yamasani04e0d262012-02-14 11:50:53 -08002622 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002623 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002624 synchronized (accounts.signinRequiredNotificationIds) {
2625 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002626 if (id == null) {
2627 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002628 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002629 }
2630 }
2631 return id;
2632 }
2633
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002634 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002635 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002636 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002637 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002638 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002639 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2640 Log.v(TAG, "addAccount: accountType " + accountType
2641 + ", response " + response
2642 + ", authTokenType " + authTokenType
2643 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2644 + ", expectActivityLaunch " + expectActivityLaunch
2645 + ", caller's uid " + Binder.getCallingUid()
2646 + ", pid " + Binder.getCallingPid());
2647 }
Fred Quintana382601f2010-03-25 12:25:10 -07002648 if (response == null) throw new IllegalArgumentException("response is null");
2649 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002650
Amith Yamasani71e6c692013-03-24 17:39:28 -07002651 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002652 final int uid = Binder.getCallingUid();
2653 final int userId = UserHandle.getUserId(uid);
2654 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002655 try {
2656 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2657 "User is not allowed to add an account!");
2658 } catch (RemoteException re) {
2659 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002660 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002661 return;
2662 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002663 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002664 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002665 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2666 "User cannot modify accounts of this type (policy).");
2667 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002668 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002669 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2670 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002671 return;
2672 }
2673
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002674 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002675 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2676 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2677 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2678
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002679 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002680 long identityToken = clearCallingIdentity();
2681 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002682 UserAccounts accounts = getUserAccounts(usrId);
2683 logRecordWithUid(
2684 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002685 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002686 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002687 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002688 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002689 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002690 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002691 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002692 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002693
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002694 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002695 protected String toDebugString(long now) {
2696 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002697 + ", accountType " + accountType
2698 + ", requiredFeatures "
2699 + (requiredFeatures != null
2700 ? TextUtils.join(",", requiredFeatures)
2701 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002702 }
2703 }.bind();
2704 } finally {
2705 restoreCallingIdentity(identityToken);
2706 }
Fred Quintana60307342009-03-24 22:48:12 -07002707 }
2708
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002709 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002710 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2711 final String authTokenType, final String[] requiredFeatures,
2712 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002713 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002714 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002715 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2716 Log.v(TAG, "addAccount: accountType " + accountType
2717 + ", response " + response
2718 + ", authTokenType " + authTokenType
2719 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2720 + ", expectActivityLaunch " + expectActivityLaunch
2721 + ", caller's uid " + Binder.getCallingUid()
2722 + ", pid " + Binder.getCallingPid()
2723 + ", for user id " + userId);
2724 }
2725 if (response == null) throw new IllegalArgumentException("response is null");
2726 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002727 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002728 if (isCrossUser(callingUid, userId)) {
2729 throw new SecurityException(
2730 String.format(
2731 "User %s trying to add account for %s" ,
2732 UserHandle.getCallingUserId(),
2733 userId));
2734 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002735
2736 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002737 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002738 try {
2739 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2740 "User is not allowed to add an account!");
2741 } catch (RemoteException re) {
2742 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002743 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002744 return;
2745 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002746 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002747 try {
2748 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2749 "User cannot modify accounts of this type (policy).");
2750 } catch (RemoteException re) {
2751 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002752 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2753 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002754 return;
2755 }
2756
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002757 final int pid = Binder.getCallingPid();
2758 final int uid = Binder.getCallingUid();
2759 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2760 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2761 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2762
2763 long identityToken = clearCallingIdentity();
2764 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002765 UserAccounts accounts = getUserAccounts(userId);
2766 logRecordWithUid(
2767 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002768 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002769 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002770 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002771 @Override
2772 public void run() throws RemoteException {
2773 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2774 options);
2775 }
2776
2777 @Override
2778 protected String toDebugString(long now) {
2779 return super.toDebugString(now) + ", addAccount"
2780 + ", accountType " + accountType
2781 + ", requiredFeatures "
2782 + (requiredFeatures != null
2783 ? TextUtils.join(",", requiredFeatures)
2784 : null);
2785 }
2786 }.bind();
2787 } finally {
2788 restoreCallingIdentity(identityToken);
2789 }
2790 }
2791
Sandra Kwan78812282015-11-04 11:19:47 -08002792 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002793 public void startAddAccountSession(
2794 final IAccountManagerResponse response,
2795 final String accountType,
2796 final String authTokenType,
2797 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002798 final boolean expectActivityLaunch,
2799 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002800 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002801 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2802 Log.v(TAG,
2803 "startAddAccountSession: accountType " + accountType
2804 + ", response " + response
2805 + ", authTokenType " + authTokenType
2806 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2807 + ", expectActivityLaunch " + expectActivityLaunch
2808 + ", caller's uid " + Binder.getCallingUid()
2809 + ", pid " + Binder.getCallingPid());
2810 }
2811 if (response == null) {
2812 throw new IllegalArgumentException("response is null");
2813 }
2814 if (accountType == null) {
2815 throw new IllegalArgumentException("accountType is null");
2816 }
2817
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002818 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002819 // Only allow system to start session
2820 if (!isSystemUid(uid)) {
2821 String msg = String.format(
2822 "uid %s cannot stat add account session.",
2823 uid);
2824 throw new SecurityException(msg);
2825 }
2826
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002827 final int userId = UserHandle.getUserId(uid);
2828 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002829 try {
2830 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2831 "User is not allowed to add an account!");
2832 } catch (RemoteException re) {
2833 }
2834 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2835 return;
2836 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002837 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002838 try {
2839 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2840 "User cannot modify accounts of this type (policy).");
2841 } catch (RemoteException re) {
2842 }
2843 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2844 userId);
2845 return;
2846 }
Sandra Kwan78812282015-11-04 11:19:47 -08002847 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002848 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2849 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2850 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2851
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002852 // Check to see if the Password should be included to the caller.
2853 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2854 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07002855 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002856
Sandra Kwan78812282015-11-04 11:19:47 -08002857 int usrId = UserHandle.getCallingUserId();
2858 long identityToken = clearCallingIdentity();
2859 try {
2860 UserAccounts accounts = getUserAccounts(usrId);
2861 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2862 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002863 new StartAccountSession(
2864 accounts,
2865 response,
2866 accountType,
2867 expectActivityLaunch,
2868 null /* accountName */,
2869 false /* authDetailsRequired */,
2870 true /* updateLastAuthenticationTime */,
2871 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002872 @Override
2873 public void run() throws RemoteException {
2874 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2875 requiredFeatures, options);
2876 }
2877
2878 @Override
2879 protected String toDebugString(long now) {
2880 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2881 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2882 + accountType + ", requiredFeatures "
2883 + (requiredFeatures != null ? requiredFeaturesStr : null);
2884 }
2885 }.bind();
2886 } finally {
2887 restoreCallingIdentity(identityToken);
2888 }
2889 }
2890
2891 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2892 private abstract class StartAccountSession extends Session {
2893
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002894 private final boolean mIsPasswordForwardingAllowed;
2895
2896 public StartAccountSession(
2897 UserAccounts accounts,
2898 IAccountManagerResponse response,
2899 String accountType,
2900 boolean expectActivityLaunch,
2901 String accountName,
2902 boolean authDetailsRequired,
2903 boolean updateLastAuthenticationTime,
2904 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002905 super(accounts, response, accountType, expectActivityLaunch,
2906 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2907 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002908 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002909 }
2910
2911 @Override
2912 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002913 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002914 mNumResults++;
2915 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002916 if (result != null
2917 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002918 checkKeyIntent(
2919 Binder.getCallingUid(),
2920 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002921 // Omit passwords if the caller isn't permitted to see them.
2922 if (!mIsPasswordForwardingAllowed) {
2923 result.remove(AccountManager.KEY_PASSWORD);
2924 }
Sandra Kwan78812282015-11-04 11:19:47 -08002925 }
Sandra Kwan78812282015-11-04 11:19:47 -08002926 IAccountManagerResponse response;
2927 if (mExpectActivityLaunch && result != null
2928 && result.containsKey(AccountManager.KEY_INTENT)) {
2929 response = mResponse;
2930 } else {
2931 response = getResponseAndClose();
2932 }
2933 if (response == null) {
2934 return;
2935 }
2936 if (result == null) {
2937 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2938 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2939 + response);
2940 }
2941 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2942 "null bundle returned");
2943 return;
2944 }
2945
2946 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2947 // All AccountManager error codes are greater
2948 // than 0
2949 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2950 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2951 return;
2952 }
2953
2954 // Strip auth token from result.
2955 result.remove(AccountManager.KEY_AUTHTOKEN);
2956
2957 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2958 Log.v(TAG,
2959 getClass().getSimpleName() + " calling onResult() on response " + response);
2960 }
2961
2962 // Get the session bundle created by authenticator. The
2963 // bundle contains data necessary for finishing the session
2964 // later. The session bundle will be encrypted here and
2965 // decrypted later when trying to finish the session.
2966 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2967 if (sessionBundle != null) {
2968 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2969 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002970 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002971 Log.w(TAG, "Account type in session bundle doesn't match request.");
2972 }
2973 // Add accountType info to session bundle. This will
2974 // override any value set by authenticator.
2975 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2976
2977 // Encrypt session bundle before returning to caller.
2978 try {
2979 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2980 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2981 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2982 } catch (GeneralSecurityException e) {
2983 if (Log.isLoggable(TAG, Log.DEBUG)) {
2984 Log.v(TAG, "Failed to encrypt session bundle!", e);
2985 }
2986 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2987 "failed to encrypt session bundle");
2988 return;
2989 }
2990 }
2991
2992 sendResponse(response, result);
2993 }
2994 }
2995
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002996 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002997 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002998 @NonNull Bundle sessionBundle,
2999 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003000 Bundle appInfo,
3001 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003002 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003003 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3005 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003006 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003007 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003008 + ", caller's uid " + callingUid
3009 + ", caller's user id " + UserHandle.getCallingUserId()
3010 + ", pid " + Binder.getCallingPid()
3011 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003012 }
3013 if (response == null) {
3014 throw new IllegalArgumentException("response is null");
3015 }
3016
3017 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3018 // Account type is added to it before encryption.
3019 if (sessionBundle == null || sessionBundle.size() == 0) {
3020 throw new IllegalArgumentException("sessionBundle is empty");
3021 }
3022
Sandra Kwan0b84b452016-01-20 15:25:42 -08003023 // Only allow the system process to finish session for other users
3024 if (isCrossUser(callingUid, userId)) {
3025 throw new SecurityException(
3026 String.format(
3027 "User %s trying to finish session for %s without cross user permission",
3028 UserHandle.getCallingUserId(),
3029 userId));
3030 }
3031
Sandra Kwana578d112015-12-16 16:01:43 -08003032 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08003033 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08003034 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08003035 "uid %s cannot finish session because it's not system uid.",
3036 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08003037 throw new SecurityException(msg);
3038 }
3039
Sandra Kwan0b84b452016-01-20 15:25:42 -08003040 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003041 sendErrorResponse(response,
3042 AccountManager.ERROR_CODE_USER_RESTRICTED,
3043 "User is not allowed to add an account!");
3044 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3045 return;
3046 }
3047
3048 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003049 final Bundle decryptedBundle;
3050 final String accountType;
3051 // First decrypt session bundle to get account type for checking permission.
3052 try {
3053 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3054 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3055 if (decryptedBundle == null) {
3056 sendErrorResponse(
3057 response,
3058 AccountManager.ERROR_CODE_BAD_REQUEST,
3059 "failed to decrypt session bundle");
3060 return;
3061 }
3062 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3063 // Account type cannot be null. This should not happen if session bundle was created
3064 // properly by #StartAccountSession.
3065 if (TextUtils.isEmpty(accountType)) {
3066 sendErrorResponse(
3067 response,
3068 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3069 "accountType is empty");
3070 return;
3071 }
3072
3073 // If by any chances, decryptedBundle contains colliding keys with
3074 // system info
3075 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3076 // update credentials flow, we should replace with the new values of the current call.
3077 if (appInfo != null) {
3078 decryptedBundle.putAll(appInfo);
3079 }
3080
3081 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003082 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003083 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3084 } catch (GeneralSecurityException e) {
3085 if (Log.isLoggable(TAG, Log.DEBUG)) {
3086 Log.v(TAG, "Failed to decrypt session bundle!", e);
3087 }
3088 sendErrorResponse(
3089 response,
3090 AccountManager.ERROR_CODE_BAD_REQUEST,
3091 "failed to decrypt session bundle");
3092 return;
3093 }
3094
Sandra Kwan0b84b452016-01-20 15:25:42 -08003095 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003096 sendErrorResponse(
3097 response,
3098 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3099 "User cannot modify accounts of this type (policy).");
3100 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3101 userId);
3102 return;
3103 }
3104
3105 long identityToken = clearCallingIdentity();
3106 try {
3107 UserAccounts accounts = getUserAccounts(userId);
3108 logRecordWithUid(
3109 accounts,
3110 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3111 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003112 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003113 new Session(
3114 accounts,
3115 response,
3116 accountType,
3117 expectActivityLaunch,
3118 true /* stripAuthTokenFromResult */,
3119 null /* accountName */,
3120 false /* authDetailsRequired */,
3121 true /* updateLastAuthenticationTime */) {
3122 @Override
3123 public void run() throws RemoteException {
3124 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3125 }
3126
3127 @Override
3128 protected String toDebugString(long now) {
3129 return super.toDebugString(now)
3130 + ", finishSession"
3131 + ", accountType " + accountType;
3132 }
3133 }.bind();
3134 } finally {
3135 restoreCallingIdentity(identityToken);
3136 }
3137 }
3138
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003139 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003140 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3141 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3142 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3143 long identityToken = clearCallingIdentity();
3144 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003145 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003146 } finally {
3147 restoreCallingIdentity(identityToken);
3148 }
3149 }
3150
3151 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003152 public void confirmCredentialsAsUser(
3153 IAccountManagerResponse response,
3154 final Account account,
3155 final Bundle options,
3156 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003157 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003158 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003159 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003160 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3161 Log.v(TAG, "confirmCredentials: " + account
3162 + ", response " + response
3163 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003164 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003165 + ", pid " + Binder.getCallingPid());
3166 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003167 // Only allow the system process to read accounts of other users
3168 if (isCrossUser(callingUid, userId)) {
3169 throw new SecurityException(
3170 String.format(
3171 "User %s trying to confirm account credentials for %s" ,
3172 UserHandle.getCallingUserId(),
3173 userId));
3174 }
Fred Quintana382601f2010-03-25 12:25:10 -07003175 if (response == null) throw new IllegalArgumentException("response is null");
3176 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003177 long identityToken = clearCallingIdentity();
3178 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003179 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003180 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003181 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003182 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003183 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003184 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003185 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003186 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003187 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003188 protected String toDebugString(long now) {
3189 return super.toDebugString(now) + ", confirmCredentials"
3190 + ", " + account;
3191 }
3192 }.bind();
3193 } finally {
3194 restoreCallingIdentity(identityToken);
3195 }
Fred Quintana60307342009-03-24 22:48:12 -07003196 }
3197
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003198 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003199 public void updateCredentials(IAccountManagerResponse response, final Account account,
3200 final String authTokenType, final boolean expectActivityLaunch,
3201 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003202 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003203 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3204 Log.v(TAG, "updateCredentials: " + account
3205 + ", response " + response
3206 + ", authTokenType " + authTokenType
3207 + ", expectActivityLaunch " + expectActivityLaunch
3208 + ", caller's uid " + Binder.getCallingUid()
3209 + ", pid " + Binder.getCallingPid());
3210 }
Fred Quintana382601f2010-03-25 12:25:10 -07003211 if (response == null) throw new IllegalArgumentException("response is null");
3212 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003213 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003214 long identityToken = clearCallingIdentity();
3215 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003216 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003217 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003218 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003219 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003220 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003221 public void run() throws RemoteException {
3222 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3223 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003224 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003225 protected String toDebugString(long now) {
3226 if (loginOptions != null) loginOptions.keySet();
3227 return super.toDebugString(now) + ", updateCredentials"
3228 + ", " + account
3229 + ", authTokenType " + authTokenType
3230 + ", loginOptions " + loginOptions;
3231 }
3232 }.bind();
3233 } finally {
3234 restoreCallingIdentity(identityToken);
3235 }
Fred Quintana60307342009-03-24 22:48:12 -07003236 }
3237
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003238 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003239 public void startUpdateCredentialsSession(
3240 IAccountManagerResponse response,
3241 final Account account,
3242 final String authTokenType,
3243 final boolean expectActivityLaunch,
3244 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003245 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003246 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3247 Log.v(TAG,
3248 "startUpdateCredentialsSession: " + account + ", response " + response
3249 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3250 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3251 + ", pid " + Binder.getCallingPid());
3252 }
3253 if (response == null) {
3254 throw new IllegalArgumentException("response is null");
3255 }
3256 if (account == null) {
3257 throw new IllegalArgumentException("account is null");
3258 }
Sandra Kwana578d112015-12-16 16:01:43 -08003259
3260 final int uid = Binder.getCallingUid();
3261 // Only allow system to start session
3262 if (!isSystemUid(uid)) {
3263 String msg = String.format(
3264 "uid %s cannot start update credentials session.",
3265 uid);
3266 throw new SecurityException(msg);
3267 }
3268
Sandra Kwane68c37e2015-11-12 17:11:49 -08003269 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003270
3271 // Check to see if the Password should be included to the caller.
3272 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3273 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003274 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003275
Sandra Kwane68c37e2015-11-12 17:11:49 -08003276 long identityToken = clearCallingIdentity();
3277 try {
3278 UserAccounts accounts = getUserAccounts(userId);
3279 new StartAccountSession(
3280 accounts,
3281 response,
3282 account.type,
3283 expectActivityLaunch,
3284 account.name,
3285 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003286 true /* updateLastCredentialTime */,
3287 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003288 @Override
3289 public void run() throws RemoteException {
3290 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3291 loginOptions);
3292 }
3293
3294 @Override
3295 protected String toDebugString(long now) {
3296 if (loginOptions != null)
3297 loginOptions.keySet();
3298 return super.toDebugString(now)
3299 + ", startUpdateCredentialsSession"
3300 + ", " + account
3301 + ", authTokenType " + authTokenType
3302 + ", loginOptions " + loginOptions;
3303 }
3304 }.bind();
3305 } finally {
3306 restoreCallingIdentity(identityToken);
3307 }
3308 }
3309
3310 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003311 public void isCredentialsUpdateSuggested(
3312 IAccountManagerResponse response,
3313 final Account account,
3314 final String statusToken) {
3315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3316 Log.v(TAG,
3317 "isCredentialsUpdateSuggested: " + account + ", response " + response
3318 + ", caller's uid " + Binder.getCallingUid()
3319 + ", pid " + Binder.getCallingPid());
3320 }
3321 if (response == null) {
3322 throw new IllegalArgumentException("response is null");
3323 }
3324 if (account == null) {
3325 throw new IllegalArgumentException("account is null");
3326 }
3327 if (TextUtils.isEmpty(statusToken)) {
3328 throw new IllegalArgumentException("status token is empty");
3329 }
3330
3331 int uid = Binder.getCallingUid();
3332 // Only allow system to start session
3333 if (!isSystemUid(uid)) {
3334 String msg = String.format(
3335 "uid %s cannot stat add account session.",
3336 uid);
3337 throw new SecurityException(msg);
3338 }
3339
3340 int usrId = UserHandle.getCallingUserId();
3341 long identityToken = clearCallingIdentity();
3342 try {
3343 UserAccounts accounts = getUserAccounts(usrId);
3344 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3345 false /* stripAuthTokenFromResult */, account.name,
3346 false /* authDetailsRequired */) {
3347 @Override
3348 protected String toDebugString(long now) {
3349 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3350 + ", " + account;
3351 }
3352
3353 @Override
3354 public void run() throws RemoteException {
3355 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3356 }
3357
3358 @Override
3359 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003360 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003361 IAccountManagerResponse response = getResponseAndClose();
3362 if (response == null) {
3363 return;
3364 }
3365
3366 if (result == null) {
3367 sendErrorResponse(
3368 response,
3369 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3370 "null bundle");
3371 return;
3372 }
3373
3374 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3375 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3376 + response);
3377 }
3378 // Check to see if an error occurred. We know if an error occurred because all
3379 // error codes are greater than 0.
3380 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3381 sendErrorResponse(response,
3382 result.getInt(AccountManager.KEY_ERROR_CODE),
3383 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3384 return;
3385 }
3386 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3387 sendErrorResponse(
3388 response,
3389 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3390 "no result in response");
3391 return;
3392 }
3393 final Bundle newResult = new Bundle();
3394 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3395 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3396 sendResponse(response, newResult);
3397 }
3398 }.bind();
3399 } finally {
3400 restoreCallingIdentity(identityToken);
3401 }
3402 }
3403
3404 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003405 public void editProperties(IAccountManagerResponse response, final String accountType,
3406 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003407 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003408 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3409 Log.v(TAG, "editProperties: accountType " + accountType
3410 + ", response " + response
3411 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003412 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003413 + ", pid " + Binder.getCallingPid());
3414 }
Fred Quintana382601f2010-03-25 12:25:10 -07003415 if (response == null) throw new IllegalArgumentException("response is null");
3416 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003417 int userId = UserHandle.getCallingUserId();
3418 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003419 String msg = String.format(
3420 "uid %s cannot edit authenticator properites for account type: %s",
3421 callingUid,
3422 accountType);
3423 throw new SecurityException(msg);
3424 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003425 long identityToken = clearCallingIdentity();
3426 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003427 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003428 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003429 true /* stripAuthTokenFromResult */, null /* accountName */,
3430 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003431 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003432 public void run() throws RemoteException {
3433 mAuthenticator.editProperties(this, mAccountType);
3434 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003435 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003436 protected String toDebugString(long now) {
3437 return super.toDebugString(now) + ", editProperties"
3438 + ", accountType " + accountType;
3439 }
3440 }.bind();
3441 } finally {
3442 restoreCallingIdentity(identityToken);
3443 }
Fred Quintana60307342009-03-24 22:48:12 -07003444 }
3445
Amith Yamasani12747872015-12-07 14:19:49 -08003446 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003447 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3448 @NonNull UserHandle userHandle) {
3449 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3450 throw new SecurityException("Can be called only by system UID");
3451 }
3452 Preconditions.checkNotNull(account, "account cannot be null");
3453 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3454 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3455
3456 final int userId = userHandle.getIdentifier();
3457
3458 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3459
3460 try {
3461
3462 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3463 // Use null token which means any token. Having a token means the package
3464 // is trusted by the authenticator, hence it is fine to access the account.
3465 if (permissionIsGranted(account, null, uid, userId)) {
3466 return true;
3467 }
3468 // In addition to the permissions required to get an auth token we also allow
3469 // the account to be accessed by holders of the get accounts permissions.
3470 return checkUidPermission(Manifest.permission.GET_ACCOUNTS_PRIVILEGED, uid, packageName)
3471 || checkUidPermission(Manifest.permission.GET_ACCOUNTS, uid, packageName);
3472 } catch (NameNotFoundException e) {
3473 return false;
3474 }
3475 }
3476
3477 private boolean checkUidPermission(String permission, int uid, String opPackageName) {
3478 final long identity = Binder.clearCallingIdentity();
3479 try {
3480 IPackageManager pm = ActivityThread.getPackageManager();
3481 if (pm.checkUidPermission(permission, uid) != PackageManager.PERMISSION_GRANTED) {
3482 return false;
3483 }
3484 final int opCode = AppOpsManager.permissionToOpCode(permission);
3485 return (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOpNoThrow(
3486 opCode, uid, opPackageName) == AppOpsManager.MODE_ALLOWED);
3487 } catch (RemoteException e) {
3488 /* ignore - local call */
3489 } finally {
3490 Binder.restoreCallingIdentity(identity);
3491 }
3492 return false;
3493 }
3494
3495 @Override
3496 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3497 @NonNull String packageName, @NonNull UserHandle userHandle) {
3498 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3499 throw new SecurityException("Can be called only by system UID");
3500 }
3501
3502 Preconditions.checkNotNull(account, "account cannot be null");
3503 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3504 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3505
3506 final int userId = userHandle.getIdentifier();
3507
3508 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3509
3510 final int uid;
3511 try {
3512 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3513 } catch (NameNotFoundException e) {
3514 Slog.e(TAG, "Unknown package " + packageName);
3515 return null;
3516 }
3517
3518 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3519
3520 return PendingIntent.getActivityAsUser(
3521 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3522 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3523 null, new UserHandle(userId)).getIntentSender();
3524 }
3525
3526 private Intent newRequestAccountAccessIntent(Account account, String packageName,
3527 int uid, RemoteCallback callback) {
3528 return newGrantCredentialsPermissionIntent(account, packageName, uid,
3529 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
3530 @Override
3531 public void onResult(Bundle value) throws RemoteException {
3532 handleAuthenticatorResponse(true);
3533 }
3534
3535 @Override
3536 public void onRequestContinued() {
3537 /* ignore */
3538 }
3539
3540 @Override
3541 public void onError(int errorCode, String errorMessage) throws RemoteException {
3542 handleAuthenticatorResponse(false);
3543 }
3544
3545 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
3546 cancelNotification(getCredentialPermissionNotificationId(account,
3547 AccountManager.ACCOUNT_ACCESS_TOKEN, uid), packageName,
3548 UserHandle.getUserHandleForUid(uid));
3549 if (callback != null) {
3550 Bundle result = new Bundle();
3551 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
3552 callback.sendResult(result);
3553 }
3554 }
3555 }), AccountManager.ACCOUNT_ACCESS_TOKEN, false);
3556 }
3557
3558 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08003559 public boolean someUserHasAccount(@NonNull final Account account) {
3560 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3561 throw new SecurityException("Only system can check for accounts across users");
3562 }
3563 final long token = Binder.clearCallingIdentity();
3564 try {
3565 AccountAndUser[] allAccounts = getAllAccounts();
3566 for (int i = allAccounts.length - 1; i >= 0; i--) {
3567 if (allAccounts[i].account.equals(account)) {
3568 return true;
3569 }
3570 }
3571 return false;
3572 } finally {
3573 Binder.restoreCallingIdentity(token);
3574 }
3575 }
3576
Fred Quintana33269202009-04-20 16:05:10 -07003577 private class GetAccountsByTypeAndFeatureSession extends Session {
3578 private final String[] mFeatures;
3579 private volatile Account[] mAccountsOfType = null;
3580 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3581 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003582 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003583
Amith Yamasani04e0d262012-02-14 11:50:53 -08003584 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003585 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003586 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003587 true /* stripAuthTokenFromResult */, null /* accountName */,
3588 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003589 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003590 mFeatures = features;
3591 }
3592
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003593 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003594 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003595 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003596 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3597 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003598 }
Fred Quintana33269202009-04-20 16:05:10 -07003599 // check whether each account matches the requested features
3600 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3601 mCurrentAccount = 0;
3602
3603 checkAccount();
3604 }
3605
3606 public void checkAccount() {
3607 if (mCurrentAccount >= mAccountsOfType.length) {
3608 sendResult();
3609 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003610 }
Fred Quintana33269202009-04-20 16:05:10 -07003611
Fred Quintana29e94b82010-03-10 12:11:51 -08003612 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3613 if (accountAuthenticator == null) {
3614 // It is possible that the authenticator has died, which is indicated by
3615 // mAuthenticator being set to null. If this happens then just abort.
3616 // There is no need to send back a result or error in this case since
3617 // that already happened when mAuthenticator was cleared.
3618 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3619 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3620 + " connected to the authenticator, " + toDebugString());
3621 }
3622 return;
3623 }
Fred Quintana33269202009-04-20 16:05:10 -07003624 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003625 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003626 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003627 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003628 }
3629 }
3630
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003631 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003632 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003633 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003634 mNumResults++;
3635 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003636 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003637 return;
3638 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003639 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003640 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3641 }
3642 mCurrentAccount++;
3643 checkAccount();
3644 }
3645
3646 public void sendResult() {
3647 IAccountManagerResponse response = getResponseAndClose();
3648 if (response != null) {
3649 try {
3650 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3651 for (int i = 0; i < accounts.length; i++) {
3652 accounts[i] = mAccountsWithFeatures.get(i);
3653 }
Fred Quintana56285a62010-12-02 14:20:51 -08003654 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3655 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3656 + response);
3657 }
Fred Quintana33269202009-04-20 16:05:10 -07003658 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003659 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003660 response.onResult(result);
3661 } catch (RemoteException e) {
3662 // if the caller is dead then there is no one to care about remote exceptions
3663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3664 Log.v(TAG, "failure while notifying response", e);
3665 }
3666 }
3667 }
3668 }
3669
3670
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003671 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003672 protected String toDebugString(long now) {
3673 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3674 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3675 }
3676 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003677
Amith Yamasani04e0d262012-02-14 11:50:53 -08003678 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003679 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003680 * @hide
3681 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003682 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003683 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003684 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003685 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3686 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003687 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003688 return new Account[0];
3689 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003690 long identityToken = clearCallingIdentity();
3691 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003692 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003693 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003694 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003695 callingUid,
3696 null, // packageName
3697 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003698 } finally {
3699 restoreCallingIdentity(identityToken);
3700 }
3701 }
3702
Amith Yamasanif29f2362012-04-05 18:29:52 -07003703 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003704 * Returns accounts for all running users.
3705 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003706 * @hide
3707 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003708 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003709 public AccountAndUser[] getRunningAccounts() {
3710 final int[] runningUserIds;
3711 try {
3712 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3713 } catch (RemoteException e) {
3714 // Running in system_server; should never happen
3715 throw new RuntimeException(e);
3716 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003717 return getAccounts(runningUserIds);
3718 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003719
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003720 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003721 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003722 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003723 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003724 final int[] userIds = new int[users.size()];
3725 for (int i = 0; i < userIds.length; i++) {
3726 userIds[i] = users.get(i).id;
3727 }
3728 return getAccounts(userIds);
3729 }
3730
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003731 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003732 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003733 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003734 for (int userId : userIds) {
3735 UserAccounts userAccounts = getUserAccounts(userId);
3736 if (userAccounts == null) continue;
3737 synchronized (userAccounts.cacheLock) {
3738 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3739 Binder.getCallingUid(), null);
3740 for (int a = 0; a < accounts.length; a++) {
3741 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003742 }
3743 }
3744 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003745
3746 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3747 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003748 }
3749
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003750 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003751 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003752 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3753 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003754 }
3755
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003756 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003757 private Account[] getAccountsAsUser(
3758 String type,
3759 int userId,
3760 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003761 int packageUid,
3762 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003763 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003764 // Only allow the system process to read accounts of other users
3765 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003766 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003767 && mContext.checkCallingOrSelfPermission(
3768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3769 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003770 throw new SecurityException("User " + UserHandle.getCallingUserId()
3771 + " trying to get account for " + userId);
3772 }
3773
Fred Quintana56285a62010-12-02 14:20:51 -08003774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3775 Log.v(TAG, "getAccounts: accountType " + type
3776 + ", caller's uid " + Binder.getCallingUid()
3777 + ", pid " + Binder.getCallingPid());
3778 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003779 // If the original calling app was using the framework account chooser activity, we'll
3780 // be passed in the original caller's uid here, which is what should be used for filtering.
3781 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3782 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003783 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003784 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003785
Svetoslavf3f02ac2015-09-08 14:36:35 -07003786 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3787 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003788 if (visibleAccountTypes.isEmpty()
3789 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003790 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003791 } else if (visibleAccountTypes.contains(type)) {
3792 // Prune the list down to just the requested type.
3793 visibleAccountTypes = new ArrayList<>();
3794 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003795 } // else aggregate all the visible accounts (it won't matter if the
3796 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003797
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003798 long identityToken = clearCallingIdentity();
3799 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003800 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003801 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003802 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003803 callingUid,
3804 callingPackage,
3805 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003806 } finally {
3807 restoreCallingIdentity(identityToken);
3808 }
3809 }
3810
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003811 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003812 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003813 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003814 int callingUid,
3815 String callingPackage,
3816 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003817 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003818 ArrayList<Account> visibleAccounts = new ArrayList<>();
3819 for (String visibleType : visibleAccountTypes) {
3820 Account[] accountsForType = getAccountsFromCacheLocked(
3821 userAccounts, visibleType, callingUid, callingPackage);
3822 if (accountsForType != null) {
3823 visibleAccounts.addAll(Arrays.asList(accountsForType));
3824 }
3825 }
3826 Account[] result = new Account[visibleAccounts.size()];
3827 for (int i = 0; i < visibleAccounts.size(); i++) {
3828 result[i] = visibleAccounts.get(i);
3829 }
3830 return result;
3831 }
3832 }
3833
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003834 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003835 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07003836 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003837 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3838 for (Account account : accounts) {
3839 addSharedAccountAsUser(account, userId);
3840 }
3841 }
3842
3843 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003844 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003845 UserAccounts accounts = getUserAccounts(userId);
3846 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003847 ContentValues values = new ContentValues();
3848 values.put(ACCOUNTS_NAME, account.name);
3849 values.put(ACCOUNTS_TYPE, account.type);
3850 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3851 new String[] {account.name, account.type});
3852 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3853 if (accountId < 0) {
3854 Log.w(TAG, "insertAccountIntoDatabase: " + account
3855 + ", skipping the DB insert failed");
3856 return false;
3857 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003858 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003859 return true;
3860 }
3861
3862 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003863 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3864 userId = handleIncomingUser(userId);
3865 UserAccounts accounts = getUserAccounts(userId);
3866 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003867 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003868 final ContentValues values = new ContentValues();
3869 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003870 int r = db.update(
3871 TABLE_SHARED_ACCOUNTS,
3872 values,
3873 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3874 new String[] { account.name, account.type });
3875 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003876 int callingUid = getCallingUid();
3877 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3878 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003879 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003880 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003881 }
3882 return r > 0;
3883 }
3884
3885 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003886 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003887 return removeSharedAccountAsUser(account, userId, getCallingUid());
3888 }
3889
3890 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003891 userId = handleIncomingUser(userId);
3892 UserAccounts accounts = getUserAccounts(userId);
3893 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003894 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003895 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3896 new String[] {account.name, account.type});
3897 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003898 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3899 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003900 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003901 }
3902 return r > 0;
3903 }
3904
3905 @Override
3906 public Account[] getSharedAccountsAsUser(int userId) {
3907 userId = handleIncomingUser(userId);
3908 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003909 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003910 Cursor cursor = null;
3911 try {
3912 cursor = accounts.openHelper.getReadableDatabase()
3913 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3914 null, null, null, null, null);
3915 if (cursor != null && cursor.moveToFirst()) {
3916 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3917 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3918 do {
3919 accountList.add(new Account(cursor.getString(nameIndex),
3920 cursor.getString(typeIndex)));
3921 } while (cursor.moveToNext());
3922 }
3923 } finally {
3924 if (cursor != null) {
3925 cursor.close();
3926 }
3927 }
3928 Account[] accountArray = new Account[accountList.size()];
3929 accountList.toArray(accountArray);
3930 return accountArray;
3931 }
3932
3933 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003934 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003935 public Account[] getAccounts(String type, String opPackageName) {
3936 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003937 }
3938
Amith Yamasani27db4682013-03-30 17:07:47 -07003939 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003940 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003941 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003942 int callingUid = Binder.getCallingUid();
3943 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3944 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3945 + callingUid + " with uid=" + uid);
3946 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003947 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3948 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003949 }
3950
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003951 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003952 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003953 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3954 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003955 int packageUid = -1;
3956 try {
3957 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003958 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3959 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003960 } catch (RemoteException re) {
3961 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3962 return new Account[0];
3963 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003964 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3965 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003966 }
3967
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003968 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003969 public void getAccountsByFeatures(
3970 IAccountManagerResponse response,
3971 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003972 String[] features,
3973 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003974 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003975 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3976 Log.v(TAG, "getAccounts: accountType " + type
3977 + ", response " + response
3978 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003979 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003980 + ", pid " + Binder.getCallingPid());
3981 }
Fred Quintana382601f2010-03-25 12:25:10 -07003982 if (response == null) throw new IllegalArgumentException("response is null");
3983 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003984 int userId = UserHandle.getCallingUserId();
3985
Svetoslavf3f02ac2015-09-08 14:36:35 -07003986 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3987 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003988 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003989 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003990 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003991 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3992 try {
3993 response.onResult(result);
3994 } catch (RemoteException e) {
3995 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3996 }
3997 return;
3998 }
Fred Quintana33269202009-04-20 16:05:10 -07003999 long identityToken = clearCallingIdentity();
4000 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004001 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004002 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004003 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004004 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004005 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004006 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004007 Bundle result = new Bundle();
4008 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4009 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004010 return;
4011 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004012 new GetAccountsByTypeAndFeatureSession(
4013 userAccounts,
4014 response,
4015 type,
4016 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004017 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004018 } finally {
4019 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004020 }
4021 }
4022
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004023 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
4024 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
4025 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
4026 try {
4027 if (cursor.moveToNext()) {
4028 return cursor.getLong(0);
4029 }
4030 return -1;
4031 } finally {
4032 cursor.close();
4033 }
4034 }
4035
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004036 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07004037 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004038 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07004039 try {
4040 if (cursor.moveToNext()) {
4041 return cursor.getLong(0);
4042 }
4043 return -1;
4044 } finally {
4045 cursor.close();
4046 }
4047 }
4048
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004049 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004050 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07004051 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
4052 new String[]{key}, null, null, null);
4053 try {
4054 if (cursor.moveToNext()) {
4055 return cursor.getLong(0);
4056 }
4057 return -1;
4058 } finally {
4059 cursor.close();
4060 }
4061 }
4062
Fred Quintanaa698f422009-04-08 19:14:54 -07004063 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004064 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004065 IAccountManagerResponse mResponse;
4066 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004067 final boolean mExpectActivityLaunch;
4068 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004069 final String mAccountName;
4070 // Indicates if we need to add auth details(like last credential time)
4071 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004072 // If set, we need to update the last authenticated time. This is
4073 // currently
4074 // used on
4075 // successful confirming credentials.
4076 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004077
Fred Quintana33269202009-04-20 16:05:10 -07004078 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004079 private int mNumRequestContinued = 0;
4080 private int mNumErrors = 0;
4081
Fred Quintana60307342009-03-24 22:48:12 -07004082 IAccountAuthenticator mAuthenticator = null;
4083
Fred Quintana8570f742010-02-18 10:32:54 -08004084 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004085 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004086
Amith Yamasani04e0d262012-02-14 11:50:53 -08004087 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004088 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4089 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004090 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4091 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4092 }
4093
4094 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4095 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4096 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004097 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004098 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004099 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004100 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004101 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004102 mResponse = response;
4103 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004104 mExpectActivityLaunch = expectActivityLaunch;
4105 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004106 mAccountName = accountName;
4107 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004108 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004109
Fred Quintanaa698f422009-04-08 19:14:54 -07004110 synchronized (mSessions) {
4111 mSessions.put(toString(), this);
4112 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004113 if (response != null) {
4114 try {
4115 response.asBinder().linkToDeath(this, 0 /* flags */);
4116 } catch (RemoteException e) {
4117 mResponse = null;
4118 binderDied();
4119 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004120 }
Fred Quintana60307342009-03-24 22:48:12 -07004121 }
4122
Fred Quintanaa698f422009-04-08 19:14:54 -07004123 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004124 if (mResponse == null) {
4125 // this session has already been closed
4126 return null;
4127 }
Fred Quintana60307342009-03-24 22:48:12 -07004128 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004129 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004130 return response;
4131 }
4132
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004133 /**
4134 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4135 * security policy.
4136 *
4137 * In particular we want to make sure that the Authenticator doesn't try to trick users
4138 * into launching aribtrary intents on the device via by tricking to click authenticator
4139 * supplied entries in the system Settings app.
4140 */
4141 protected void checkKeyIntent(
4142 int authUid,
4143 Intent intent) throws SecurityException {
4144 long bid = Binder.clearCallingIdentity();
4145 try {
4146 PackageManager pm = mContext.getPackageManager();
4147 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4148 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4149 int targetUid = targetActivityInfo.applicationInfo.uid;
4150 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
4151 String pkgName = targetActivityInfo.packageName;
4152 String activityName = targetActivityInfo.name;
4153 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4154 + "does not share a signature with the supplying authenticator (%s).";
4155 throw new SecurityException(
4156 String.format(tmpl, activityName, pkgName, mAccountType));
4157 }
4158 } finally {
4159 Binder.restoreCallingIdentity(bid);
4160 }
4161 }
4162
Fred Quintanaa698f422009-04-08 19:14:54 -07004163 private void close() {
4164 synchronized (mSessions) {
4165 if (mSessions.remove(toString()) == null) {
4166 // the session was already closed, so bail out now
4167 return;
4168 }
4169 }
4170 if (mResponse != null) {
4171 // stop listening for response deaths
4172 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4173
4174 // clear this so that we don't accidentally send any further results
4175 mResponse = null;
4176 }
4177 cancelTimeout();
4178 unbind();
4179 }
4180
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004181 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004182 public void binderDied() {
4183 mResponse = null;
4184 close();
4185 }
4186
4187 protected String toDebugString() {
4188 return toDebugString(SystemClock.elapsedRealtime());
4189 }
4190
4191 protected String toDebugString(long now) {
4192 return "Session: expectLaunch " + mExpectActivityLaunch
4193 + ", connected " + (mAuthenticator != null)
4194 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4195 + "/" + mNumErrors + ")"
4196 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4197 }
4198
Fred Quintana60307342009-03-24 22:48:12 -07004199 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004200 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4201 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4202 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004203 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004204 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004205 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004206 }
4207 }
4208
4209 private void unbind() {
4210 if (mAuthenticator != null) {
4211 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004212 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004213 }
4214 }
4215
Fred Quintana60307342009-03-24 22:48:12 -07004216 public void cancelTimeout() {
4217 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
4218 }
4219
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004220 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004221 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004222 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004223 try {
4224 run();
4225 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004226 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004227 "remote exception");
4228 }
Fred Quintana60307342009-03-24 22:48:12 -07004229 }
4230
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004231 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004232 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004233 mAuthenticator = null;
4234 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004235 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004236 try {
4237 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4238 "disconnected");
4239 } catch (RemoteException e) {
4240 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4241 Log.v(TAG, "Session.onServiceDisconnected: "
4242 + "caught RemoteException while responding", e);
4243 }
4244 }
Fred Quintana60307342009-03-24 22:48:12 -07004245 }
4246 }
4247
Fred Quintanab839afc2009-10-14 15:57:28 -07004248 public abstract void run() throws RemoteException;
4249
Fred Quintana60307342009-03-24 22:48:12 -07004250 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004251 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004252 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004253 try {
4254 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4255 "timeout");
4256 } catch (RemoteException e) {
4257 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4258 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4259 e);
4260 }
4261 }
Fred Quintana60307342009-03-24 22:48:12 -07004262 }
4263 }
4264
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004265 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004266 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004267 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004268 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004269 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004270 if (result != null) {
4271 boolean isSuccessfulConfirmCreds = result.getBoolean(
4272 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004273 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004274 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4275 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004276 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004277 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4278 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004279 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004280 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004281 if (needUpdate || mAuthDetailsRequired) {
4282 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4283 if (needUpdate && accountPresent) {
4284 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4285 }
4286 if (mAuthDetailsRequired) {
4287 long lastAuthenticatedTime = -1;
4288 if (accountPresent) {
4289 lastAuthenticatedTime = DatabaseUtils.longForQuery(
4290 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004291 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4292 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004293 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
4294 + ACCOUNTS_TYPE + "=?",
4295 new String[] {
4296 mAccountName, mAccountType
4297 });
4298 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004299 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004300 lastAuthenticatedTime);
4301 }
4302 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004303 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004304 if (result != null
4305 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004306 checkKeyIntent(
4307 Binder.getCallingUid(),
4308 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004309 }
4310 if (result != null
4311 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004312 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4313 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004314 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4315 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004316 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4317 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004318 }
Fred Quintana60307342009-03-24 22:48:12 -07004319 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004320 IAccountManagerResponse response;
4321 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004322 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004323 response = mResponse;
4324 } else {
4325 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004326 }
Fred Quintana60307342009-03-24 22:48:12 -07004327 if (response != null) {
4328 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004329 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004330 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4331 Log.v(TAG, getClass().getSimpleName()
4332 + " calling onError() on response " + response);
4333 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004334 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004335 "null bundle returned");
4336 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004337 if (mStripAuthTokenFromResult) {
4338 result.remove(AccountManager.KEY_AUTHTOKEN);
4339 }
Fred Quintana56285a62010-12-02 14:20:51 -08004340 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4341 Log.v(TAG, getClass().getSimpleName()
4342 + " calling onResult() on response " + response);
4343 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004344 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4345 (intent == null)) {
4346 // All AccountManager error codes are greater than 0
4347 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4348 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4349 } else {
4350 response.onResult(result);
4351 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004352 }
Fred Quintana60307342009-03-24 22:48:12 -07004353 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004354 // if the caller is dead then there is no one to care about remote exceptions
4355 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4356 Log.v(TAG, "failure while notifying response", e);
4357 }
Fred Quintana60307342009-03-24 22:48:12 -07004358 }
4359 }
4360 }
Fred Quintana60307342009-03-24 22:48:12 -07004361
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004362 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004363 public void onRequestContinued() {
4364 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004365 }
4366
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004367 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004368 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004369 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004370 IAccountManagerResponse response = getResponseAndClose();
4371 if (response != null) {
4372 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004373 Log.v(TAG, getClass().getSimpleName()
4374 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004375 }
4376 try {
4377 response.onError(errorCode, errorMessage);
4378 } catch (RemoteException e) {
4379 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4380 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4381 }
4382 }
4383 } else {
4384 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4385 Log.v(TAG, "Session.onError: already closed");
4386 }
Fred Quintana60307342009-03-24 22:48:12 -07004387 }
4388 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004389
4390 /**
4391 * find the component name for the authenticator and initiate a bind
4392 * if no authenticator or the bind fails then return false, otherwise return true
4393 */
4394 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004395 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4396 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4397 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004398 if (authenticatorInfo == null) {
4399 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4400 Log.v(TAG, "there is no authenticator for " + authenticatorType
4401 + ", bailing out");
4402 }
4403 return false;
4404 }
4405
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004406 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004407 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004408 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4409 + " which isn't encryption aware");
4410 return false;
4411 }
4412
Fred Quintanab839afc2009-10-14 15:57:28 -07004413 Intent intent = new Intent();
4414 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4415 intent.setComponent(authenticatorInfo.componentName);
4416 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4417 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4418 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004419 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004420 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004421 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4422 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4423 }
4424 return false;
4425 }
4426
Fred Quintanab839afc2009-10-14 15:57:28 -07004427 return true;
4428 }
Fred Quintana60307342009-03-24 22:48:12 -07004429 }
4430
4431 private class MessageHandler extends Handler {
4432 MessageHandler(Looper looper) {
4433 super(looper);
4434 }
Costin Manolache3348f142009-09-29 18:58:36 -07004435
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004436 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004437 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004438 switch (msg.what) {
4439 case MESSAGE_TIMED_OUT:
4440 Session session = (Session)msg.obj;
4441 session.onTimedOut();
4442 break;
4443
Amith Yamasani5be347b2013-03-31 17:44:31 -07004444 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004445 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004446 break;
4447
Fred Quintana60307342009-03-24 22:48:12 -07004448 default:
4449 throw new IllegalStateException("unhandled message: " + msg.what);
4450 }
4451 }
4452 }
4453
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004454 @VisibleForTesting
4455 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004456 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004457 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4458 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004459 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004460 // Migrate old file, if it exists, to the new location.
4461 // Make sure the new file doesn't already exist. A dummy file could have been
4462 // accidentally created in the old location, causing the new one to become corrupted
4463 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004464 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004465 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004466 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004467 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004468 if (!userDir.exists()) {
4469 if (!userDir.mkdirs()) {
4470 throw new IllegalStateException("User dir cannot be created: " + userDir);
4471 }
4472 }
4473 if (!oldFile.renameTo(databaseFile)) {
4474 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4475 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004476 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004477 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004478 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004479 }
4480
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004481 @VisibleForTesting
4482 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004483 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4484 DE_DATABASE_NAME);
4485 return databaseFile.getPath();
4486 }
4487
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004488 @VisibleForTesting
4489 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004490 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4491 CE_DATABASE_NAME);
4492 return databaseFile.getPath();
4493 }
4494
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004495 private static class DebugDbHelper{
4496 private DebugDbHelper() {
4497 }
4498
4499 private static String TABLE_DEBUG = "debug_table";
4500
4501 // Columns for the table
4502 private static String ACTION_TYPE = "action_type";
4503 private static String TIMESTAMP = "time";
4504 private static String CALLER_UID = "caller_uid";
4505 private static String TABLE_NAME = "table_name";
4506 private static String KEY = "primary_key";
4507
4508 // These actions correspond to the occurrence of real actions. Since
4509 // these are called by the authenticators, the uid associated will be
4510 // of the authenticator.
4511 private static String ACTION_SET_PASSWORD = "action_set_password";
4512 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4513 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4514 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004515 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004516 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4517 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4518
4519 // These actions don't necessarily correspond to any action on
4520 // accountDb taking place. As an example, there might be a request for
4521 // addingAccount, which might not lead to addition of account on grounds
4522 // of bad authentication. We will still be logging it to keep track of
4523 // who called.
4524 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4525 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004526 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004527
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004528 //This action doesn't add account to accountdb. Account is only
4529 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004530 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004531 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4532 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004533
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004534 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4535
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004536 private static void createDebugTable(SQLiteDatabase db) {
4537 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4538 + ACCOUNTS_ID + " INTEGER,"
4539 + ACTION_TYPE + " TEXT NOT NULL, "
4540 + TIMESTAMP + " DATETIME,"
4541 + CALLER_UID + " INTEGER NOT NULL,"
4542 + TABLE_NAME + " TEXT NOT NULL,"
4543 + KEY + " INTEGER PRIMARY KEY)");
4544 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4545 }
4546 }
4547
4548 private void logRecord(UserAccounts accounts, String action, String tableName) {
4549 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4550 logRecord(db, action, tableName, -1, accounts);
4551 }
4552
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004553 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4554 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4555 logRecord(db, action, tableName, -1, accounts, uid);
4556 }
4557
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004558 /*
4559 * This function receives an opened writable database.
4560 */
4561 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4562 UserAccounts userAccount) {
4563 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4564 }
4565
4566 /*
4567 * This function receives an opened writable database.
4568 */
4569 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4570 UserAccounts userAccount, int callingUid) {
4571 SQLiteStatement logStatement = userAccount.statementForLogging;
4572 logStatement.bindLong(1, accountId);
4573 logStatement.bindString(2, action);
4574 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4575 logStatement.bindLong(4, callingUid);
4576 logStatement.bindString(5, tableName);
4577 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4578 logStatement.execute();
4579 logStatement.clearBindings();
4580 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4581 % MAX_DEBUG_DB_SIZE;
4582 }
4583
4584 /*
4585 * This should only be called once to compile the sql statement for logging
4586 * and to find the insertion point.
4587 */
4588 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4589 UserAccounts userAccount) {
4590 // Initialize the count if not done earlier.
4591 int size = (int) getDebugTableRowCount(db);
4592 if (size >= MAX_DEBUG_DB_SIZE) {
4593 // Table is full, and we need to find the point where to insert.
4594 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4595 } else {
4596 userAccount.debugDbInsertionPoint = size;
4597 }
4598 compileSqlStatementForLogging(db, userAccount);
4599 }
4600
4601 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4602 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4603 + " VALUES (?,?,?,?,?,?)";
4604 userAccount.statementForLogging = db.compileStatement(sql);
4605 }
4606
4607 private long getDebugTableRowCount(SQLiteDatabase db) {
4608 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4609 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4610 }
4611
4612 /*
4613 * Finds the row key where the next insertion should take place. This should
4614 * be invoked only if the table has reached its full capacity.
4615 */
4616 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4617 // This query finds the smallest timestamp value (and if 2 records have
4618 // same timestamp, the choose the lower id).
4619 String queryCountDebugDbRows = new StringBuilder()
4620 .append("SELECT ").append(DebugDbHelper.KEY)
4621 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4622 .append(" ORDER BY ")
4623 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4624 .append(" LIMIT 1")
4625 .toString();
4626 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4627 }
4628
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004629 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004630 private final Context mContext;
4631 private final int mUserId;
4632
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004633 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4634 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004635 mContext = context;
4636 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004637 }
4638
4639 @Override
4640 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004641 // We use PreNDatabaseHelper only if pre-N db exists
4642 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004643 }
4644
Amith Yamasani67df64b2012-12-14 12:09:36 -08004645 private void createSharedAccountsTable(SQLiteDatabase db) {
4646 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4647 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4648 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4649 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4650 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4651 }
4652
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004653 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4654 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4655 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4656 }
4657
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004658 private void addOldAccountNameColumn(SQLiteDatabase db) {
4659 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4660 }
4661
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004662 private void addDebugTable(SQLiteDatabase db) {
4663 DebugDbHelper.createDebugTable(db);
4664 }
4665
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004666 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004667 db.execSQL(""
4668 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4669 + " BEGIN"
4670 + " DELETE FROM " + TABLE_AUTHTOKENS
4671 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4672 + " DELETE FROM " + TABLE_EXTRAS
4673 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004674 + " DELETE FROM " + TABLE_GRANTS
4675 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004676 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004677 }
4678
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004679 private void createGrantsTable(SQLiteDatabase db) {
4680 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4681 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4682 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4683 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4684 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4685 + "," + GRANTS_GRANTEE_UID + "))");
4686 }
4687
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004688 private void populateMetaTableWithAuthTypeAndUID(
4689 SQLiteDatabase db,
4690 Map<String, Integer> authTypeAndUIDMap) {
4691 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4692 while (iterator.hasNext()) {
4693 Entry<String, Integer> entry = iterator.next();
4694 ContentValues values = new ContentValues();
4695 values.put(META_KEY,
4696 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4697 values.put(META_VALUE, entry.getValue());
4698 db.insert(TABLE_META, null, values);
4699 }
4700 }
4701
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004702 /**
4703 * Pre-N database may need an upgrade before splitting
4704 */
Fred Quintana60307342009-03-24 22:48:12 -07004705 @Override
4706 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004707 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004708
Fred Quintanaa698f422009-04-08 19:14:54 -07004709 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004710 // no longer need to do anything since the work is done
4711 // when upgrading from version 2
4712 oldVersion++;
4713 }
4714
4715 if (oldVersion == 2) {
4716 createGrantsTable(db);
4717 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4718 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004719 oldVersion++;
4720 }
Costin Manolache3348f142009-09-29 18:58:36 -07004721
4722 if (oldVersion == 3) {
4723 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4724 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4725 oldVersion++;
4726 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004727
4728 if (oldVersion == 4) {
4729 createSharedAccountsTable(db);
4730 oldVersion++;
4731 }
4732
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004733 if (oldVersion == 5) {
4734 addOldAccountNameColumn(db);
4735 oldVersion++;
4736 }
4737
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004738 if (oldVersion == 6) {
4739 addLastSuccessfullAuthenticatedTimeColumn(db);
4740 oldVersion++;
4741 }
4742
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004743 if (oldVersion == 7) {
4744 addDebugTable(db);
4745 oldVersion++;
4746 }
4747
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004748 if (oldVersion == 8) {
4749 populateMetaTableWithAuthTypeAndUID(
4750 db,
4751 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4752 oldVersion++;
4753 }
4754
Amith Yamasani67df64b2012-12-14 12:09:36 -08004755 if (oldVersion != newVersion) {
4756 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4757 }
Fred Quintana60307342009-03-24 22:48:12 -07004758 }
4759
4760 @Override
4761 public void onOpen(SQLiteDatabase db) {
4762 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4763 }
4764 }
4765
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004766 static class DeDatabaseHelper extends SQLiteOpenHelper {
4767
4768 private final int mUserId;
4769 private volatile boolean mCeAttached;
4770
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004771 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4772 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004773 mUserId = userId;
4774 }
4775
4776 /**
4777 * This call needs to be made while the mCacheLock is held. The way to
4778 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4779 * @param db The database.
4780 */
4781 @Override
4782 public void onCreate(SQLiteDatabase db) {
4783 Log.i(TAG, "Creating DE database for user " + mUserId);
4784 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4785 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4786 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4787 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4788 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4789 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4790 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4791
4792 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4793 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4794 + META_VALUE + " TEXT)");
4795
4796 createGrantsTable(db);
4797 createSharedAccountsTable(db);
4798 createAccountsDeletionTrigger(db);
4799 DebugDbHelper.createDebugTable(db);
4800 }
4801
4802 private void createSharedAccountsTable(SQLiteDatabase db) {
4803 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4804 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4805 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4806 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4807 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4808 }
4809
4810 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4811 db.execSQL(""
4812 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4813 + " BEGIN"
4814 + " DELETE FROM " + TABLE_GRANTS
4815 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4816 + " END");
4817 }
4818
4819 private void createGrantsTable(SQLiteDatabase db) {
4820 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4821 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4822 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4823 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4824 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4825 + "," + GRANTS_GRANTEE_UID + "))");
4826 }
4827
4828 @Override
4829 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4830 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4831
4832 if (oldVersion != newVersion) {
4833 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4834 }
4835 }
4836
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004837 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004838 SQLiteDatabase db = getWritableDatabase();
4839 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4840 mCeAttached = true;
4841 }
4842
4843 public boolean isCeDatabaseAttached() {
4844 return mCeAttached;
4845 }
4846
4847
4848 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4849 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004850 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
4851 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004852 }
4853 return super.getReadableDatabase();
4854 }
4855
4856 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4857 if(!mCeAttached) {
4858 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004859 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004860 }
4861 return super.getWritableDatabase();
4862 }
4863
4864 @Override
4865 public void onOpen(SQLiteDatabase db) {
4866 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4867 }
4868
4869 private void migratePreNDbToDe(File preNDbFile) {
4870 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4871 SQLiteDatabase db = getWritableDatabase();
4872 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4873 db.beginTransaction();
4874 // Copy accounts fields
4875 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4876 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4877 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4878 + ") "
4879 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4880 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4881 + " FROM preNDb." + TABLE_ACCOUNTS);
4882 // Copy SHARED_ACCOUNTS
4883 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4884 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4885 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4886 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4887 // Copy DEBUG_TABLE
4888 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4889 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4890 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4891 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4892 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4893 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4894 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4895 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4896 // Copy GRANTS
4897 db.execSQL("INSERT INTO " + TABLE_GRANTS
4898 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4899 + GRANTS_GRANTEE_UID + ") " +
4900 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4901 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4902 // Copy META
4903 db.execSQL("INSERT INTO " + TABLE_META
4904 + "(" + META_KEY + "," + META_VALUE + ") "
4905 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4906 db.setTransactionSuccessful();
4907 db.endTransaction();
4908
4909 db.execSQL("DETACH DATABASE preNDb");
4910 }
4911
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004912 static DeDatabaseHelper create(
4913 Context context,
4914 int userId,
4915 File preNDatabaseFile,
4916 File deDatabaseFile) {
4917 boolean newDbExists = deDatabaseFile.exists();
4918 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
4919 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004920 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004921 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004922 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004923 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
4924 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004925 // Open the database to force upgrade if required
4926 preNDatabaseHelper.getWritableDatabase();
4927 preNDatabaseHelper.close();
4928 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004929 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004930 }
4931 return deDatabaseHelper;
4932 }
4933 }
4934
4935 static class CeDatabaseHelper extends SQLiteOpenHelper {
4936
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004937 public CeDatabaseHelper(Context context, String ceDatabaseName) {
4938 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004939 }
4940
4941 /**
4942 * This call needs to be made while the mCacheLock is held.
4943 * @param db The database.
4944 */
4945 @Override
4946 public void onCreate(SQLiteDatabase db) {
4947 Log.i(TAG, "Creating CE database " + getDatabaseName());
4948 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4949 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4950 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4951 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4952 + ACCOUNTS_PASSWORD + " TEXT, "
4953 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4954
4955 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4956 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4957 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4958 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4959 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4960 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4961
4962 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4963 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4964 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4965 + EXTRAS_KEY + " TEXT NOT NULL, "
4966 + EXTRAS_VALUE + " TEXT, "
4967 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4968
4969 createAccountsDeletionTrigger(db);
4970 }
4971
4972 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4973 db.execSQL(""
4974 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4975 + " BEGIN"
4976 + " DELETE FROM " + TABLE_AUTHTOKENS
4977 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4978 + " DELETE FROM " + TABLE_EXTRAS
4979 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4980 + " END");
4981 }
4982
4983 @Override
4984 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4985 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4986
4987 if (oldVersion == 9) {
4988 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4989 Log.v(TAG, "onUpgrade upgrading to v10");
4990 }
4991 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4992 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4993 // Recreate the trigger, since the old one references the table to be removed
4994 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4995 createAccountsDeletionTrigger(db);
4996 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4997 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4998 oldVersion ++;
4999 }
5000
5001 if (oldVersion != newVersion) {
5002 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
5003 }
5004 }
5005
5006 @Override
5007 public void onOpen(SQLiteDatabase db) {
5008 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
5009 }
5010
5011 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
5012 String type) {
5013 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
5014 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
5015 new String[]{name, type}, null, null, null);
5016 try {
5017 if (cursor.moveToNext()) {
5018 return cursor.getString(0);
5019 }
5020 return null;
5021 } finally {
5022 cursor.close();
5023 }
5024 }
5025
Fyodor Kupolov35f68082016-04-06 12:14:17 -07005026 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
5027 // Select accounts from CE that do not exist in DE
5028 Cursor cursor = db.rawQuery(
5029 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
5030 + " FROM " + CE_TABLE_ACCOUNTS
5031 + " WHERE NOT EXISTS "
5032 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
5033 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
5034 + " )", null);
5035 try {
5036 List<Account> accounts = new ArrayList<>(cursor.getCount());
5037 while (cursor.moveToNext()) {
5038 String accountName = cursor.getString(0);
5039 String accountType = cursor.getString(1);
5040 accounts.add(new Account(accountName, accountType));
5041 }
5042 return accounts;
5043 } finally {
5044 cursor.close();
5045 }
5046 }
5047
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005048 /**
5049 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
5050 * it also performs migration to the new CE database.
5051 * @param context
5052 * @param userId id of the user where the database is located
5053 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005054 static CeDatabaseHelper create(
5055 Context context,
5056 int userId,
5057 File preNDatabaseFile,
5058 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005059 boolean newDbExists = ceDatabaseFile.exists();
5060 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5061 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005062 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005063 }
5064 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005065 if (!newDbExists && preNDatabaseFile.exists()) {
5066 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005067 }
5068 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005069 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005070 ceHelper.getWritableDatabase();
5071 ceHelper.close();
5072 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005073 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
5074 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
5075 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
5076 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005077 }
5078 return ceHelper;
5079 }
5080
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005081 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005082 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005083 try {
5084 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
5085 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005086 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005087 // Try to remove potentially damaged file if I/O error occurred
5088 deleteDbFileWarnIfFailed(ceDbFile);
5089 return false;
5090 }
5091 return true;
5092 }
5093 }
5094
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005095 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005096 return asBinder();
5097 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005098
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005099 /**
5100 * Searches array of arguments for the specified string
5101 * @param args array of argument strings
5102 * @param value value to search for
5103 * @return true if the value is contained in the array
5104 */
5105 private static boolean scanArgs(String[] args, String value) {
5106 if (args != null) {
5107 for (String arg : args) {
5108 if (value.equals(arg)) {
5109 return true;
5110 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005111 }
5112 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005113 return false;
5114 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005115
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005116 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005117 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07005118 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5119 != PackageManager.PERMISSION_GRANTED) {
5120 fout.println("Permission Denial: can't dump AccountsManager from from pid="
5121 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5122 + " without permission " + android.Manifest.permission.DUMP);
5123 return;
5124 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005125 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005126 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005127
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005128 final List<UserInfo> users = getUserManager().getUsers();
5129 for (UserInfo user : users) {
5130 ipw.println("User " + user + ":");
5131 ipw.increaseIndent();
5132 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5133 ipw.println();
5134 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005135 }
5136 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005137
Amith Yamasani04e0d262012-02-14 11:50:53 -08005138 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5139 String[] args, boolean isCheckinRequest) {
5140 synchronized (userAccounts.cacheLock) {
5141 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005142
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005143 if (isCheckinRequest) {
5144 // This is a checkin request. *Only* upload the account types and the count of each.
5145 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
5146 null, null, ACCOUNTS_TYPE, null, null);
5147 try {
5148 while (cursor.moveToNext()) {
5149 // print type,count
5150 fout.println(cursor.getString(0) + "," + cursor.getString(1));
5151 }
5152 } finally {
5153 if (cursor != null) {
5154 cursor.close();
5155 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005156 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005157 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005158 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07005159 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005160 fout.println("Accounts: " + accounts.length);
5161 for (Account account : accounts) {
5162 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005163 }
Fred Quintana307da1a2010-01-21 14:24:20 -08005164
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005165 // Add debug information.
5166 fout.println();
5167 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
5168 null, null, null, null, DebugDbHelper.TIMESTAMP);
5169 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
5170 fout.println("Accounts History");
5171 try {
5172 while (cursor.moveToNext()) {
5173 // print type,count
5174 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
5175 cursor.getString(2) + "," + cursor.getString(3) + ","
5176 + cursor.getString(4) + "," + cursor.getString(5));
5177 }
5178 } finally {
5179 cursor.close();
5180 }
5181
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005182 fout.println();
5183 synchronized (mSessions) {
5184 final long now = SystemClock.elapsedRealtime();
5185 fout.println("Active Sessions: " + mSessions.size());
5186 for (Session session : mSessions.values()) {
5187 fout.println(" " + session.toDebugString(now));
5188 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005189 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005190
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005191 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005192 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005193 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005194 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005195 }
5196
Amith Yamasani04e0d262012-02-14 11:50:53 -08005197 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005198 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005199 long identityToken = clearCallingIdentity();
5200 try {
5201 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5202 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5203 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005205 if (intent.getComponent() != null &&
5206 GrantCredentialsPermissionActivity.class.getName().equals(
5207 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005208 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005209 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005210 Context contextForUser = getContextForUser(new UserHandle(userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005211 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07005212 intent.addCategory(String.valueOf(notificationId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005213
Fred Quintana33f889a2009-09-14 17:31:26 -07005214 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005215 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005216 Notification n = new Notification.Builder(contextForUser)
5217 .setWhen(0)
5218 .setSmallIcon(android.R.drawable.stat_sys_warning)
5219 .setColor(contextForUser.getColor(
5220 com.android.internal.R.color.system_notification_accent_color))
5221 .setContentTitle(String.format(notificationTitleFormat, account.name))
5222 .setContentText(message)
5223 .setContentIntent(PendingIntent.getActivityAsUser(
5224 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005225 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005226 .build();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005227 installNotification(notificationId, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005228 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005229 } finally {
5230 restoreCallingIdentity(identityToken);
5231 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005232 }
5233
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005234 @VisibleForTesting
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005235 protected void installNotification(int notificationId, final Notification notification,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005236 UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005237 installNotification(notificationId, notification, "android", user.getIdentifier());
5238 }
5239
5240 private void installNotification(int notificationId, final Notification notification,
5241 String packageName, int userId) {
5242 final long token = clearCallingIdentity();
5243 try {
5244 INotificationManager notificationManager = NotificationManager.getService();
5245 try {
5246 notificationManager.enqueueNotificationWithTag(packageName, packageName, null,
5247 notificationId, notification, new int[1], userId);
5248 } catch (RemoteException e) {
5249 /* ignore - local call */
5250 }
5251 } finally {
5252 Binder.restoreCallingIdentity(token);
5253 }
Fred Quintana56285a62010-12-02 14:20:51 -08005254 }
5255
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005256 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005257 protected void cancelNotification(int id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005258 cancelNotification(id, mContext.getPackageName(), user);
5259 }
5260
5261 protected void cancelNotification(int id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005262 long identityToken = clearCallingIdentity();
5263 try {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005264 INotificationManager service = INotificationManager.Stub.asInterface(
5265 ServiceManager.getService(Context.NOTIFICATION_SERVICE));
5266 service.cancelNotificationWithTag(packageName, null, id, user.getIdentifier());
5267 } catch (RemoteException e) {
5268 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005269 } finally {
5270 restoreCallingIdentity(identityToken);
5271 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005272 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005273
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005274 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5275 for (String perm : permissions) {
5276 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5277 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5278 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5279 }
5280 final int opCode = AppOpsManager.permissionToOpCode(perm);
5281 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5282 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5283 return true;
5284 }
5285 }
5286 }
5287 return false;
5288 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005289
Amith Yamasani67df64b2012-12-14 12:09:36 -08005290 private int handleIncomingUser(int userId) {
5291 try {
5292 return ActivityManagerNative.getDefault().handleIncomingUser(
5293 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5294 } catch (RemoteException re) {
5295 // Shouldn't happen, local.
5296 }
5297 return userId;
5298 }
5299
Christopher Tateccbf84f2013-05-08 15:25:41 -07005300 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005301 final int callingUserId = UserHandle.getUserId(callingUid);
5302
5303 final PackageManager userPackageManager;
5304 try {
5305 userPackageManager = mContext.createPackageContextAsUser(
5306 "android", 0, new UserHandle(callingUserId)).getPackageManager();
5307 } catch (NameNotFoundException e) {
5308 return false;
5309 }
5310
5311 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005312 for (String name : packages) {
5313 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005314 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005315 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005316 && (packageInfo.applicationInfo.privateFlags
5317 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005318 return true;
5319 }
5320 } catch (PackageManager.NameNotFoundException e) {
5321 return false;
5322 }
5323 }
5324 return false;
5325 }
5326
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005327 private boolean permissionIsGranted(
5328 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005329 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5330 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5331 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5332 }
5333 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005334 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005335
5336 if (isPrivileged(callerUid)) {
5337 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5338 Log.v(TAG, "Access to " + account + " granted calling uid "
5339 + callerUid + " privileged");
5340 }
5341 return true;
5342 }
5343 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5344 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5345 Log.v(TAG, "Access to " + account + " granted calling uid "
5346 + callerUid + " manages the account");
5347 }
5348 return true;
5349 }
5350 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5351 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5352 Log.v(TAG, "Access to " + account + " granted calling uid "
5353 + callerUid + " user granted access");
5354 }
5355 return true;
5356 }
5357
5358 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5359 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5360 }
5361
5362 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005363 }
5364
Svetoslavf3f02ac2015-09-08 14:36:35 -07005365 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5366 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005367 if (accountType == null) {
5368 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005369 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005370 return getTypesVisibleToCaller(callingUid, userId,
5371 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005372 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005373 }
5374
5375 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5376 if (accountType == null) {
5377 return false;
5378 } else {
5379 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5380 }
5381 }
5382
Svetoslavf3f02ac2015-09-08 14:36:35 -07005383 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5384 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005385 boolean isPermitted =
5386 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5387 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005388 return getTypesForCaller(callingUid, userId, isPermitted);
5389 }
5390
5391 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5392 return getTypesForCaller(callingUid, userId, false);
5393 }
5394
5395 private List<String> getTypesForCaller(
5396 int callingUid, int userId, boolean isOtherwisePermitted) {
5397 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005398 long identityToken = Binder.clearCallingIdentity();
5399 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5400 try {
5401 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5402 } finally {
5403 Binder.restoreCallingIdentity(identityToken);
5404 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005405 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005406 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005407 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5408 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5409 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005410 }
5411 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005412 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005413 }
5414
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005415 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5416 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5417 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5418 if (account.name.equals(accountName)) {
5419 return true;
5420 }
5421 }
5422 }
5423 return false;
5424 }
5425
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005426 private static void checkManageUsersPermission(String message) {
5427 if (ActivityManager.checkComponentPermission(
5428 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5429 != PackageManager.PERMISSION_GRANTED) {
5430 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5431 }
5432 }
5433
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005434 private static void checkManageOrCreateUsersPermission(String message) {
5435 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5436 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5437 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5438 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5439 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5440 + message);
5441 }
5442 }
5443
Amith Yamasani04e0d262012-02-14 11:50:53 -08005444 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5445 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005446 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005447 return true;
5448 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005449 UserAccounts accounts = getUserAccountsForCaller();
5450 synchronized (accounts.cacheLock) {
5451 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005452
5453 final String query;
5454 final String[] args;
5455
5456 if (authTokenType != null) {
5457 query = COUNT_OF_MATCHING_GRANTS;
5458 args = new String[] {String.valueOf(callerUid), authTokenType,
5459 account.name, account.type};
5460 } else {
5461 query = COUNT_OF_MATCHING_GRANTS_ANY_TOKEN;
5462 args = new String[] {String.valueOf(callerUid), account.name,
5463 account.type};
5464 }
5465 final boolean permissionGranted = DatabaseUtils.longForQuery(db, query, args) != 0;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005466 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5467 // TODO: Skip this check when running automated tests. Replace this
5468 // with a more general solution.
5469 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005470 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005471 + " but ignoring since device is in test harness.");
5472 return true;
5473 }
5474 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005475 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005476 }
5477
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005478 private boolean isSystemUid(int callingUid) {
5479 String[] packages = null;
5480 long ident = Binder.clearCallingIdentity();
5481 try {
5482 packages = mPackageManager.getPackagesForUid(callingUid);
5483 } finally {
5484 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005485 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005486 if (packages != null) {
5487 for (String name : packages) {
5488 try {
5489 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5490 if (packageInfo != null
5491 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5492 != 0) {
5493 return true;
5494 }
5495 } catch (PackageManager.NameNotFoundException e) {
5496 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5497 }
5498 }
5499 } else {
5500 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005501 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005502 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005503 }
5504
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005505 /** Succeeds if any of the specified permissions are granted. */
5506 private void checkReadAccountsPermitted(
5507 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005508 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005509 int userId,
5510 String opPackageName) {
5511 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005512 String msg = String.format(
5513 "caller uid %s cannot access %s accounts",
5514 callingUid,
5515 accountType);
5516 Log.w(TAG, " " + msg);
5517 throw new SecurityException(msg);
5518 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005519 }
5520
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005521 private boolean canUserModifyAccounts(int userId, int callingUid) {
5522 // the managing app can always modify accounts
5523 if (isProfileOwner(callingUid)) {
5524 return true;
5525 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005526 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5527 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5528 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005529 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005530 return true;
5531 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005532
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005533 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5534 // the managing app can always modify accounts
5535 if (isProfileOwner(callingUid)) {
5536 return true;
5537 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005538 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5539 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005540 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005541 if (typesArray == null) {
5542 return true;
5543 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005544 for (String forbiddenType : typesArray) {
5545 if (forbiddenType.equals(accountType)) {
5546 return false;
5547 }
5548 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005549 return true;
5550 }
5551
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005552 private boolean isProfileOwner(int uid) {
5553 final DevicePolicyManagerInternal dpmi =
5554 LocalServices.getService(DevicePolicyManagerInternal.class);
5555 return (dpmi != null)
5556 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5557 }
5558
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005559 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005560 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5561 throws RemoteException {
5562 final int callingUid = getCallingUid();
5563
Amith Yamasani27db4682013-03-30 17:07:47 -07005564 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005565 throw new SecurityException();
5566 }
5567
5568 if (value) {
5569 grantAppPermission(account, authTokenType, uid);
5570 } else {
5571 revokeAppPermission(account, authTokenType, uid);
5572 }
5573 }
5574
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005575 /**
5576 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5577 * <p>
5578 * Although this is public it can only be accessed via the AccountManagerService object
5579 * which is in the system. This means we don't need to protect it with permissions.
5580 * @hide
5581 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005582 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005583 if (account == null || authTokenType == null) {
5584 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005585 return;
5586 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005587 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005588 synchronized (accounts.cacheLock) {
5589 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005590 db.beginTransaction();
5591 try {
5592 long accountId = getAccountIdLocked(db, account);
5593 if (accountId >= 0) {
5594 ContentValues values = new ContentValues();
5595 values.put(GRANTS_ACCOUNTS_ID, accountId);
5596 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5597 values.put(GRANTS_GRANTEE_UID, uid);
5598 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5599 db.setTransactionSuccessful();
5600 }
5601 } finally {
5602 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005603 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005604 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005605 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005606
5607 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005608 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005609 }
5610
5611 /**
5612 * Don't allow callers with the given uid permission to get credentials for
5613 * account/authTokenType.
5614 * <p>
5615 * Although this is public it can only be accessed via the AccountManagerService object
5616 * which is in the system. This means we don't need to protect it with permissions.
5617 * @hide
5618 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005619 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005620 if (account == null || authTokenType == null) {
5621 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005622 return;
5623 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005624 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005625 synchronized (accounts.cacheLock) {
5626 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005627 db.beginTransaction();
5628 try {
5629 long accountId = getAccountIdLocked(db, account);
5630 if (accountId >= 0) {
5631 db.delete(TABLE_GRANTS,
5632 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5633 + GRANTS_GRANTEE_UID + "=?",
5634 new String[]{String.valueOf(accountId), authTokenType,
5635 String.valueOf(uid)});
5636 db.setTransactionSuccessful();
5637 }
5638 } finally {
5639 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005640 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005641 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5642 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005643 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005644 }
Fred Quintana56285a62010-12-02 14:20:51 -08005645
5646 static final private String stringArrayToString(String[] value) {
5647 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5648 }
5649
Amith Yamasani04e0d262012-02-14 11:50:53 -08005650 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5651 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005652 if (oldAccountsForType != null) {
5653 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5654 for (Account curAccount : oldAccountsForType) {
5655 if (!curAccount.equals(account)) {
5656 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005657 }
5658 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005659 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005660 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005661 } else {
5662 Account[] newAccountsForType = new Account[newAccountsList.size()];
5663 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005664 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005665 }
Fred Quintana56285a62010-12-02 14:20:51 -08005666 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005667 accounts.userDataCache.remove(account);
5668 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005669 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005670 }
5671
5672 /**
5673 * This assumes that the caller has already checked that the account is not already present.
5674 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005675 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5676 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005677 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5678 Account[] newAccountsForType = new Account[oldLength + 1];
5679 if (accountsForType != null) {
5680 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005681 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005682 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005683 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005684 }
5685
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005686 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005687 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005688 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005689 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005690 return unfiltered;
5691 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005692 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005693 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005694 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005695 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005696 // otherwise return non-shared accounts only.
5697 // This might be a temporary way to specify a whitelist
5698 String whiteList = mContext.getResources().getString(
5699 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5700 for (String packageName : packages) {
5701 if (whiteList.contains(";" + packageName + ";")) {
5702 return unfiltered;
5703 }
5704 }
5705 ArrayList<Account> allowed = new ArrayList<Account>();
5706 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5707 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005708 String requiredAccountType = "";
5709 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005710 // If there's an explicit callingPackage specified, check if that package
5711 // opted in to see restricted accounts.
5712 if (callingPackage != null) {
5713 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005714 if (pi != null && pi.restrictedAccountType != null) {
5715 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005716 }
5717 } else {
5718 // Otherwise check if the callingUid has a package that has opted in
5719 for (String packageName : packages) {
5720 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5721 if (pi != null && pi.restrictedAccountType != null) {
5722 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005723 break;
5724 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005725 }
5726 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005727 } catch (NameNotFoundException nnfe) {
5728 }
5729 for (Account account : unfiltered) {
5730 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005731 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005732 } else {
5733 boolean found = false;
5734 for (Account shared : sharedAccounts) {
5735 if (shared.equals(account)) {
5736 found = true;
5737 break;
5738 }
5739 }
5740 if (!found) {
5741 allowed.add(account);
5742 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005743 }
5744 }
5745 Account[] filtered = new Account[allowed.size()];
5746 allowed.toArray(filtered);
5747 return filtered;
5748 } else {
5749 return unfiltered;
5750 }
5751 }
5752
Amith Yamasani27db4682013-03-30 17:07:47 -07005753 /*
5754 * packageName can be null. If not null, it should be used to filter out restricted accounts
5755 * that the package is not allowed to access.
5756 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005757 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005758 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005759 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005760 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005761 if (accounts == null) {
5762 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005763 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005764 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005765 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005766 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005767 } else {
5768 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005769 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005770 totalLength += accounts.length;
5771 }
5772 if (totalLength == 0) {
5773 return EMPTY_ACCOUNT_ARRAY;
5774 }
5775 Account[] accounts = new Account[totalLength];
5776 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005777 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005778 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5779 accountsOfType.length);
5780 totalLength += accountsOfType.length;
5781 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005782 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005783 }
5784 }
5785
Amith Yamasani04e0d262012-02-14 11:50:53 -08005786 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5787 Account account, String key, String value) {
5788 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005789 if (userDataForAccount == null) {
5790 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005791 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005792 }
5793 if (value == null) {
5794 userDataForAccount.remove(key);
5795 } else {
5796 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005797 }
5798 }
5799
Carlos Valdivia91979be2015-05-22 14:11:35 -07005800 protected String readCachedTokenInternal(
5801 UserAccounts accounts,
5802 Account account,
5803 String tokenType,
5804 String callingPackage,
5805 byte[] pkgSigDigest) {
5806 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005807 return accounts.accountTokenCaches.get(
5808 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005809 }
5810 }
5811
Amith Yamasani04e0d262012-02-14 11:50:53 -08005812 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5813 Account account, String key, String value) {
5814 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005815 if (authTokensForAccount == null) {
5816 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005817 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005818 }
5819 if (value == null) {
5820 authTokensForAccount.remove(key);
5821 } else {
5822 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005823 }
5824 }
5825
Amith Yamasani04e0d262012-02-14 11:50:53 -08005826 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5827 String authTokenType) {
5828 synchronized (accounts.cacheLock) {
5829 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005830 if (authTokensForAccount == null) {
5831 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005832 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005833 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005834 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005835 }
5836 return authTokensForAccount.get(authTokenType);
5837 }
5838 }
5839
Simranjit Kohli858511c2016-03-10 18:36:11 +00005840 protected String readUserDataInternalLocked(
5841 UserAccounts accounts, Account account, String key) {
5842 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5843 if (userDataForAccount == null) {
5844 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005845 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli858511c2016-03-10 18:36:11 +00005846 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5847 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005848 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005849 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005850 }
5851
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005852 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5853 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005854 HashMap<String, String> userDataForAccount = new HashMap<>();
5855 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005856 COLUMNS_EXTRAS_KEY_AND_VALUE,
5857 SELECTION_USERDATA_BY_ACCOUNT,
5858 new String[]{account.name, account.type},
5859 null, null, null);
5860 try {
5861 while (cursor.moveToNext()) {
5862 final String tmpkey = cursor.getString(0);
5863 final String value = cursor.getString(1);
5864 userDataForAccount.put(tmpkey, value);
5865 }
5866 } finally {
5867 cursor.close();
5868 }
5869 return userDataForAccount;
5870 }
5871
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005872 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5873 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005874 HashMap<String, String> authTokensForAccount = new HashMap<>();
5875 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005876 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5877 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5878 new String[]{account.name, account.type},
5879 null, null, null);
5880 try {
5881 while (cursor.moveToNext()) {
5882 final String type = cursor.getString(0);
5883 final String authToken = cursor.getString(1);
5884 authTokensForAccount.put(type, authToken);
5885 }
5886 } finally {
5887 cursor.close();
5888 }
5889 return authTokensForAccount;
5890 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005891
5892 private Context getContextForUser(UserHandle user) {
5893 try {
5894 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5895 } catch (NameNotFoundException e) {
5896 // Default to mContext, not finding the package system is running as is unlikely.
5897 return mContext;
5898 }
5899 }
Sandra Kwan78812282015-11-04 11:19:47 -08005900
5901 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5902 try {
5903 response.onResult(result);
5904 } catch (RemoteException e) {
5905 // if the caller is dead then there is no one to care about remote
5906 // exceptions
5907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5908 Log.v(TAG, "failure while notifying response", e);
5909 }
5910 }
5911 }
5912
5913 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5914 String errorMessage) {
5915 try {
5916 response.onError(errorCode, errorMessage);
5917 } catch (RemoteException e) {
5918 // if the caller is dead then there is no one to care about remote
5919 // exceptions
5920 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5921 Log.v(TAG, "failure while notifying response", e);
5922 }
5923 }
5924 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005925
5926 private final class AccountManagerInternalImpl extends AccountManagerInternal {
5927 @Override
5928 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
5929 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
5930 if (account == null) {
5931 Slog.w(TAG, "account cannot be null");
5932 return;
5933 }
5934 if (packageName == null) {
5935 Slog.w(TAG, "packageName cannot be null");
5936 return;
5937 }
5938 if (userId < UserHandle.USER_SYSTEM) {
5939 Slog.w(TAG, "user id must be concrete");
5940 return;
5941 }
5942 if (callback == null) {
5943 Slog.w(TAG, "callback cannot be null");
5944 return;
5945 }
5946
5947 if (hasAccountAccess(account, packageName, new UserHandle(userId))) {
5948 Bundle result = new Bundle();
5949 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
5950 callback.sendResult(result);
5951 return;
5952 }
5953
5954 final int uid;
5955 try {
5956 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
5957 } catch (NameNotFoundException e) {
5958 Slog.e(TAG, "Unknown package " + packageName);
5959 return;
5960 }
5961
5962 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
5963 doNotification(mUsers.get(userId), account, null, intent, packageName, userId);
5964 }
5965 }
Fred Quintana60307342009-03-24 22:48:12 -07005966}