blob: 7ee5fd9fdf8a13de7ebc2023ae6db17944609c30 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070032import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080033import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070034import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070035import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070036import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010040import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070041import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.content.ContentValues;
44import android.content.Context;
45import android.content.Intent;
46import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070047import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070048import android.content.pm.ApplicationInfo;
49import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070050import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070051import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070052import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070053import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070054import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070055import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070056import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070057import android.database.Cursor;
58import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import android.database.sqlite.SQLiteDatabase;
60import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070061import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070062import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070063import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080064import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.IBinder;
67import android.os.Looper;
68import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070069import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070070import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import android.os.RemoteException;
72import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070073import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070074import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.text.TextUtils;
76import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070077import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070078import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080079import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070080
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070081import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080082import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080083import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070084import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070085import com.google.android.collect.Lists;
86import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070087
Oscar Montemayora8529f62009-11-18 10:14:20 -080088import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070089import java.io.FileDescriptor;
90import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -080091import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -070092import java.security.MessageDigest;
93import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070094import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070095import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080096import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070097import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070098import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070099import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700100import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800101import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700102import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800103import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700104import java.util.concurrent.atomic.AtomicInteger;
105import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700106
Fred Quintana60307342009-03-24 22:48:12 -0700107/**
108 * A system service that provides account, password, and authtoken management for all
109 * accounts on the device. Some of these calls are implemented with the help of the corresponding
110 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
111 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700112 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700113 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700114 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700115public class AccountManagerService
116 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800117 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Sandra Kwan78812282015-11-04 11:19:47 -0800118
Fred Quintana60307342009-03-24 22:48:12 -0700119 private static final String TAG = "AccountManagerService";
120
Fred Quintana60307342009-03-24 22:48:12 -0700121 private static final String DATABASE_NAME = "accounts.db";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700122 private static final int DATABASE_VERSION = 8;
123
124 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700125
126 private final Context mContext;
127
Fred Quintana56285a62010-12-02 14:20:51 -0800128 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700129 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700130 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800131
Fred Quintana60307342009-03-24 22:48:12 -0700132 private final MessageHandler mMessageHandler;
133
134 // Messages that can be sent on mHandler
135 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700136 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700137
Fred Quintana56285a62010-12-02 14:20:51 -0800138 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700139
140 private static final String TABLE_ACCOUNTS = "accounts";
141 private static final String ACCOUNTS_ID = "_id";
142 private static final String ACCOUNTS_NAME = "name";
143 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700144 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700145 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700146 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800147 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
148 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700149
150 private static final String TABLE_AUTHTOKENS = "authtokens";
151 private static final String AUTHTOKENS_ID = "_id";
152 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
153 private static final String AUTHTOKENS_TYPE = "type";
154 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
155
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700156 private static final String TABLE_GRANTS = "grants";
157 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
158 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
159 private static final String GRANTS_GRANTEE_UID = "uid";
160
Fred Quintana60307342009-03-24 22:48:12 -0700161 private static final String TABLE_EXTRAS = "extras";
162 private static final String EXTRAS_ID = "_id";
163 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
164 private static final String EXTRAS_KEY = "key";
165 private static final String EXTRAS_VALUE = "value";
166
167 private static final String TABLE_META = "meta";
168 private static final String META_KEY = "key";
169 private static final String META_VALUE = "value";
170
Amith Yamasani67df64b2012-12-14 12:09:36 -0800171 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
172
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700173 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
174 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700175 private static final Intent ACCOUNTS_CHANGED_INTENT;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700176 static {
177 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
178 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
179 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700180
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700181 private static final String COUNT_OF_MATCHING_GRANTS = ""
182 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
183 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
184 + " AND " + GRANTS_GRANTEE_UID + "=?"
185 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
186 + " AND " + ACCOUNTS_NAME + "=?"
187 + " AND " + ACCOUNTS_TYPE + "=?";
188
Fred Quintana56285a62010-12-02 14:20:51 -0800189 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
190 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700191
Fred Quintana56285a62010-12-02 14:20:51 -0800192 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
193 AUTHTOKENS_AUTHTOKEN};
194
195 private static final String SELECTION_USERDATA_BY_ACCOUNT =
196 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
197 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
198
Fred Quintanaa698f422009-04-08 19:14:54 -0700199 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700200 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
201
Amith Yamasani04e0d262012-02-14 11:50:53 -0800202 static class UserAccounts {
203 private final int userId;
204 private final DatabaseHelper openHelper;
205 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
206 credentialsPermissionNotificationIds =
207 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
208 private final HashMap<Account, Integer> signinRequiredNotificationIds =
209 new HashMap<Account, Integer>();
210 private final Object cacheLock = new Object();
211 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700212 private final HashMap<String, Account[]> accountCache =
213 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800215 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 new HashMap<Account, HashMap<String, String>>();
217 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800218 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800219 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700220
221 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700222 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700223
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700224 /**
225 * protected by the {@link #cacheLock}
226 *
227 * Caches the previous names associated with an account. Previous names
228 * should be cached because we expect that when an Account is renamed,
229 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
230 * want to know if the accounts they care about have been renamed.
231 *
232 * The previous names are wrapped in an {@link AtomicReference} so that
233 * we can distinguish between those accounts with no previous names and
234 * those whose previous names haven't been cached (yet).
235 */
236 private final HashMap<Account, AtomicReference<String>> previousNameCache =
237 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800238
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700239 private int debugDbInsertionPoint = -1;
240 private SQLiteStatement statementForLogging;
241
Amith Yamasani04e0d262012-02-14 11:50:53 -0800242 UserAccounts(Context context, int userId) {
243 this.userId = userId;
244 synchronized (cacheLock) {
245 openHelper = new DatabaseHelper(context, userId);
246 }
247 }
248 }
249
250 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
251
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700252 private static AtomicReference<AccountManagerService> sThis =
253 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700254 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700255
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700256 /**
257 * This should only be called by system code. One should only call this after the service
258 * has started.
259 * @return a reference to the AccountManagerService instance
260 * @hide
261 */
262 public static AccountManagerService getSingleton() {
263 return sThis.get();
264 }
Fred Quintana60307342009-03-24 22:48:12 -0700265
Fred Quintana56285a62010-12-02 14:20:51 -0800266 public AccountManagerService(Context context) {
267 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700268 }
269
Fred Quintana56285a62010-12-02 14:20:51 -0800270 public AccountManagerService(Context context, PackageManager packageManager,
271 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700272 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800273 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700274 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700275
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700276 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintana56285a62010-12-02 14:20:51 -0800278 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800279 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700280
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700281 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800282
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800283 IntentFilter intentFilter = new IntentFilter();
284 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
285 intentFilter.addDataScheme("package");
286 mContext.registerReceiver(new BroadcastReceiver() {
287 @Override
288 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700289 // Don't delete accounts when updating a authenticator's
290 // package.
291 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700292 /* Purging data requires file io, don't block the main thread. This is probably
293 * less than ideal because we are introducing a race condition where old grants
294 * could be exercised until they are purged. But that race condition existed
295 * anyway with the broadcast receiver.
296 *
297 * Ideally, we would completely clear the cache, purge data from the database,
298 * and then rebuild the cache. All under the cache lock. But that change is too
299 * large at this point.
300 */
301 Runnable r = new Runnable() {
302 @Override
303 public void run() {
304 purgeOldGrantsAll();
305 }
306 };
307 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700308 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800309 }
310 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800311
Amith Yamasani13593602012-03-22 16:16:17 -0700312 IntentFilter userFilter = new IntentFilter();
313 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800314 userFilter.addAction(Intent.ACTION_USER_STARTED);
315 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700316 @Override
317 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800318 String action = intent.getAction();
319 if (Intent.ACTION_USER_REMOVED.equals(action)) {
320 onUserRemoved(intent);
321 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
322 onUserStarted(intent);
323 }
Amith Yamasani13593602012-03-22 16:16:17 -0700324 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800325 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800326 }
327
Dianne Hackborn164371f2013-10-01 19:10:13 -0700328 @Override
329 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
330 throws RemoteException {
331 try {
332 return super.onTransact(code, data, reply, flags);
333 } catch (RuntimeException e) {
334 // The account manager only throws security exceptions, so let's
335 // log all others.
336 if (!(e instanceof SecurityException)) {
337 Slog.wtf(TAG, "Account Manager Crash", e);
338 }
339 throw e;
340 }
341 }
342
Kenny Root26ff6622012-07-30 12:58:03 -0700343 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700344 }
345
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 private UserManager getUserManager() {
347 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700348 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700349 }
350 return mUserManager;
351 }
352
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700353 /**
354 * Validate internal set of accounts against installed authenticators for
355 * given user. Clears cached authenticators before validating.
356 */
357 public void validateAccounts(int userId) {
358 final UserAccounts accounts = getUserAccounts(userId);
359
360 // Invalidate user-specific cache to make sure we catch any
361 // removed authenticators.
362 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
363 }
364
365 /**
366 * Validate internal set of accounts against installed authenticators for
367 * given user. Clear cached authenticators before validating when requested.
368 */
369 private void validateAccountsInternal(
370 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
371 if (invalidateAuthenticatorCache) {
372 mAuthenticatorCache.invalidateCache(accounts.userId);
373 }
374
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700375 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
376 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
377 mAuthenticatorCache.getAllServices(accounts.userId)) {
378 knownAuth.add(service.type);
379 }
380
Amith Yamasani04e0d262012-02-14 11:50:53 -0800381 synchronized (accounts.cacheLock) {
382 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800383 boolean accountDeleted = false;
384 Cursor cursor = db.query(TABLE_ACCOUNTS,
385 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800386 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800387 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800388 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800389 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700390 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800391 while (cursor.moveToNext()) {
392 final long accountId = cursor.getLong(0);
393 final String accountType = cursor.getString(1);
394 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700395
396 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700397 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800398 + accountType + " no longer has a registered authenticator");
399 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
400 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700401
402 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
403 accountId, accounts);
404
Fred Quintana56285a62010-12-02 14:20:51 -0800405 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 accounts.userDataCache.remove(account);
407 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700408 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800409 } else {
410 ArrayList<String> accountNames = accountNamesByType.get(accountType);
411 if (accountNames == null) {
412 accountNames = new ArrayList<String>();
413 accountNamesByType.put(accountType, accountNames);
414 }
415 accountNames.add(accountName);
416 }
417 }
Andy McFadden2f362292012-01-20 14:43:38 -0800418 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800419 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800420 final String accountType = cur.getKey();
421 final ArrayList<String> accountNames = cur.getValue();
422 final Account[] accountsForType = new Account[accountNames.size()];
423 int i = 0;
424 for (String accountName : accountNames) {
425 accountsForType[i] = new Account(accountName, accountType);
426 ++i;
427 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800428 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800429 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800430 } finally {
431 cursor.close();
432 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800433 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800434 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800435 }
436 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700437 }
438
Amith Yamasani04e0d262012-02-14 11:50:53 -0800439 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700440 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800441 }
442
443 protected UserAccounts getUserAccounts(int userId) {
444 synchronized (mUsers) {
445 UserAccounts accounts = mUsers.get(userId);
446 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700447 accounts = new UserAccounts(mContext, userId);
448 initializeDebugDbSizeAndCompileSqlStatementForLogging(
449 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700451 purgeOldGrants(accounts);
452 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800453 }
454 return accounts;
455 }
456 }
457
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700458 private void purgeOldGrantsAll() {
459 synchronized (mUsers) {
460 for (int i = 0; i < mUsers.size(); i++) {
461 purgeOldGrants(mUsers.valueAt(i));
462 }
463 }
464 }
465
466 private void purgeOldGrants(UserAccounts accounts) {
467 synchronized (accounts.cacheLock) {
468 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
469 final Cursor cursor = db.query(TABLE_GRANTS,
470 new String[]{GRANTS_GRANTEE_UID},
471 null, null, GRANTS_GRANTEE_UID, null, null);
472 try {
473 while (cursor.moveToNext()) {
474 final int uid = cursor.getInt(0);
475 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
476 if (packageExists) {
477 continue;
478 }
479 Log.d(TAG, "deleting grants for UID " + uid
480 + " because its package is no longer installed");
481 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
482 new String[]{Integer.toString(uid)});
483 }
484 } finally {
485 cursor.close();
486 }
487 }
488 }
489
Amith Yamasani13593602012-03-22 16:16:17 -0700490 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700491 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700492 if (userId < 1) return;
493
494 UserAccounts accounts;
495 synchronized (mUsers) {
496 accounts = mUsers.get(userId);
497 mUsers.remove(userId);
498 }
499 if (accounts == null) {
500 File dbFile = new File(getDatabaseName(userId));
501 dbFile.delete();
502 return;
503 }
504
505 synchronized (accounts.cacheLock) {
506 accounts.openHelper.close();
507 File dbFile = new File(getDatabaseName(userId));
508 dbFile.delete();
509 }
510 }
511
Amith Yamasani67df64b2012-12-14 12:09:36 -0800512 private void onUserStarted(Intent intent) {
513 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
514 if (userId < 1) return;
515
516 // Check if there's a shared account that needs to be created as an account
517 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
518 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700519 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700520 int parentUserId = UserManager.isSplitSystemUser()
521 ? mUserManager.getUserInfo(userId).restrictedProfileParentId
522 : UserHandle.USER_SYSTEM;
523 if (parentUserId < 0) {
524 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
525 return;
526 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800527 for (Account sa : sharedAccounts) {
528 if (ArrayUtils.contains(accounts, sa)) continue;
529 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700530 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800531 }
532 }
533
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700534 @Override
535 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700536 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700537 }
538
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800539 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700540 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700541 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800542 if (Log.isLoggable(TAG, Log.VERBOSE)) {
543 Log.v(TAG, "getPassword: " + account
544 + ", caller's uid " + Binder.getCallingUid()
545 + ", pid " + Binder.getCallingPid());
546 }
Fred Quintana382601f2010-03-25 12:25:10 -0700547 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000548 int userId = UserHandle.getCallingUserId();
549 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700550 String msg = String.format(
551 "uid %s cannot get secrets for accounts of type: %s",
552 callingUid,
553 account.type);
554 throw new SecurityException(msg);
555 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700556 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700557 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700558 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800559 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700560 } finally {
561 restoreCallingIdentity(identityToken);
562 }
563 }
564
Amith Yamasani04e0d262012-02-14 11:50:53 -0800565 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700566 if (account == null) {
567 return null;
568 }
569
Amith Yamasani04e0d262012-02-14 11:50:53 -0800570 synchronized (accounts.cacheLock) {
571 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800572 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
573 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
574 new String[]{account.name, account.type}, null, null, null);
575 try {
576 if (cursor.moveToNext()) {
577 return cursor.getString(0);
578 }
579 return null;
580 } finally {
581 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700582 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700583 }
584 }
585
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800586 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700587 public String getPreviousName(Account account) {
588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
589 Log.v(TAG, "getPreviousName: " + account
590 + ", caller's uid " + Binder.getCallingUid()
591 + ", pid " + Binder.getCallingPid());
592 }
593 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700594 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700595 long identityToken = clearCallingIdentity();
596 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700597 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700598 return readPreviousNameInternal(accounts, account);
599 } finally {
600 restoreCallingIdentity(identityToken);
601 }
602 }
603
604 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
605 if (account == null) {
606 return null;
607 }
608 synchronized (accounts.cacheLock) {
609 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
610 if (previousNameRef == null) {
611 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
612 Cursor cursor = db.query(
613 TABLE_ACCOUNTS,
614 new String[]{ ACCOUNTS_PREVIOUS_NAME },
615 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
616 new String[] { account.name, account.type },
617 null,
618 null,
619 null);
620 try {
621 if (cursor.moveToNext()) {
622 String previousName = cursor.getString(0);
623 previousNameRef = new AtomicReference<String>(previousName);
624 accounts.previousNameCache.put(account, previousNameRef);
625 return previousName;
626 } else {
627 return null;
628 }
629 } finally {
630 cursor.close();
631 }
632 } else {
633 return previousNameRef.get();
634 }
635 }
636 }
637
638 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700639 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700640 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800641 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700642 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
643 account, key, callingUid, Binder.getCallingPid());
644 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800645 }
Fred Quintana382601f2010-03-25 12:25:10 -0700646 if (account == null) throw new IllegalArgumentException("account is null");
647 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000648 int userId = UserHandle.getCallingUserId();
649 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700650 String msg = String.format(
651 "uid %s cannot get user data for accounts of type: %s",
652 callingUid,
653 account.type);
654 throw new SecurityException(msg);
655 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700656 long identityToken = clearCallingIdentity();
657 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700658 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800659 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700660 } finally {
661 restoreCallingIdentity(identityToken);
662 }
663 }
664
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800665 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100666 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700667 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800668 if (Log.isLoggable(TAG, Log.VERBOSE)) {
669 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100670 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700671 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800672 + ", pid " + Binder.getCallingPid());
673 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100674 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700675 if (isCrossUser(callingUid, userId)) {
676 throw new SecurityException(
677 String.format(
678 "User %s tying to get authenticator types for %s" ,
679 UserHandle.getCallingUserId(),
680 userId));
681 }
682
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700683 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700684 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000685 return getAuthenticatorTypesInternal(userId);
686
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 } finally {
688 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700689 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700690 }
691
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000692 /**
693 * Should only be called inside of a clearCallingIdentity block.
694 */
695 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
696 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
697 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
698 AuthenticatorDescription[] types =
699 new AuthenticatorDescription[authenticatorCollection.size()];
700 int i = 0;
701 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
702 : authenticatorCollection) {
703 types[i] = authenticator.type;
704 i++;
705 }
706 return types;
707 }
708
709
710
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700711 private boolean isCrossUser(int callingUid, int userId) {
712 return (userId != UserHandle.getCallingUserId()
713 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100714 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700715 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
716 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100717 }
718
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700719 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700720 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700721 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800722 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700723 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700724 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800725 + ", pid " + Binder.getCallingPid());
726 }
Fred Quintana382601f2010-03-25 12:25:10 -0700727 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000728 int userId = UserHandle.getCallingUserId();
729 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700730 String msg = String.format(
731 "uid %s cannot explicitly add accounts of type: %s",
732 callingUid,
733 account.type);
734 throw new SecurityException(msg);
735 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700736 /*
737 * Child users are not allowed to add accounts. Only the accounts that are
738 * shared by the parent profile can be added to child profile.
739 *
740 * TODO: Only allow accounts that were shared to be added by
741 * a limited user.
742 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700743
Fred Quintana60307342009-03-24 22:48:12 -0700744 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700745 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700746 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700747 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000748 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700749 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700750 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700751 }
752 }
753
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000754 @Override
755 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700756 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700757 int callingUid = Binder.getCallingUid();
758 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
759 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000760 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700761 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800762 final UserAccounts fromAccounts = getUserAccounts(userFrom);
763 final UserAccounts toAccounts = getUserAccounts(userTo);
764 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000765 if (response != null) {
766 Bundle result = new Bundle();
767 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
768 try {
769 response.onResult(result);
770 } catch (RemoteException e) {
771 Slog.w(TAG, "Failed to report error back to the client." + e);
772 }
773 }
774 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800775 }
776
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000777 Slog.d(TAG, "Copying account " + account.name
778 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800779 long identityToken = clearCallingIdentity();
780 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000781 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800782 false /* stripAuthTokenFromResult */, account.name,
783 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700784 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800785 protected String toDebugString(long now) {
786 return super.toDebugString(now) + ", getAccountCredentialsForClone"
787 + ", " + account.type;
788 }
789
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700790 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800791 public void run() throws RemoteException {
792 mAuthenticator.getAccountCredentialsForCloning(this, account);
793 }
794
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700795 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800796 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000797 if (result != null
798 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
799 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700800 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800801 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800802 super.onResult(result);
803 }
804 }
805 }.bind();
806 } finally {
807 restoreCallingIdentity(identityToken);
808 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800809 }
810
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800811 @Override
812 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700813 final int callingUid = Binder.getCallingUid();
814 if (Log.isLoggable(TAG, Log.VERBOSE)) {
815 String msg = String.format(
816 "accountAuthenticated( account: %s, callerUid: %s)",
817 account,
818 callingUid);
819 Log.v(TAG, msg);
820 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800821 if (account == null) {
822 throw new IllegalArgumentException("account is null");
823 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000824 int userId = UserHandle.getCallingUserId();
825 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700826 String msg = String.format(
827 "uid %s cannot notify authentication for accounts of type: %s",
828 callingUid,
829 account.type);
830 throw new SecurityException(msg);
831 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000832
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800833 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
834 return false;
835 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000836
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700837 long identityToken = clearCallingIdentity();
838 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000839 UserAccounts accounts = getUserAccounts(userId);
840 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700841 } finally {
842 restoreCallingIdentity(identityToken);
843 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700844 }
845
846 private boolean updateLastAuthenticatedTime(Account account) {
847 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800848 synchronized (accounts.cacheLock) {
849 final ContentValues values = new ContentValues();
850 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
851 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
852 int i = db.update(
853 TABLE_ACCOUNTS,
854 values,
855 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
856 new String[] {
857 account.name, account.type
858 });
859 if (i > 0) {
860 return true;
861 }
862 }
863 return false;
864 }
865
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000866 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700867 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
868 final int parentUserId){
Amith Yamasani67df64b2012-12-14 12:09:36 -0800869 long id = clearCallingIdentity();
870 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000871 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800872 false /* stripAuthTokenFromResult */, account.name,
873 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700874 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800875 protected String toDebugString(long now) {
876 return super.toDebugString(now) + ", getAccountCredentialsForClone"
877 + ", " + account.type;
878 }
879
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700880 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800881 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700882 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700883 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700884 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700885 for (Account acc : getAccounts(parentUserId,
886 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700887 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000888 mAuthenticator.addAccountFromCredentials(
889 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700890 break;
891 }
892 }
893 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800894 }
895
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700896 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800897 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000898 // TODO: Anything to do if if succedded?
899 // TODO: If it failed: Show error notification? Should we remove the shadow
900 // account to avoid retries?
901 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800902 }
903
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700904 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800905 public void onError(int errorCode, String errorMessage) {
906 super.onError(errorCode, errorMessage);
907 // TODO: Show error notification to user
908 // TODO: Should we remove the shadow account so that it doesn't keep trying?
909 }
910
911 }.bind();
912 } finally {
913 restoreCallingIdentity(id);
914 }
915 }
916
Amith Yamasani04e0d262012-02-14 11:50:53 -0800917 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700918 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700919 if (account == null) {
920 return false;
921 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 synchronized (accounts.cacheLock) {
923 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800924 db.beginTransaction();
925 try {
926 long numMatches = DatabaseUtils.longForQuery(db,
927 "select count(*) from " + TABLE_ACCOUNTS
928 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
929 new String[]{account.name, account.type});
930 if (numMatches > 0) {
931 Log.w(TAG, "insertAccountIntoDatabase: " + account
932 + ", skipping since the account already exists");
933 return false;
934 }
935 ContentValues values = new ContentValues();
936 values.put(ACCOUNTS_NAME, account.name);
937 values.put(ACCOUNTS_TYPE, account.type);
938 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800939 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800940 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
941 if (accountId < 0) {
942 Log.w(TAG, "insertAccountIntoDatabase: " + account
943 + ", skipping the DB insert failed");
944 return false;
945 }
946 if (extras != null) {
947 for (String key : extras.keySet()) {
948 final String value = extras.getString(key);
949 if (insertExtraLocked(db, accountId, key, value) < 0) {
950 Log.w(TAG, "insertAccountIntoDatabase: " + account
951 + ", skipping since insertExtra failed for key " + key);
952 return false;
953 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700954 }
955 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800956 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700957
958 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
959 accounts, callingUid);
960
Amith Yamasani04e0d262012-02-14 11:50:53 -0800961 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800962 } finally {
963 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700964 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800965 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700966 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700967 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
968 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700969 }
970 return true;
971 }
972
973 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700974 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -0700975 * running, then clone the account too.
976 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700977 *
Amith Yamasani5be347b2013-03-31 17:44:31 -0700978 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700979 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700980 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700981 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700982 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700983 addSharedAccountAsUser(account, user.id);
984 try {
Jeff Sharkeye17ac152015-11-06 22:40:29 -0800985 if (ActivityManagerNative.getDefault().isUserRunning(user.id, 0)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700986 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700987 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -0700988 }
989 } catch (RemoteException re) {
990 // Shouldn't happen
991 }
992 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700993 }
994 }
995
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800996 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700997 ContentValues values = new ContentValues();
998 values.put(EXTRAS_KEY, key);
999 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1000 values.put(EXTRAS_VALUE, value);
1001 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
1002 }
1003
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001004 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001005 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001006 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001007 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001008 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1009 Log.v(TAG, "hasFeatures: " + account
1010 + ", response " + response
1011 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001012 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001013 + ", pid " + Binder.getCallingPid());
1014 }
Fred Quintana382601f2010-03-25 12:25:10 -07001015 if (response == null) throw new IllegalArgumentException("response is null");
1016 if (account == null) throw new IllegalArgumentException("account is null");
1017 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001018 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001019 checkReadAccountsPermitted(callingUid, account.type, userId,
1020 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001021
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001022 long identityToken = clearCallingIdentity();
1023 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001024 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001026 } finally {
1027 restoreCallingIdentity(identityToken);
1028 }
1029 }
1030
1031 private class TestFeaturesSession extends Session {
1032 private final String[] mFeatures;
1033 private final Account mAccount;
1034
Amith Yamasani04e0d262012-02-14 11:50:53 -08001035 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001036 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001038 true /* stripAuthTokenFromResult */, account.name,
1039 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001040 mFeatures = features;
1041 mAccount = account;
1042 }
1043
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001044 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001045 public void run() throws RemoteException {
1046 try {
1047 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1048 } catch (RemoteException e) {
1049 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1050 }
1051 }
1052
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001053 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001054 public void onResult(Bundle result) {
1055 IAccountManagerResponse response = getResponseAndClose();
1056 if (response != null) {
1057 try {
1058 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001059 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001060 return;
1061 }
Fred Quintana56285a62010-12-02 14:20:51 -08001062 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1063 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1064 + response);
1065 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001066 final Bundle newResult = new Bundle();
1067 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1068 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1069 response.onResult(newResult);
1070 } catch (RemoteException e) {
1071 // if the caller is dead then there is no one to care about remote exceptions
1072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1073 Log.v(TAG, "failure while notifying response", e);
1074 }
1075 }
1076 }
1077 }
1078
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001079 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001080 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001081 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001082 + ", " + mAccount
1083 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1084 }
1085 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001086
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001087 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001088 public void renameAccount(
1089 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001090 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001091 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1092 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001093 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001094 + ", pid " + Binder.getCallingPid());
1095 }
1096 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001097 int userId = UserHandle.getCallingUserId();
1098 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001099 String msg = String.format(
1100 "uid %s cannot rename accounts of type: %s",
1101 callingUid,
1102 accountToRename.type);
1103 throw new SecurityException(msg);
1104 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001105 long identityToken = clearCallingIdentity();
1106 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001107 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001108 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001109 Bundle result = new Bundle();
1110 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1111 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1112 try {
1113 response.onResult(result);
1114 } catch (RemoteException e) {
1115 Log.w(TAG, e.getMessage());
1116 }
1117 } finally {
1118 restoreCallingIdentity(identityToken);
1119 }
1120 }
1121
1122 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001123 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001124 Account resultAccount = null;
1125 /*
1126 * Cancel existing notifications. Let authenticators
1127 * re-post notifications as required. But we don't know if
1128 * the authenticators have bound their notifications to
1129 * now stale account name data.
1130 *
1131 * With a rename api, we might not need to do this anymore but it
1132 * shouldn't hurt.
1133 */
1134 cancelNotification(
1135 getSigninRequiredNotificationId(accounts, accountToRename),
1136 new UserHandle(accounts.userId));
1137 synchronized(accounts.credentialsPermissionNotificationIds) {
1138 for (Pair<Pair<Account, String>, Integer> pair:
1139 accounts.credentialsPermissionNotificationIds.keySet()) {
1140 if (accountToRename.equals(pair.first.first)) {
1141 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1142 cancelNotification(id, new UserHandle(accounts.userId));
1143 }
1144 }
1145 }
1146 synchronized (accounts.cacheLock) {
1147 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1148 db.beginTransaction();
1149 boolean isSuccessful = false;
1150 Account renamedAccount = new Account(newName, accountToRename.type);
1151 try {
1152 final ContentValues values = new ContentValues();
1153 values.put(ACCOUNTS_NAME, newName);
1154 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1155 final long accountId = getAccountIdLocked(db, accountToRename);
1156 if (accountId >= 0) {
1157 final String[] argsAccountId = { String.valueOf(accountId) };
1158 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1159 db.setTransactionSuccessful();
1160 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001161 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1162 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001163 }
1164 } finally {
1165 db.endTransaction();
1166 if (isSuccessful) {
1167 /*
1168 * Database transaction was successful. Clean up cached
1169 * data associated with the account in the user profile.
1170 */
1171 insertAccountIntoCacheLocked(accounts, renamedAccount);
1172 /*
1173 * Extract the data and token caches before removing the
1174 * old account to preserve the user data associated with
1175 * the account.
1176 */
1177 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1178 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1179 removeAccountFromCacheLocked(accounts, accountToRename);
1180 /*
1181 * Update the cached data associated with the renamed
1182 * account.
1183 */
1184 accounts.userDataCache.put(renamedAccount, tmpData);
1185 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1186 accounts.previousNameCache.put(
1187 renamedAccount,
1188 new AtomicReference<String>(accountToRename.name));
1189 resultAccount = renamedAccount;
1190
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001191 int parentUserId = accounts.userId;
1192 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001193 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001194 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001195 * those users with which the account was shared.
1196 */
1197 List<UserInfo> users = mUserManager.getUsers(true);
1198 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001199 if (user.isRestricted()
1200 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001201 renameSharedAccountAsUser(accountToRename, newName, user.id);
1202 }
1203 }
1204 }
1205 sendAccountsChangedBroadcast(accounts.userId);
1206 }
1207 }
1208 }
1209 return resultAccount;
1210 }
1211
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001212 private boolean canHaveProfile(final int parentUserId) {
1213 final UserInfo userInfo = mUserManager.getUserInfo(parentUserId);
1214 return userInfo != null && userInfo.canHaveProfile();
1215 }
1216
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001217 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001218 public void removeAccount(IAccountManagerResponse response, Account account,
1219 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001220 removeAccountAsUser(
1221 response,
1222 account,
1223 expectActivityLaunch,
1224 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001225 }
1226
1227 @Override
1228 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001229 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001230 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001231 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1232 Log.v(TAG, "removeAccount: " + account
1233 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001234 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001235 + ", pid " + Binder.getCallingPid()
1236 + ", for user id " + userId);
1237 }
1238 if (response == null) throw new IllegalArgumentException("response is null");
1239 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001240 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001241 if (isCrossUser(callingUid, userId)) {
1242 throw new SecurityException(
1243 String.format(
1244 "User %s tying remove account for %s" ,
1245 UserHandle.getCallingUserId(),
1246 userId));
1247 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001248 /*
1249 * Only the system or authenticator should be allowed to remove accounts for that
1250 * authenticator. This will let users remove accounts (via Settings in the system) but not
1251 * arbitrary applications (like competing authenticators).
1252 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001253 UserHandle user = new UserHandle(userId);
1254 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1255 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001256 String msg = String.format(
1257 "uid %s cannot remove accounts of type: %s",
1258 callingUid,
1259 account.type);
1260 throw new SecurityException(msg);
1261 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001262 if (!canUserModifyAccounts(userId)) {
1263 try {
1264 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1265 "User cannot modify accounts");
1266 } catch (RemoteException re) {
1267 }
1268 return;
1269 }
1270 if (!canUserModifyAccountsForType(userId, account.type)) {
1271 try {
1272 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1273 "User cannot modify accounts of this type (policy).");
1274 } catch (RemoteException re) {
1275 }
1276 return;
1277 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001278 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001279 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001280 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001281 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001282 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001283 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001284 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001286 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001287 }
1288 }
1289 }
1290
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001291 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1292
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001293 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001294 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1295 } finally {
1296 restoreCallingIdentity(identityToken);
1297 }
1298 }
1299
1300 @Override
1301 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001302 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001303 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1304 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001305 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001306 + ", pid " + Binder.getCallingPid());
1307 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001308 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001309 if (account == null) {
1310 /*
1311 * Null accounts should result in returning false, as per
1312 * AccountManage.addAccountExplicitly(...) java doc.
1313 */
1314 Log.e(TAG, "account is null");
1315 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001316 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001317 String msg = String.format(
1318 "uid %s cannot explicitly add accounts of type: %s",
1319 callingUid,
1320 account.type);
1321 throw new SecurityException(msg);
1322 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001323 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001324 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1325 return false;
1326 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001327 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001328 long identityToken = clearCallingIdentity();
1329 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001330 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001331 } finally {
1332 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001333 }
Fred Quintana60307342009-03-24 22:48:12 -07001334 }
1335
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001336 private class RemoveAccountSession extends Session {
1337 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001338 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001339 Account account, boolean expectActivityLaunch) {
1340 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001341 true /* stripAuthTokenFromResult */, account.name,
1342 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001343 mAccount = account;
1344 }
1345
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001346 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001347 protected String toDebugString(long now) {
1348 return super.toDebugString(now) + ", removeAccount"
1349 + ", account " + mAccount;
1350 }
1351
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001352 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001353 public void run() throws RemoteException {
1354 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1355 }
1356
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001357 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001358 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001359 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1360 && !result.containsKey(AccountManager.KEY_INTENT)) {
1361 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001362 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001363 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001364 }
1365 IAccountManagerResponse response = getResponseAndClose();
1366 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001367 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1368 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1369 + response);
1370 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001371 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001372 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001373 try {
1374 response.onResult(result2);
1375 } catch (RemoteException e) {
1376 // ignore
1377 }
1378 }
1379 }
1380 super.onResult(result);
1381 }
1382 }
1383
Amith Yamasani04e0d262012-02-14 11:50:53 -08001384 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001385 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001386 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 }
1388
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001389 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001390 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001391 synchronized (accounts.cacheLock) {
1392 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001393 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001394 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1395 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001396 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001397 removeAccountFromCacheLocked(accounts, account);
1398 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001399
1400 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001401 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001402 long id = Binder.clearCallingIdentity();
1403 try {
1404 int parentUserId = accounts.userId;
1405 if (canHaveProfile(parentUserId)) {
1406 // Remove from any restricted profiles that are sharing this account.
Amith Yamasani67df64b2012-12-14 12:09:36 -08001407 List<UserInfo> users = mUserManager.getUsers(true);
1408 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001409 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001410 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001411 }
1412 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001413 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001414 } finally {
1415 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001416 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001417 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001418 }
1419
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001420 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001421 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001422 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001423 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1424 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001425 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001426 + ", pid " + Binder.getCallingPid());
1427 }
Fred Quintana382601f2010-03-25 12:25:10 -07001428 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1429 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001430 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001431 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001432 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001433 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001434 synchronized (accounts.cacheLock) {
1435 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001436 db.beginTransaction();
1437 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001438 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001439 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001440 db.setTransactionSuccessful();
1441 } finally {
1442 db.endTransaction();
1443 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001444 }
Fred Quintana60307342009-03-24 22:48:12 -07001445 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001446 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001447 }
1448 }
1449
Carlos Valdivia91979be2015-05-22 14:11:35 -07001450 private void invalidateCustomTokenLocked(
1451 UserAccounts accounts,
1452 String accountType,
1453 String authToken) {
1454 if (authToken == null || accountType == null) {
1455 return;
1456 }
1457 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001458 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001459 }
1460
Amith Yamasani04e0d262012-02-14 11:50:53 -08001461 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1462 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001463 if (authToken == null || accountType == null) {
1464 return;
1465 }
Fred Quintana33269202009-04-20 16:05:10 -07001466 Cursor cursor = db.rawQuery(
1467 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1468 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1469 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1470 + " FROM " + TABLE_ACCOUNTS
1471 + " JOIN " + TABLE_AUTHTOKENS
1472 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1473 + " = " + AUTHTOKENS_ACCOUNTS_ID
1474 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1475 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1476 new String[]{authToken, accountType});
1477 try {
1478 while (cursor.moveToNext()) {
1479 long authTokenId = cursor.getLong(0);
1480 String accountName = cursor.getString(1);
1481 String authTokenType = cursor.getString(2);
1482 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001483 writeAuthTokenIntoCacheLocked(
1484 accounts,
1485 db,
1486 new Account(accountName, accountType),
1487 authTokenType,
1488 null);
Fred Quintana60307342009-03-24 22:48:12 -07001489 }
Fred Quintana33269202009-04-20 16:05:10 -07001490 } finally {
1491 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001492 }
1493 }
1494
Carlos Valdivia91979be2015-05-22 14:11:35 -07001495 private void saveCachedToken(
1496 UserAccounts accounts,
1497 Account account,
1498 String callerPkg,
1499 byte[] callerSigDigest,
1500 String tokenType,
1501 String token,
1502 long expiryMillis) {
1503
1504 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1505 return;
1506 }
1507 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1508 new UserHandle(accounts.userId));
1509 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001510 accounts.accountTokenCaches.put(
1511 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001512 }
1513 }
1514
Amith Yamasani04e0d262012-02-14 11:50:53 -08001515 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1516 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001517 if (account == null || type == null) {
1518 return false;
1519 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001520 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1521 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001522 synchronized (accounts.cacheLock) {
1523 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001524 db.beginTransaction();
1525 try {
1526 long accountId = getAccountIdLocked(db, account);
1527 if (accountId < 0) {
1528 return false;
1529 }
1530 db.delete(TABLE_AUTHTOKENS,
1531 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1532 new String[]{type});
1533 ContentValues values = new ContentValues();
1534 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1535 values.put(AUTHTOKENS_TYPE, type);
1536 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1537 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1538 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001539 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001540 return true;
1541 }
Fred Quintana33269202009-04-20 16:05:10 -07001542 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001543 } finally {
1544 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001545 }
Fred Quintana60307342009-03-24 22:48:12 -07001546 }
1547 }
1548
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001549 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001550 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001551 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1553 Log.v(TAG, "peekAuthToken: " + account
1554 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001555 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001556 + ", pid " + Binder.getCallingPid());
1557 }
Fred Quintana382601f2010-03-25 12:25:10 -07001558 if (account == null) throw new IllegalArgumentException("account is null");
1559 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001560 int userId = UserHandle.getCallingUserId();
1561 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001562 String msg = String.format(
1563 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1564 callingUid,
1565 account.type);
1566 throw new SecurityException(msg);
1567 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001568 long identityToken = clearCallingIdentity();
1569 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001570 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001571 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001572 } finally {
1573 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001574 }
Fred Quintana60307342009-03-24 22:48:12 -07001575 }
1576
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001577 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001578 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001579 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001580 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1581 Log.v(TAG, "setAuthToken: " + account
1582 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001583 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001584 + ", pid " + Binder.getCallingPid());
1585 }
Fred Quintana382601f2010-03-25 12:25:10 -07001586 if (account == null) throw new IllegalArgumentException("account is null");
1587 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001588 int userId = UserHandle.getCallingUserId();
1589 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001590 String msg = String.format(
1591 "uid %s cannot set auth tokens associated with accounts of type: %s",
1592 callingUid,
1593 account.type);
1594 throw new SecurityException(msg);
1595 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001596 long identityToken = clearCallingIdentity();
1597 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001598 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001599 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001600 } finally {
1601 restoreCallingIdentity(identityToken);
1602 }
Fred Quintana60307342009-03-24 22:48:12 -07001603 }
1604
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001605 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001606 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001607 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1609 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001610 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001611 + ", pid " + Binder.getCallingPid());
1612 }
Fred Quintana382601f2010-03-25 12:25:10 -07001613 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001614 int userId = UserHandle.getCallingUserId();
1615 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001616 String msg = String.format(
1617 "uid %s cannot set secrets for accounts of type: %s",
1618 callingUid,
1619 account.type);
1620 throw new SecurityException(msg);
1621 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001622 long identityToken = clearCallingIdentity();
1623 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001624 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001625 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001626 } finally {
1627 restoreCallingIdentity(identityToken);
1628 }
Fred Quintana60307342009-03-24 22:48:12 -07001629 }
1630
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001631 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1632 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001633 if (account == null) {
1634 return;
1635 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001636 synchronized (accounts.cacheLock) {
1637 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001638 db.beginTransaction();
1639 try {
1640 final ContentValues values = new ContentValues();
1641 values.put(ACCOUNTS_PASSWORD, password);
1642 final long accountId = getAccountIdLocked(db, account);
1643 if (accountId >= 0) {
1644 final String[] argsAccountId = {String.valueOf(accountId)};
1645 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1646 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001647 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001648 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001649 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001650
1651 String action = (password == null || password.length() == 0) ?
1652 DebugDbHelper.ACTION_CLEAR_PASSWORD
1653 : DebugDbHelper.ACTION_SET_PASSWORD;
1654 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001655 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001656 } finally {
1657 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001658 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001659 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001660 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001661 }
1662
Amith Yamasani04e0d262012-02-14 11:50:53 -08001663 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001664 Log.i(TAG, "the accounts changed, sending broadcast of "
1665 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001666 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001667 }
1668
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001669 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001670 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001671 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001672 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1673 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001674 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001675 + ", pid " + Binder.getCallingPid());
1676 }
Fred Quintana382601f2010-03-25 12:25:10 -07001677 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001678 int userId = UserHandle.getCallingUserId();
1679 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001680 String msg = String.format(
1681 "uid %s cannot clear passwords for accounts of type: %s",
1682 callingUid,
1683 account.type);
1684 throw new SecurityException(msg);
1685 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001686 long identityToken = clearCallingIdentity();
1687 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001688 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001689 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001690 } finally {
1691 restoreCallingIdentity(identityToken);
1692 }
Fred Quintana60307342009-03-24 22:48:12 -07001693 }
1694
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001695 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001696 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001697 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001698 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1699 Log.v(TAG, "setUserData: " + account
1700 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001701 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001702 + ", pid " + Binder.getCallingPid());
1703 }
Fred Quintana382601f2010-03-25 12:25:10 -07001704 if (key == null) throw new IllegalArgumentException("key is null");
1705 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001706 int userId = UserHandle.getCallingUserId();
1707 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001708 String msg = String.format(
1709 "uid %s cannot set user data for accounts of type: %s",
1710 callingUid,
1711 account.type);
1712 throw new SecurityException(msg);
1713 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001714 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001715 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001716 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001717 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001718 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001719 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001720 }
1721 }
1722
Amith Yamasani04e0d262012-02-14 11:50:53 -08001723 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1724 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001725 if (account == null || key == null) {
1726 return;
1727 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001728 synchronized (accounts.cacheLock) {
1729 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001730 db.beginTransaction();
1731 try {
1732 long accountId = getAccountIdLocked(db, account);
1733 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001734 return;
1735 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001736 long extrasId = getExtrasIdLocked(db, accountId, key);
1737 if (extrasId < 0 ) {
1738 extrasId = insertExtraLocked(db, accountId, key, value);
1739 if (extrasId < 0) {
1740 return;
1741 }
1742 } else {
1743 ContentValues values = new ContentValues();
1744 values.put(EXTRAS_VALUE, value);
1745 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1746 return;
1747 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001748
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001749 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001750 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001751 db.setTransactionSuccessful();
1752 } finally {
1753 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001754 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001755 }
1756 }
1757
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001758 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001759 if (result == null) {
1760 Log.e(TAG, "the result is unexpectedly null", new Exception());
1761 }
1762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1763 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1764 + response);
1765 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001766 try {
1767 response.onResult(result);
1768 } catch (RemoteException e) {
1769 // if the caller is dead then there is no one to care about remote
1770 // exceptions
1771 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1772 Log.v(TAG, "failure while notifying response", e);
1773 }
1774 }
1775 }
1776
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001777 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001778 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1779 final String authTokenType)
1780 throws RemoteException {
1781 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001782 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1783
Fred Quintanad9640ec2012-05-23 12:37:00 -07001784 final int callingUid = getCallingUid();
1785 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001786 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001787 throw new SecurityException("can only call from system");
1788 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001789 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001790 long identityToken = clearCallingIdentity();
1791 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001792 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001793 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1794 false /* stripAuthTokenFromResult */, null /* accountName */,
1795 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001796 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001797 protected String toDebugString(long now) {
1798 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001799 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001800 + ", authTokenType " + authTokenType;
1801 }
1802
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001803 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001804 public void run() throws RemoteException {
1805 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1806 }
1807
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001808 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001809 public void onResult(Bundle result) {
1810 if (result != null) {
1811 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1812 Bundle bundle = new Bundle();
1813 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1814 super.onResult(bundle);
1815 return;
1816 } else {
1817 super.onResult(result);
1818 }
1819 }
1820 }.bind();
1821 } finally {
1822 restoreCallingIdentity(identityToken);
1823 }
1824 }
1825
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001826 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001827 public void getAuthToken(
1828 IAccountManagerResponse response,
1829 final Account account,
1830 final String authTokenType,
1831 final boolean notifyOnAuthFailure,
1832 final boolean expectActivityLaunch,
1833 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1835 Log.v(TAG, "getAuthToken: " + account
1836 + ", response " + response
1837 + ", authTokenType " + authTokenType
1838 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1839 + ", expectActivityLaunch " + expectActivityLaunch
1840 + ", caller's uid " + Binder.getCallingUid()
1841 + ", pid " + Binder.getCallingPid());
1842 }
Fred Quintana382601f2010-03-25 12:25:10 -07001843 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001844 try {
1845 if (account == null) {
1846 Slog.w(TAG, "getAuthToken called with null account");
1847 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1848 return;
1849 }
1850 if (authTokenType == null) {
1851 Slog.w(TAG, "getAuthToken called with null authTokenType");
1852 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1853 return;
1854 }
1855 } catch (RemoteException e) {
1856 Slog.w(TAG, "Failed to report error back to the client." + e);
1857 return;
1858 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001859 int userId = UserHandle.getCallingUserId();
1860 long ident = Binder.clearCallingIdentity();
1861 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001862 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001863 try {
1864 accounts = getUserAccounts(userId);
1865 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1866 AuthenticatorDescription.newKey(account.type), accounts.userId);
1867 } finally {
1868 Binder.restoreCallingIdentity(ident);
1869 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001870
Costin Manolachea40c6302010-12-13 14:50:45 -08001871 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001872 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001873
1874 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001875 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001876 final boolean permissionGranted =
1877 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001878
Carlos Valdivia91979be2015-05-22 14:11:35 -07001879 // Get the calling package. We will use it for the purpose of caching.
1880 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001881 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001882 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001883 try {
1884 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1885 } finally {
1886 Binder.restoreCallingIdentity(ident);
1887 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001888 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1889 String msg = String.format(
1890 "Uid %s is attempting to illegally masquerade as package %s!",
1891 callerUid,
1892 callerPkg);
1893 throw new SecurityException(msg);
1894 }
1895
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001896 // let authenticator know the identity of the caller
1897 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1898 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001899
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001900 if (notifyOnAuthFailure) {
1901 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001902 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001903
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001904 long identityToken = clearCallingIdentity();
1905 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001906 // Distill the caller's package signatures into a single digest.
1907 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1908
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001909 // if the caller has permission, do the peek. otherwise go the more expensive
1910 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001911 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001912 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001913 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001914 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001915 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1916 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1917 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001918 onResult(response, result);
1919 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001920 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001921 }
1922
Carlos Valdivia91979be2015-05-22 14:11:35 -07001923 if (customTokens) {
1924 /*
1925 * Look up tokens in the new cache only if the loginOptions don't have parameters
1926 * outside of those expected to be injected by the AccountManager, e.g.
1927 * ANDORID_PACKAGE_NAME.
1928 */
1929 String token = readCachedTokenInternal(
1930 accounts,
1931 account,
1932 authTokenType,
1933 callerPkg,
1934 callerPkgSigDigest);
1935 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001936 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1937 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
1938 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001939 Bundle result = new Bundle();
1940 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1941 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1942 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1943 onResult(response, result);
1944 return;
1945 }
1946 }
1947
Amith Yamasani04e0d262012-02-14 11:50:53 -08001948 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001949 false /* stripAuthTokenFromResult */, account.name,
1950 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001951 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001952 protected String toDebugString(long now) {
1953 if (loginOptions != null) loginOptions.keySet();
1954 return super.toDebugString(now) + ", getAuthToken"
1955 + ", " + account
1956 + ", authTokenType " + authTokenType
1957 + ", loginOptions " + loginOptions
1958 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1959 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001960
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001961 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001962 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001963 // If the caller doesn't have permission then create and return the
1964 // "grant permission" intent instead of the "getAuthToken" intent.
1965 if (!permissionGranted) {
1966 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1967 } else {
1968 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1969 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001970 }
1971
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001972 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001973 public void onResult(Bundle result) {
1974 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001975 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001976 Intent intent = newGrantCredentialsPermissionIntent(
1977 account,
1978 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001979 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001980 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001981 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001982 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001983 onResult(bundle);
1984 return;
1985 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001986 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001987 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001988 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1989 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001990 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001991 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001992 "the type and name should not be empty");
1993 return;
1994 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001995 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001996 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001997 saveAuthTokenToDatabase(
1998 mAccounts,
1999 resultAccount,
2000 authTokenType,
2001 authToken);
2002 }
2003 long expiryMillis = result.getLong(
2004 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2005 if (customTokens
2006 && expiryMillis > System.currentTimeMillis()) {
2007 saveCachedToken(
2008 mAccounts,
2009 account,
2010 callerPkg,
2011 callerPkgSigDigest,
2012 authTokenType,
2013 authToken,
2014 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002015 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002016 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002017
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002018 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002019 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002020 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002021 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002022 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002023 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002024 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002025 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002026 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002027 }.bind();
2028 } finally {
2029 restoreCallingIdentity(identityToken);
2030 }
Fred Quintana60307342009-03-24 22:48:12 -07002031 }
2032
Carlos Valdivia91979be2015-05-22 14:11:35 -07002033 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2034 MessageDigest digester;
2035 try {
2036 digester = MessageDigest.getInstance("SHA-256");
2037 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2038 callerPkg, PackageManager.GET_SIGNATURES);
2039 for (Signature sig : pkgInfo.signatures) {
2040 digester.update(sig.toByteArray());
2041 }
2042 } catch (NoSuchAlgorithmException x) {
2043 Log.wtf(TAG, "SHA-256 should be available", x);
2044 digester = null;
2045 } catch (NameNotFoundException e) {
2046 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2047 digester = null;
2048 }
2049 return (digester == null) ? null : digester.digest();
2050 }
2051
Dianne Hackborn41203752012-08-31 14:05:51 -07002052 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2053 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002054 int uid = intent.getIntExtra(
2055 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2056 String authTokenType = intent.getStringExtra(
2057 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002058 final String titleAndSubtitle =
2059 mContext.getString(R.string.permission_request_notification_with_subtitle,
2060 account.name);
2061 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002062 String title = titleAndSubtitle;
2063 String subtitle = "";
2064 if (index > 0) {
2065 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002066 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002067 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002068 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002069 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002070 Notification n = new Notification.Builder(contextForUser)
2071 .setSmallIcon(android.R.drawable.stat_sys_warning)
2072 .setWhen(0)
2073 .setColor(contextForUser.getColor(
2074 com.android.internal.R.color.system_notification_accent_color))
2075 .setContentTitle(title)
2076 .setContentText(subtitle)
2077 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2078 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2079 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002080 installNotification(getCredentialPermissionNotificationId(
2081 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002082 }
2083
Costin Manolache5f383ad92010-12-02 16:44:46 -08002084 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002085 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002086
2087 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002088 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002089 // Since it was set in Eclair+ we can't change it without breaking apps using
2090 // the intent from a non-Activity context.
2091 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002092 intent.addCategory(
2093 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002094
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002095 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002096 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2097 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002098 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002099
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002100 return intent;
2101 }
2102
2103 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2104 int uid) {
2105 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002106 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002107 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002108 final Pair<Pair<Account, String>, Integer> key =
2109 new Pair<Pair<Account, String>, Integer>(
2110 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002111 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002112 if (id == null) {
2113 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002114 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002115 }
2116 }
2117 return id;
2118 }
2119
Amith Yamasani04e0d262012-02-14 11:50:53 -08002120 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002121 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002122 synchronized (accounts.signinRequiredNotificationIds) {
2123 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 if (id == null) {
2125 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002126 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002127 }
2128 }
2129 return id;
2130 }
2131
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002132 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002133 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002134 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002135 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002136 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2137 Log.v(TAG, "addAccount: accountType " + accountType
2138 + ", response " + response
2139 + ", authTokenType " + authTokenType
2140 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2141 + ", expectActivityLaunch " + expectActivityLaunch
2142 + ", caller's uid " + Binder.getCallingUid()
2143 + ", pid " + Binder.getCallingPid());
2144 }
Fred Quintana382601f2010-03-25 12:25:10 -07002145 if (response == null) throw new IllegalArgumentException("response is null");
2146 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002147
Amith Yamasani71e6c692013-03-24 17:39:28 -07002148 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002149 int userId = Binder.getCallingUserHandle().getIdentifier();
2150 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002151 try {
2152 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2153 "User is not allowed to add an account!");
2154 } catch (RemoteException re) {
2155 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002156 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002157 return;
2158 }
2159 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002160 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002161 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2162 "User cannot modify accounts of this type (policy).");
2163 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002164 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002165 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2166 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002167 return;
2168 }
2169
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002170 final int pid = Binder.getCallingPid();
2171 final int uid = Binder.getCallingUid();
2172 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2173 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2174 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2175
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002176 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002177 long identityToken = clearCallingIdentity();
2178 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002179 UserAccounts accounts = getUserAccounts(usrId);
2180 logRecordWithUid(
2181 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002182 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002183 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002184 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002185 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002186 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002187 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002188 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002189 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002190
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002191 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002192 protected String toDebugString(long now) {
2193 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002194 + ", accountType " + accountType
2195 + ", requiredFeatures "
2196 + (requiredFeatures != null
2197 ? TextUtils.join(",", requiredFeatures)
2198 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002199 }
2200 }.bind();
2201 } finally {
2202 restoreCallingIdentity(identityToken);
2203 }
Fred Quintana60307342009-03-24 22:48:12 -07002204 }
2205
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002206 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002207 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2208 final String authTokenType, final String[] requiredFeatures,
2209 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002210 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002211 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2212 Log.v(TAG, "addAccount: accountType " + accountType
2213 + ", response " + response
2214 + ", authTokenType " + authTokenType
2215 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2216 + ", expectActivityLaunch " + expectActivityLaunch
2217 + ", caller's uid " + Binder.getCallingUid()
2218 + ", pid " + Binder.getCallingPid()
2219 + ", for user id " + userId);
2220 }
2221 if (response == null) throw new IllegalArgumentException("response is null");
2222 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002223 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002224 if (isCrossUser(callingUid, userId)) {
2225 throw new SecurityException(
2226 String.format(
2227 "User %s trying to add account for %s" ,
2228 UserHandle.getCallingUserId(),
2229 userId));
2230 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002231
2232 // Is user disallowed from modifying accounts?
2233 if (!canUserModifyAccounts(userId)) {
2234 try {
2235 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2236 "User is not allowed to add an account!");
2237 } catch (RemoteException re) {
2238 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002239 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002240 return;
2241 }
2242 if (!canUserModifyAccountsForType(userId, accountType)) {
2243 try {
2244 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2245 "User cannot modify accounts of this type (policy).");
2246 } catch (RemoteException re) {
2247 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002248 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2249 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002250 return;
2251 }
2252
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002253 final int pid = Binder.getCallingPid();
2254 final int uid = Binder.getCallingUid();
2255 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2256 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2257 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2258
2259 long identityToken = clearCallingIdentity();
2260 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002261 UserAccounts accounts = getUserAccounts(userId);
2262 logRecordWithUid(
2263 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002264 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002265 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002266 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002267 @Override
2268 public void run() throws RemoteException {
2269 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2270 options);
2271 }
2272
2273 @Override
2274 protected String toDebugString(long now) {
2275 return super.toDebugString(now) + ", addAccount"
2276 + ", accountType " + accountType
2277 + ", requiredFeatures "
2278 + (requiredFeatures != null
2279 ? TextUtils.join(",", requiredFeatures)
2280 : null);
2281 }
2282 }.bind();
2283 } finally {
2284 restoreCallingIdentity(identityToken);
2285 }
2286 }
2287
Sandra Kwan78812282015-11-04 11:19:47 -08002288 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002289 public void startAddAccountSession(
2290 final IAccountManagerResponse response,
2291 final String accountType,
2292 final String authTokenType,
2293 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002294 final boolean expectActivityLaunch,
2295 final Bundle optionsIn) {
2296 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2297 Log.v(TAG,
2298 "startAddAccountSession: accountType " + accountType
2299 + ", response " + response
2300 + ", authTokenType " + authTokenType
2301 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2302 + ", expectActivityLaunch " + expectActivityLaunch
2303 + ", caller's uid " + Binder.getCallingUid()
2304 + ", pid " + Binder.getCallingPid());
2305 }
2306 if (response == null) {
2307 throw new IllegalArgumentException("response is null");
2308 }
2309 if (accountType == null) {
2310 throw new IllegalArgumentException("accountType is null");
2311 }
2312
2313 int userId = Binder.getCallingUserHandle().getIdentifier();
2314 if (!canUserModifyAccounts(userId)) {
2315 try {
2316 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2317 "User is not allowed to add an account!");
2318 } catch (RemoteException re) {
2319 }
2320 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2321 return;
2322 }
2323 if (!canUserModifyAccountsForType(userId, accountType)) {
2324 try {
2325 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2326 "User cannot modify accounts of this type (policy).");
2327 } catch (RemoteException re) {
2328 }
2329 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2330 userId);
2331 return;
2332 }
2333
2334 final int pid = Binder.getCallingPid();
2335 final int uid = Binder.getCallingUid();
2336 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2337 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2338 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2339
2340 int usrId = UserHandle.getCallingUserId();
2341 long identityToken = clearCallingIdentity();
2342 try {
2343 UserAccounts accounts = getUserAccounts(usrId);
2344 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2345 TABLE_ACCOUNTS, uid);
2346 new StartAccountSession(accounts, response, accountType, expectActivityLaunch,
2347 null /* accountName */, false /* authDetailsRequired */,
2348 true /* updateLastAuthenticationTime */) {
2349 @Override
2350 public void run() throws RemoteException {
2351 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2352 requiredFeatures, options);
2353 }
2354
2355 @Override
2356 protected String toDebugString(long now) {
2357 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2358 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2359 + accountType + ", requiredFeatures "
2360 + (requiredFeatures != null ? requiredFeaturesStr : null);
2361 }
2362 }.bind();
2363 } finally {
2364 restoreCallingIdentity(identityToken);
2365 }
2366 }
2367
2368 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2369 private abstract class StartAccountSession extends Session {
2370
2371 public StartAccountSession(UserAccounts accounts, IAccountManagerResponse response,
2372 String accountType, boolean expectActivityLaunch, String accountName,
2373 boolean authDetailsRequired, boolean updateLastAuthenticationTime) {
2374 super(accounts, response, accountType, expectActivityLaunch,
2375 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2376 updateLastAuthenticationTime);
2377 }
2378
2379 @Override
2380 public void onResult(Bundle result) {
2381 mNumResults++;
2382 Intent intent = null;
2383
2384 if (result != null
2385 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2386 /*
2387 * The Authenticator API allows third party authenticators to
2388 * supply arbitrary intents to other apps that they can run,
2389 * this can be very bad when those apps are in the system like
2390 * the System Settings.
2391 */
2392 int authenticatorUid = Binder.getCallingUid();
2393 long bid = Binder.clearCallingIdentity();
2394 try {
2395 PackageManager pm = mContext.getPackageManager();
2396 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2397 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2398 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authenticatorUid,
2399 targetUid)) {
2400 throw new SecurityException("Activity to be started with KEY_INTENT must "
2401 + "share Authenticator's signatures");
2402 }
2403 } finally {
2404 Binder.restoreCallingIdentity(bid);
2405 }
2406 }
2407
2408 IAccountManagerResponse response;
2409 if (mExpectActivityLaunch && result != null
2410 && result.containsKey(AccountManager.KEY_INTENT)) {
2411 response = mResponse;
2412 } else {
2413 response = getResponseAndClose();
2414 }
2415 if (response == null) {
2416 return;
2417 }
2418 if (result == null) {
2419 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2420 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2421 + response);
2422 }
2423 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2424 "null bundle returned");
2425 return;
2426 }
2427
2428 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2429 // All AccountManager error codes are greater
2430 // than 0
2431 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2432 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2433 return;
2434 }
2435
2436 // Strip auth token from result.
2437 result.remove(AccountManager.KEY_AUTHTOKEN);
2438
2439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2440 Log.v(TAG,
2441 getClass().getSimpleName() + " calling onResult() on response " + response);
2442 }
2443
2444 // Get the session bundle created by authenticator. The
2445 // bundle contains data necessary for finishing the session
2446 // later. The session bundle will be encrypted here and
2447 // decrypted later when trying to finish the session.
2448 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2449 if (sessionBundle != null) {
2450 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2451 if (TextUtils.isEmpty(accountType)
2452 && !mAccountType.equalsIgnoreCase(mAccountType)) {
2453 Log.w(TAG, "Account type in session bundle doesn't match request.");
2454 }
2455 // Add accountType info to session bundle. This will
2456 // override any value set by authenticator.
2457 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2458
2459 // Encrypt session bundle before returning to caller.
2460 try {
2461 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2462 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2463 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2464 } catch (GeneralSecurityException e) {
2465 if (Log.isLoggable(TAG, Log.DEBUG)) {
2466 Log.v(TAG, "Failed to encrypt session bundle!", e);
2467 }
2468 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2469 "failed to encrypt session bundle");
2470 return;
2471 }
2472 }
2473
2474 sendResponse(response, result);
2475 }
2476 }
2477
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002478 @Override
2479 public void finishSession(IAccountManagerResponse response,
2480 @NonNull Bundle sessionBundle,
2481 boolean expectActivityLaunch,
2482 Bundle appInfo) {
2483 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2484 Log.v(TAG,
2485 "finishSession: response "+ response
2486 + ", expectActivityLaunch " + expectActivityLaunch
2487 + ", caller's uid " + Binder.getCallingUid()
2488 + ", pid " + Binder.getCallingPid());
2489 }
2490 if (response == null) {
2491 throw new IllegalArgumentException("response is null");
2492 }
2493
2494 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2495 // Account type is added to it before encryption.
2496 if (sessionBundle == null || sessionBundle.size() == 0) {
2497 throw new IllegalArgumentException("sessionBundle is empty");
2498 }
2499
2500 int userId = Binder.getCallingUserHandle().getIdentifier();
2501 if (!canUserModifyAccounts(userId)) {
2502 sendErrorResponse(response,
2503 AccountManager.ERROR_CODE_USER_RESTRICTED,
2504 "User is not allowed to add an account!");
2505 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2506 return;
2507 }
2508
2509 final int pid = Binder.getCallingPid();
2510 final int uid = Binder.getCallingUid();
2511 final Bundle decryptedBundle;
2512 final String accountType;
2513 // First decrypt session bundle to get account type for checking permission.
2514 try {
2515 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2516 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2517 if (decryptedBundle == null) {
2518 sendErrorResponse(
2519 response,
2520 AccountManager.ERROR_CODE_BAD_REQUEST,
2521 "failed to decrypt session bundle");
2522 return;
2523 }
2524 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2525 // Account type cannot be null. This should not happen if session bundle was created
2526 // properly by #StartAccountSession.
2527 if (TextUtils.isEmpty(accountType)) {
2528 sendErrorResponse(
2529 response,
2530 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2531 "accountType is empty");
2532 return;
2533 }
2534
2535 // If by any chances, decryptedBundle contains colliding keys with
2536 // system info
2537 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2538 // update credentials flow, we should replace with the new values of the current call.
2539 if (appInfo != null) {
2540 decryptedBundle.putAll(appInfo);
2541 }
2542
2543 // Add info that may be used by add account or update credentials flow.
2544 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, uid);
2545 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2546 } catch (GeneralSecurityException e) {
2547 if (Log.isLoggable(TAG, Log.DEBUG)) {
2548 Log.v(TAG, "Failed to decrypt session bundle!", e);
2549 }
2550 sendErrorResponse(
2551 response,
2552 AccountManager.ERROR_CODE_BAD_REQUEST,
2553 "failed to decrypt session bundle");
2554 return;
2555 }
2556
2557 if (!canUserModifyAccountsForType(userId, accountType)) {
2558 sendErrorResponse(
2559 response,
2560 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2561 "User cannot modify accounts of this type (policy).");
2562 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2563 userId);
2564 return;
2565 }
2566
2567 long identityToken = clearCallingIdentity();
2568 try {
2569 UserAccounts accounts = getUserAccounts(userId);
2570 logRecordWithUid(
2571 accounts,
2572 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2573 TABLE_ACCOUNTS,
2574 uid);
2575 new Session(
2576 accounts,
2577 response,
2578 accountType,
2579 expectActivityLaunch,
2580 true /* stripAuthTokenFromResult */,
2581 null /* accountName */,
2582 false /* authDetailsRequired */,
2583 true /* updateLastAuthenticationTime */) {
2584 @Override
2585 public void run() throws RemoteException {
2586 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2587 }
2588
2589 @Override
2590 protected String toDebugString(long now) {
2591 return super.toDebugString(now)
2592 + ", finishSession"
2593 + ", accountType " + accountType;
2594 }
2595 }.bind();
2596 } finally {
2597 restoreCallingIdentity(identityToken);
2598 }
2599 }
2600
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002601 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002602 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2603 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2604 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2605 long identityToken = clearCallingIdentity();
2606 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002607 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002608 } finally {
2609 restoreCallingIdentity(identityToken);
2610 }
2611 }
2612
2613 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002614 public void confirmCredentialsAsUser(
2615 IAccountManagerResponse response,
2616 final Account account,
2617 final Bundle options,
2618 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002619 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002620 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2622 Log.v(TAG, "confirmCredentials: " + account
2623 + ", response " + response
2624 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002625 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002626 + ", pid " + Binder.getCallingPid());
2627 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002628 // Only allow the system process to read accounts of other users
2629 if (isCrossUser(callingUid, userId)) {
2630 throw new SecurityException(
2631 String.format(
2632 "User %s trying to confirm account credentials for %s" ,
2633 UserHandle.getCallingUserId(),
2634 userId));
2635 }
Fred Quintana382601f2010-03-25 12:25:10 -07002636 if (response == null) throw new IllegalArgumentException("response is null");
2637 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002638 long identityToken = clearCallingIdentity();
2639 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002640 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002641 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002642 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002643 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002644 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002645 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002646 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002647 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002648 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002649 protected String toDebugString(long now) {
2650 return super.toDebugString(now) + ", confirmCredentials"
2651 + ", " + account;
2652 }
2653 }.bind();
2654 } finally {
2655 restoreCallingIdentity(identityToken);
2656 }
Fred Quintana60307342009-03-24 22:48:12 -07002657 }
2658
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002659 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002660 public void updateCredentials(IAccountManagerResponse response, final Account account,
2661 final String authTokenType, final boolean expectActivityLaunch,
2662 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2664 Log.v(TAG, "updateCredentials: " + account
2665 + ", response " + response
2666 + ", authTokenType " + authTokenType
2667 + ", expectActivityLaunch " + expectActivityLaunch
2668 + ", caller's uid " + Binder.getCallingUid()
2669 + ", pid " + Binder.getCallingPid());
2670 }
Fred Quintana382601f2010-03-25 12:25:10 -07002671 if (response == null) throw new IllegalArgumentException("response is null");
2672 if (account == null) throw new IllegalArgumentException("account is null");
2673 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002674 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002675 long identityToken = clearCallingIdentity();
2676 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002677 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002678 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002679 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002680 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002681 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002682 public void run() throws RemoteException {
2683 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2684 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002685 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002686 protected String toDebugString(long now) {
2687 if (loginOptions != null) loginOptions.keySet();
2688 return super.toDebugString(now) + ", updateCredentials"
2689 + ", " + account
2690 + ", authTokenType " + authTokenType
2691 + ", loginOptions " + loginOptions;
2692 }
2693 }.bind();
2694 } finally {
2695 restoreCallingIdentity(identityToken);
2696 }
Fred Quintana60307342009-03-24 22:48:12 -07002697 }
2698
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002699 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002700 public void startUpdateCredentialsSession(
2701 IAccountManagerResponse response,
2702 final Account account,
2703 final String authTokenType,
2704 final boolean expectActivityLaunch,
2705 final Bundle loginOptions) {
2706 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2707 Log.v(TAG,
2708 "startUpdateCredentialsSession: " + account + ", response " + response
2709 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2710 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2711 + ", pid " + Binder.getCallingPid());
2712 }
2713 if (response == null) {
2714 throw new IllegalArgumentException("response is null");
2715 }
2716 if (account == null) {
2717 throw new IllegalArgumentException("account is null");
2718 }
2719 int userId = UserHandle.getCallingUserId();
2720 long identityToken = clearCallingIdentity();
2721 try {
2722 UserAccounts accounts = getUserAccounts(userId);
2723 new StartAccountSession(
2724 accounts,
2725 response,
2726 account.type,
2727 expectActivityLaunch,
2728 account.name,
2729 false /* authDetailsRequired */,
2730 true /* updateLastCredentialTime */) {
2731 @Override
2732 public void run() throws RemoteException {
2733 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2734 loginOptions);
2735 }
2736
2737 @Override
2738 protected String toDebugString(long now) {
2739 if (loginOptions != null)
2740 loginOptions.keySet();
2741 return super.toDebugString(now)
2742 + ", startUpdateCredentialsSession"
2743 + ", " + account
2744 + ", authTokenType " + authTokenType
2745 + ", loginOptions " + loginOptions;
2746 }
2747 }.bind();
2748 } finally {
2749 restoreCallingIdentity(identityToken);
2750 }
2751 }
2752
2753 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002754 public void editProperties(IAccountManagerResponse response, final String accountType,
2755 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002756 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002757 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2758 Log.v(TAG, "editProperties: accountType " + accountType
2759 + ", response " + response
2760 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002761 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002762 + ", pid " + Binder.getCallingPid());
2763 }
Fred Quintana382601f2010-03-25 12:25:10 -07002764 if (response == null) throw new IllegalArgumentException("response is null");
2765 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002766 int userId = UserHandle.getCallingUserId();
2767 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002768 String msg = String.format(
2769 "uid %s cannot edit authenticator properites for account type: %s",
2770 callingUid,
2771 accountType);
2772 throw new SecurityException(msg);
2773 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002774 long identityToken = clearCallingIdentity();
2775 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002776 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002777 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002778 true /* stripAuthTokenFromResult */, null /* accountName */,
2779 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002780 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002781 public void run() throws RemoteException {
2782 mAuthenticator.editProperties(this, mAccountType);
2783 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002784 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002785 protected String toDebugString(long now) {
2786 return super.toDebugString(now) + ", editProperties"
2787 + ", accountType " + accountType;
2788 }
2789 }.bind();
2790 } finally {
2791 restoreCallingIdentity(identityToken);
2792 }
Fred Quintana60307342009-03-24 22:48:12 -07002793 }
2794
Fred Quintana33269202009-04-20 16:05:10 -07002795 private class GetAccountsByTypeAndFeatureSession extends Session {
2796 private final String[] mFeatures;
2797 private volatile Account[] mAccountsOfType = null;
2798 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2799 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002800 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002801
Amith Yamasani04e0d262012-02-14 11:50:53 -08002802 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002803 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002804 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002805 true /* stripAuthTokenFromResult */, null /* accountName */,
2806 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002807 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002808 mFeatures = features;
2809 }
2810
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002811 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002812 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002813 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002814 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2815 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002816 }
Fred Quintana33269202009-04-20 16:05:10 -07002817 // check whether each account matches the requested features
2818 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2819 mCurrentAccount = 0;
2820
2821 checkAccount();
2822 }
2823
2824 public void checkAccount() {
2825 if (mCurrentAccount >= mAccountsOfType.length) {
2826 sendResult();
2827 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002828 }
Fred Quintana33269202009-04-20 16:05:10 -07002829
Fred Quintana29e94b82010-03-10 12:11:51 -08002830 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2831 if (accountAuthenticator == null) {
2832 // It is possible that the authenticator has died, which is indicated by
2833 // mAuthenticator being set to null. If this happens then just abort.
2834 // There is no need to send back a result or error in this case since
2835 // that already happened when mAuthenticator was cleared.
2836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2837 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2838 + " connected to the authenticator, " + toDebugString());
2839 }
2840 return;
2841 }
Fred Quintana33269202009-04-20 16:05:10 -07002842 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002843 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002844 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002845 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002846 }
2847 }
2848
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002849 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002850 public void onResult(Bundle result) {
2851 mNumResults++;
2852 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002853 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002854 return;
2855 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002856 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002857 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2858 }
2859 mCurrentAccount++;
2860 checkAccount();
2861 }
2862
2863 public void sendResult() {
2864 IAccountManagerResponse response = getResponseAndClose();
2865 if (response != null) {
2866 try {
2867 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2868 for (int i = 0; i < accounts.length; i++) {
2869 accounts[i] = mAccountsWithFeatures.get(i);
2870 }
Fred Quintana56285a62010-12-02 14:20:51 -08002871 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2872 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2873 + response);
2874 }
Fred Quintana33269202009-04-20 16:05:10 -07002875 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002876 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002877 response.onResult(result);
2878 } catch (RemoteException e) {
2879 // if the caller is dead then there is no one to care about remote exceptions
2880 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2881 Log.v(TAG, "failure while notifying response", e);
2882 }
2883 }
2884 }
2885 }
2886
2887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002888 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002889 protected String toDebugString(long now) {
2890 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2891 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2892 }
2893 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002894
Amith Yamasani04e0d262012-02-14 11:50:53 -08002895 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002896 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08002897 * @hide
2898 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002899 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07002900 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002901 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07002902 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2903 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002904 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002905 return new Account[0];
2906 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002907 long identityToken = clearCallingIdentity();
2908 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002909 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002910 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002911 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002912 callingUid,
2913 null, // packageName
2914 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002915 } finally {
2916 restoreCallingIdentity(identityToken);
2917 }
2918 }
2919
Amith Yamasanif29f2362012-04-05 18:29:52 -07002920 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002921 * Returns accounts for all running users.
2922 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002923 * @hide
2924 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002925 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002926 public AccountAndUser[] getRunningAccounts() {
2927 final int[] runningUserIds;
2928 try {
2929 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2930 } catch (RemoteException e) {
2931 // Running in system_server; should never happen
2932 throw new RuntimeException(e);
2933 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002934 return getAccounts(runningUserIds);
2935 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002936
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002937 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002938 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002939 public AccountAndUser[] getAllAccounts() {
2940 final List<UserInfo> users = getUserManager().getUsers();
2941 final int[] userIds = new int[users.size()];
2942 for (int i = 0; i < userIds.length; i++) {
2943 userIds[i] = users.get(i).id;
2944 }
2945 return getAccounts(userIds);
2946 }
2947
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002948 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002949 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002950 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002951 for (int userId : userIds) {
2952 UserAccounts userAccounts = getUserAccounts(userId);
2953 if (userAccounts == null) continue;
2954 synchronized (userAccounts.cacheLock) {
2955 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2956 Binder.getCallingUid(), null);
2957 for (int a = 0; a < accounts.length; a++) {
2958 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002959 }
2960 }
2961 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002962
2963 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2964 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002965 }
2966
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002967 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002968 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07002969 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
2970 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002971 }
2972
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07002973 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002974 private Account[] getAccountsAsUser(
2975 String type,
2976 int userId,
2977 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07002978 int packageUid,
2979 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002980 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002981 // Only allow the system process to read accounts of other users
2982 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002983 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002984 && mContext.checkCallingOrSelfPermission(
2985 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2986 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002987 throw new SecurityException("User " + UserHandle.getCallingUserId()
2988 + " trying to get account for " + userId);
2989 }
2990
Fred Quintana56285a62010-12-02 14:20:51 -08002991 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2992 Log.v(TAG, "getAccounts: accountType " + type
2993 + ", caller's uid " + Binder.getCallingUid()
2994 + ", pid " + Binder.getCallingPid());
2995 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002996 // If the original calling app was using the framework account chooser activity, we'll
2997 // be passed in the original caller's uid here, which is what should be used for filtering.
2998 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2999 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003000 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003001 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003002
Svetoslavf3f02ac2015-09-08 14:36:35 -07003003 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3004 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003005 if (visibleAccountTypes.isEmpty()
3006 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003007 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003008 } else if (visibleAccountTypes.contains(type)) {
3009 // Prune the list down to just the requested type.
3010 visibleAccountTypes = new ArrayList<>();
3011 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003012 } // else aggregate all the visible accounts (it won't matter if the
3013 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003014
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003015 long identityToken = clearCallingIdentity();
3016 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003017 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003018 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003019 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003020 callingUid,
3021 callingPackage,
3022 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003023 } finally {
3024 restoreCallingIdentity(identityToken);
3025 }
3026 }
3027
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003028 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003029 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003030 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003031 int callingUid,
3032 String callingPackage,
3033 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003034 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003035 ArrayList<Account> visibleAccounts = new ArrayList<>();
3036 for (String visibleType : visibleAccountTypes) {
3037 Account[] accountsForType = getAccountsFromCacheLocked(
3038 userAccounts, visibleType, callingUid, callingPackage);
3039 if (accountsForType != null) {
3040 visibleAccounts.addAll(Arrays.asList(accountsForType));
3041 }
3042 }
3043 Account[] result = new Account[visibleAccounts.size()];
3044 for (int i = 0; i < visibleAccounts.size(); i++) {
3045 result[i] = visibleAccounts.get(i);
3046 }
3047 return result;
3048 }
3049 }
3050
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003051 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003052 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3053 checkManageUsersPermission("addSharedAccountsFromParentUser");
3054 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3055 for (Account account : accounts) {
3056 addSharedAccountAsUser(account, userId);
3057 }
3058 }
3059
3060 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003061 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003062 UserAccounts accounts = getUserAccounts(userId);
3063 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003064 ContentValues values = new ContentValues();
3065 values.put(ACCOUNTS_NAME, account.name);
3066 values.put(ACCOUNTS_TYPE, account.type);
3067 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3068 new String[] {account.name, account.type});
3069 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3070 if (accountId < 0) {
3071 Log.w(TAG, "insertAccountIntoDatabase: " + account
3072 + ", skipping the DB insert failed");
3073 return false;
3074 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003075 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003076 return true;
3077 }
3078
3079 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003080 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3081 userId = handleIncomingUser(userId);
3082 UserAccounts accounts = getUserAccounts(userId);
3083 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003084 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003085 final ContentValues values = new ContentValues();
3086 values.put(ACCOUNTS_NAME, newName);
3087 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
3088 int r = db.update(
3089 TABLE_SHARED_ACCOUNTS,
3090 values,
3091 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3092 new String[] { account.name, account.type });
3093 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003094 int callingUid = getCallingUid();
3095 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3096 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003097 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003098 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003099 }
3100 return r > 0;
3101 }
3102
3103 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003104 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003105 return removeSharedAccountAsUser(account, userId, getCallingUid());
3106 }
3107
3108 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003109 userId = handleIncomingUser(userId);
3110 UserAccounts accounts = getUserAccounts(userId);
3111 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003112 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003113 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3114 new String[] {account.name, account.type});
3115 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003116 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3117 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003118 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003119 }
3120 return r > 0;
3121 }
3122
3123 @Override
3124 public Account[] getSharedAccountsAsUser(int userId) {
3125 userId = handleIncomingUser(userId);
3126 UserAccounts accounts = getUserAccounts(userId);
3127 ArrayList<Account> accountList = new ArrayList<Account>();
3128 Cursor cursor = null;
3129 try {
3130 cursor = accounts.openHelper.getReadableDatabase()
3131 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3132 null, null, null, null, null);
3133 if (cursor != null && cursor.moveToFirst()) {
3134 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3135 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3136 do {
3137 accountList.add(new Account(cursor.getString(nameIndex),
3138 cursor.getString(typeIndex)));
3139 } while (cursor.moveToNext());
3140 }
3141 } finally {
3142 if (cursor != null) {
3143 cursor.close();
3144 }
3145 }
3146 Account[] accountArray = new Account[accountList.size()];
3147 accountList.toArray(accountArray);
3148 return accountArray;
3149 }
3150
3151 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003152 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003153 public Account[] getAccounts(String type, String opPackageName) {
3154 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003155 }
3156
Amith Yamasani27db4682013-03-30 17:07:47 -07003157 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003158 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003159 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003160 int callingUid = Binder.getCallingUid();
3161 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3162 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3163 + callingUid + " with uid=" + uid);
3164 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003165 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3166 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003167 }
3168
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003169 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003170 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003171 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3172 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003173 int packageUid = -1;
3174 try {
3175 packageUid = AppGlobals.getPackageManager().getPackageUid(
3176 packageName, UserHandle.getCallingUserId());
3177 } catch (RemoteException re) {
3178 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3179 return new Account[0];
3180 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003181 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3182 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003183 }
3184
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003185 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003186 public void getAccountsByFeatures(
3187 IAccountManagerResponse response,
3188 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003189 String[] features,
3190 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003191 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003192 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3193 Log.v(TAG, "getAccounts: accountType " + type
3194 + ", response " + response
3195 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003196 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003197 + ", pid " + Binder.getCallingPid());
3198 }
Fred Quintana382601f2010-03-25 12:25:10 -07003199 if (response == null) throw new IllegalArgumentException("response is null");
3200 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003201 int userId = UserHandle.getCallingUserId();
3202
Svetoslavf3f02ac2015-09-08 14:36:35 -07003203 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3204 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003205 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003206 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003207 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003208 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3209 try {
3210 response.onResult(result);
3211 } catch (RemoteException e) {
3212 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3213 }
3214 return;
3215 }
Fred Quintana33269202009-04-20 16:05:10 -07003216 long identityToken = clearCallingIdentity();
3217 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003218 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003219 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003220 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003221 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003222 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003223 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003224 Bundle result = new Bundle();
3225 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3226 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003227 return;
3228 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003229 new GetAccountsByTypeAndFeatureSession(
3230 userAccounts,
3231 response,
3232 type,
3233 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003234 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003235 } finally {
3236 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003237 }
3238 }
3239
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003240 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3241 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3242 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3243 try {
3244 if (cursor.moveToNext()) {
3245 return cursor.getLong(0);
3246 }
3247 return -1;
3248 } finally {
3249 cursor.close();
3250 }
3251 }
3252
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003253 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003254 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003255 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003256 try {
3257 if (cursor.moveToNext()) {
3258 return cursor.getLong(0);
3259 }
3260 return -1;
3261 } finally {
3262 cursor.close();
3263 }
3264 }
3265
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003266 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07003267 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
3268 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3269 new String[]{key}, null, null, null);
3270 try {
3271 if (cursor.moveToNext()) {
3272 return cursor.getLong(0);
3273 }
3274 return -1;
3275 } finally {
3276 cursor.close();
3277 }
3278 }
3279
Fred Quintanaa698f422009-04-08 19:14:54 -07003280 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003281 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003282 IAccountManagerResponse mResponse;
3283 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003284 final boolean mExpectActivityLaunch;
3285 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003286 final String mAccountName;
3287 // Indicates if we need to add auth details(like last credential time)
3288 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003289 // If set, we need to update the last authenticated time. This is
3290 // currently
3291 // used on
3292 // successful confirming credentials.
3293 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003294
Fred Quintana33269202009-04-20 16:05:10 -07003295 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003296 private int mNumRequestContinued = 0;
3297 private int mNumErrors = 0;
3298
Fred Quintana60307342009-03-24 22:48:12 -07003299 IAccountAuthenticator mAuthenticator = null;
3300
Fred Quintana8570f742010-02-18 10:32:54 -08003301 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003302 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003303
Amith Yamasani04e0d262012-02-14 11:50:53 -08003304 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003305 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3306 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003307 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3308 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3309 }
3310
3311 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3312 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3313 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003314 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003315 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003316 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003317 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003318 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003319 mResponse = response;
3320 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003321 mExpectActivityLaunch = expectActivityLaunch;
3322 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003323 mAccountName = accountName;
3324 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003325 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003326
Fred Quintanaa698f422009-04-08 19:14:54 -07003327 synchronized (mSessions) {
3328 mSessions.put(toString(), this);
3329 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003330 if (response != null) {
3331 try {
3332 response.asBinder().linkToDeath(this, 0 /* flags */);
3333 } catch (RemoteException e) {
3334 mResponse = null;
3335 binderDied();
3336 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003337 }
Fred Quintana60307342009-03-24 22:48:12 -07003338 }
3339
Fred Quintanaa698f422009-04-08 19:14:54 -07003340 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003341 if (mResponse == null) {
3342 // this session has already been closed
3343 return null;
3344 }
Fred Quintana60307342009-03-24 22:48:12 -07003345 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003346 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003347 return response;
3348 }
3349
Fred Quintanaa698f422009-04-08 19:14:54 -07003350 private void close() {
3351 synchronized (mSessions) {
3352 if (mSessions.remove(toString()) == null) {
3353 // the session was already closed, so bail out now
3354 return;
3355 }
3356 }
3357 if (mResponse != null) {
3358 // stop listening for response deaths
3359 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3360
3361 // clear this so that we don't accidentally send any further results
3362 mResponse = null;
3363 }
3364 cancelTimeout();
3365 unbind();
3366 }
3367
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003368 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003369 public void binderDied() {
3370 mResponse = null;
3371 close();
3372 }
3373
3374 protected String toDebugString() {
3375 return toDebugString(SystemClock.elapsedRealtime());
3376 }
3377
3378 protected String toDebugString(long now) {
3379 return "Session: expectLaunch " + mExpectActivityLaunch
3380 + ", connected " + (mAuthenticator != null)
3381 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3382 + "/" + mNumErrors + ")"
3383 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3384 }
3385
Fred Quintana60307342009-03-24 22:48:12 -07003386 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003387 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3388 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3389 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003390 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003391 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003392 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003393 }
3394 }
3395
3396 private void unbind() {
3397 if (mAuthenticator != null) {
3398 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003399 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003400 }
3401 }
3402
Fred Quintana60307342009-03-24 22:48:12 -07003403 public void cancelTimeout() {
3404 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3405 }
3406
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003407 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003408 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003409 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003410 try {
3411 run();
3412 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003413 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003414 "remote exception");
3415 }
Fred Quintana60307342009-03-24 22:48:12 -07003416 }
3417
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003418 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003419 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003420 mAuthenticator = null;
3421 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003422 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003423 try {
3424 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3425 "disconnected");
3426 } catch (RemoteException e) {
3427 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3428 Log.v(TAG, "Session.onServiceDisconnected: "
3429 + "caught RemoteException while responding", e);
3430 }
3431 }
Fred Quintana60307342009-03-24 22:48:12 -07003432 }
3433 }
3434
Fred Quintanab839afc2009-10-14 15:57:28 -07003435 public abstract void run() throws RemoteException;
3436
Fred Quintana60307342009-03-24 22:48:12 -07003437 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003438 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003439 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003440 try {
3441 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3442 "timeout");
3443 } catch (RemoteException e) {
3444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3445 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3446 e);
3447 }
3448 }
Fred Quintana60307342009-03-24 22:48:12 -07003449 }
3450 }
3451
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003452 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003453 public void onResult(Bundle result) {
3454 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003455 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003456 if (result != null) {
3457 boolean isSuccessfulConfirmCreds = result.getBoolean(
3458 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003459 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003460 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3461 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003462 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003463 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3464 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003465 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003466 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003467 if (needUpdate || mAuthDetailsRequired) {
3468 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3469 if (needUpdate && accountPresent) {
3470 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3471 }
3472 if (mAuthDetailsRequired) {
3473 long lastAuthenticatedTime = -1;
3474 if (accountPresent) {
3475 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3476 mAccounts.openHelper.getReadableDatabase(),
3477 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3478 + " from " +
3479 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3480 + ACCOUNTS_TYPE + "=?",
3481 new String[] {
3482 mAccountName, mAccountType
3483 });
3484 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003485 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003486 lastAuthenticatedTime);
3487 }
3488 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003489 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003490 if (result != null
3491 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
3492 /*
3493 * The Authenticator API allows third party authenticators to
3494 * supply arbitrary intents to other apps that they can run,
3495 * this can be very bad when those apps are in the system like
3496 * the System Settings.
3497 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003498 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07003499 long bid = Binder.clearCallingIdentity();
3500 try {
3501 PackageManager pm = mContext.getPackageManager();
3502 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3503 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
3504 if (PackageManager.SIGNATURE_MATCH !=
3505 pm.checkSignatures(authenticatorUid, targetUid)) {
3506 throw new SecurityException(
3507 "Activity to be started with KEY_INTENT must " +
3508 "share Authenticator's signatures");
3509 }
3510 } finally {
3511 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003512 }
3513 }
3514 if (result != null
3515 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003516 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3517 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003518 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3519 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003520 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3521 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003522 }
Fred Quintana60307342009-03-24 22:48:12 -07003523 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003524 IAccountManagerResponse response;
3525 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003526 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003527 response = mResponse;
3528 } else {
3529 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003530 }
Fred Quintana60307342009-03-24 22:48:12 -07003531 if (response != null) {
3532 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003533 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3535 Log.v(TAG, getClass().getSimpleName()
3536 + " calling onError() on response " + response);
3537 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003538 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003539 "null bundle returned");
3540 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003541 if (mStripAuthTokenFromResult) {
3542 result.remove(AccountManager.KEY_AUTHTOKEN);
3543 }
Fred Quintana56285a62010-12-02 14:20:51 -08003544 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3545 Log.v(TAG, getClass().getSimpleName()
3546 + " calling onResult() on response " + response);
3547 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003548 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3549 (intent == null)) {
3550 // All AccountManager error codes are greater than 0
3551 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3552 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3553 } else {
3554 response.onResult(result);
3555 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003556 }
Fred Quintana60307342009-03-24 22:48:12 -07003557 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003558 // if the caller is dead then there is no one to care about remote exceptions
3559 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3560 Log.v(TAG, "failure while notifying response", e);
3561 }
Fred Quintana60307342009-03-24 22:48:12 -07003562 }
3563 }
3564 }
Fred Quintana60307342009-03-24 22:48:12 -07003565
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003566 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003567 public void onRequestContinued() {
3568 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003569 }
3570
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003571 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003572 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003573 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003574 IAccountManagerResponse response = getResponseAndClose();
3575 if (response != null) {
3576 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003577 Log.v(TAG, getClass().getSimpleName()
3578 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003579 }
3580 try {
3581 response.onError(errorCode, errorMessage);
3582 } catch (RemoteException e) {
3583 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3584 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3585 }
3586 }
3587 } else {
3588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3589 Log.v(TAG, "Session.onError: already closed");
3590 }
Fred Quintana60307342009-03-24 22:48:12 -07003591 }
3592 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003593
3594 /**
3595 * find the component name for the authenticator and initiate a bind
3596 * if no authenticator or the bind fails then return false, otherwise return true
3597 */
3598 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003599 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3600 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3601 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003602 if (authenticatorInfo == null) {
3603 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3604 Log.v(TAG, "there is no authenticator for " + authenticatorType
3605 + ", bailing out");
3606 }
3607 return false;
3608 }
3609
3610 Intent intent = new Intent();
3611 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3612 intent.setComponent(authenticatorInfo.componentName);
3613 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3614 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3615 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003616 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3617 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003618 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3619 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3620 }
3621 return false;
3622 }
3623
3624
3625 return true;
3626 }
Fred Quintana60307342009-03-24 22:48:12 -07003627 }
3628
3629 private class MessageHandler extends Handler {
3630 MessageHandler(Looper looper) {
3631 super(looper);
3632 }
Costin Manolache3348f142009-09-29 18:58:36 -07003633
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003634 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003635 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003636 switch (msg.what) {
3637 case MESSAGE_TIMED_OUT:
3638 Session session = (Session)msg.obj;
3639 session.onTimedOut();
3640 break;
3641
Amith Yamasani5be347b2013-03-31 17:44:31 -07003642 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003643 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003644 break;
3645
Fred Quintana60307342009-03-24 22:48:12 -07003646 default:
3647 throw new IllegalStateException("unhandled message: " + msg.what);
3648 }
3649 }
3650 }
3651
Amith Yamasani04e0d262012-02-14 11:50:53 -08003652 private static String getDatabaseName(int userId) {
3653 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003654 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003655 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003656 // Migrate old file, if it exists, to the new location.
3657 // Make sure the new file doesn't already exist. A dummy file could have been
3658 // accidentally created in the old location, causing the new one to become corrupted
3659 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003660 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003661 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003662 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003663 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003664 if (!userDir.exists()) {
3665 if (!userDir.mkdirs()) {
3666 throw new IllegalStateException("User dir cannot be created: " + userDir);
3667 }
3668 }
3669 if (!oldFile.renameTo(databaseFile)) {
3670 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3671 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003672 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003673 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003674 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003675 }
3676
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003677 private static class DebugDbHelper{
3678 private DebugDbHelper() {
3679 }
3680
3681 private static String TABLE_DEBUG = "debug_table";
3682
3683 // Columns for the table
3684 private static String ACTION_TYPE = "action_type";
3685 private static String TIMESTAMP = "time";
3686 private static String CALLER_UID = "caller_uid";
3687 private static String TABLE_NAME = "table_name";
3688 private static String KEY = "primary_key";
3689
3690 // These actions correspond to the occurrence of real actions. Since
3691 // these are called by the authenticators, the uid associated will be
3692 // of the authenticator.
3693 private static String ACTION_SET_PASSWORD = "action_set_password";
3694 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3695 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3696 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3697 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3698 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3699
3700 // These actions don't necessarily correspond to any action on
3701 // accountDb taking place. As an example, there might be a request for
3702 // addingAccount, which might not lead to addition of account on grounds
3703 // of bad authentication. We will still be logging it to keep track of
3704 // who called.
3705 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3706 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003707
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003708 //This action doesn't add account to accountdb. Account is only
3709 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08003710 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003711 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
3712 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08003713
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003714 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3715
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003716 private static void createDebugTable(SQLiteDatabase db) {
3717 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3718 + ACCOUNTS_ID + " INTEGER,"
3719 + ACTION_TYPE + " TEXT NOT NULL, "
3720 + TIMESTAMP + " DATETIME,"
3721 + CALLER_UID + " INTEGER NOT NULL,"
3722 + TABLE_NAME + " TEXT NOT NULL,"
3723 + KEY + " INTEGER PRIMARY KEY)");
3724 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3725 }
3726 }
3727
3728 private void logRecord(UserAccounts accounts, String action, String tableName) {
3729 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3730 logRecord(db, action, tableName, -1, accounts);
3731 }
3732
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003733 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3734 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3735 logRecord(db, action, tableName, -1, accounts, uid);
3736 }
3737
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003738 /*
3739 * This function receives an opened writable database.
3740 */
3741 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3742 UserAccounts userAccount) {
3743 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3744 }
3745
3746 /*
3747 * This function receives an opened writable database.
3748 */
3749 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3750 UserAccounts userAccount, int callingUid) {
3751 SQLiteStatement logStatement = userAccount.statementForLogging;
3752 logStatement.bindLong(1, accountId);
3753 logStatement.bindString(2, action);
3754 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3755 logStatement.bindLong(4, callingUid);
3756 logStatement.bindString(5, tableName);
3757 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3758 logStatement.execute();
3759 logStatement.clearBindings();
3760 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3761 % MAX_DEBUG_DB_SIZE;
3762 }
3763
3764 /*
3765 * This should only be called once to compile the sql statement for logging
3766 * and to find the insertion point.
3767 */
3768 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3769 UserAccounts userAccount) {
3770 // Initialize the count if not done earlier.
3771 int size = (int) getDebugTableRowCount(db);
3772 if (size >= MAX_DEBUG_DB_SIZE) {
3773 // Table is full, and we need to find the point where to insert.
3774 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3775 } else {
3776 userAccount.debugDbInsertionPoint = size;
3777 }
3778 compileSqlStatementForLogging(db, userAccount);
3779 }
3780
3781 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3782 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3783 + " VALUES (?,?,?,?,?,?)";
3784 userAccount.statementForLogging = db.compileStatement(sql);
3785 }
3786
3787 private long getDebugTableRowCount(SQLiteDatabase db) {
3788 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3789 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3790 }
3791
3792 /*
3793 * Finds the row key where the next insertion should take place. This should
3794 * be invoked only if the table has reached its full capacity.
3795 */
3796 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3797 // This query finds the smallest timestamp value (and if 2 records have
3798 // same timestamp, the choose the lower id).
3799 String queryCountDebugDbRows = new StringBuilder()
3800 .append("SELECT ").append(DebugDbHelper.KEY)
3801 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3802 .append(" ORDER BY ")
3803 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3804 .append(" LIMIT 1")
3805 .toString();
3806 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3807 }
3808
Amith Yamasani04e0d262012-02-14 11:50:53 -08003809 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003810
Amith Yamasani04e0d262012-02-14 11:50:53 -08003811 public DatabaseHelper(Context context, int userId) {
3812 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003813 }
3814
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003815 /**
3816 * This call needs to be made while the mCacheLock is held. The way to
3817 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3818 * @param db The database.
3819 */
Fred Quintana60307342009-03-24 22:48:12 -07003820 @Override
3821 public void onCreate(SQLiteDatabase db) {
3822 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3823 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3824 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3825 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3826 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003827 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003828 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003829 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3830
3831 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3832 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3833 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3834 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3835 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3836 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3837
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003838 createGrantsTable(db);
3839
Fred Quintana60307342009-03-24 22:48:12 -07003840 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3841 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3842 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3843 + EXTRAS_KEY + " TEXT NOT NULL, "
3844 + EXTRAS_VALUE + " TEXT, "
3845 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3846
3847 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3848 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3849 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003850
Amith Yamasani67df64b2012-12-14 12:09:36 -08003851 createSharedAccountsTable(db);
3852
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003853 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003854
3855 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003856 }
3857
Amith Yamasani67df64b2012-12-14 12:09:36 -08003858 private void createSharedAccountsTable(SQLiteDatabase db) {
3859 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3860 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3861 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3862 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3863 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3864 }
3865
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003866 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3867 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3868 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3869 }
3870
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003871 private void addOldAccountNameColumn(SQLiteDatabase db) {
3872 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3873 }
3874
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003875 private void addDebugTable(SQLiteDatabase db) {
3876 DebugDbHelper.createDebugTable(db);
3877 }
3878
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003879 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003880 db.execSQL(""
3881 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3882 + " BEGIN"
3883 + " DELETE FROM " + TABLE_AUTHTOKENS
3884 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3885 + " DELETE FROM " + TABLE_EXTRAS
3886 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003887 + " DELETE FROM " + TABLE_GRANTS
3888 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003889 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003890 }
3891
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003892 private void createGrantsTable(SQLiteDatabase db) {
3893 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3894 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3895 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3896 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3897 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3898 + "," + GRANTS_GRANTEE_UID + "))");
3899 }
3900
Fred Quintana60307342009-03-24 22:48:12 -07003901 @Override
3902 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003903 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003904
Fred Quintanaa698f422009-04-08 19:14:54 -07003905 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003906 // no longer need to do anything since the work is done
3907 // when upgrading from version 2
3908 oldVersion++;
3909 }
3910
3911 if (oldVersion == 2) {
3912 createGrantsTable(db);
3913 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3914 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003915 oldVersion++;
3916 }
Costin Manolache3348f142009-09-29 18:58:36 -07003917
3918 if (oldVersion == 3) {
3919 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3920 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3921 oldVersion++;
3922 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003923
3924 if (oldVersion == 4) {
3925 createSharedAccountsTable(db);
3926 oldVersion++;
3927 }
3928
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003929 if (oldVersion == 5) {
3930 addOldAccountNameColumn(db);
3931 oldVersion++;
3932 }
3933
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003934 if (oldVersion == 6) {
3935 addLastSuccessfullAuthenticatedTimeColumn(db);
3936 oldVersion++;
3937 }
3938
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003939 if (oldVersion == 7) {
3940 addDebugTable(db);
3941 oldVersion++;
3942 }
3943
Amith Yamasani67df64b2012-12-14 12:09:36 -08003944 if (oldVersion != newVersion) {
3945 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3946 }
Fred Quintana60307342009-03-24 22:48:12 -07003947 }
3948
3949 @Override
3950 public void onOpen(SQLiteDatabase db) {
3951 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3952 }
3953 }
3954
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003955 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07003956 return asBinder();
3957 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003958
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003959 /**
3960 * Searches array of arguments for the specified string
3961 * @param args array of argument strings
3962 * @param value value to search for
3963 * @return true if the value is contained in the array
3964 */
3965 private static boolean scanArgs(String[] args, String value) {
3966 if (args != null) {
3967 for (String arg : args) {
3968 if (value.equals(arg)) {
3969 return true;
3970 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003971 }
3972 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003973 return false;
3974 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003975
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003976 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003977 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003978 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3979 != PackageManager.PERMISSION_GRANTED) {
3980 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3981 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3982 + " without permission " + android.Manifest.permission.DUMP);
3983 return;
3984 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003985 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003986 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003987
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003988 final List<UserInfo> users = getUserManager().getUsers();
3989 for (UserInfo user : users) {
3990 ipw.println("User " + user + ":");
3991 ipw.increaseIndent();
3992 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3993 ipw.println();
3994 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003995 }
3996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003997
Amith Yamasani04e0d262012-02-14 11:50:53 -08003998 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3999 String[] args, boolean isCheckinRequest) {
4000 synchronized (userAccounts.cacheLock) {
4001 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004002
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004003 if (isCheckinRequest) {
4004 // This is a checkin request. *Only* upload the account types and the count of each.
4005 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4006 null, null, ACCOUNTS_TYPE, null, null);
4007 try {
4008 while (cursor.moveToNext()) {
4009 // print type,count
4010 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4011 }
4012 } finally {
4013 if (cursor != null) {
4014 cursor.close();
4015 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004016 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004017 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004018 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004019 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004020 fout.println("Accounts: " + accounts.length);
4021 for (Account account : accounts) {
4022 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004023 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004024
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004025 // Add debug information.
4026 fout.println();
4027 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4028 null, null, null, null, DebugDbHelper.TIMESTAMP);
4029 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4030 fout.println("Accounts History");
4031 try {
4032 while (cursor.moveToNext()) {
4033 // print type,count
4034 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4035 cursor.getString(2) + "," + cursor.getString(3) + ","
4036 + cursor.getString(4) + "," + cursor.getString(5));
4037 }
4038 } finally {
4039 cursor.close();
4040 }
4041
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004042 fout.println();
4043 synchronized (mSessions) {
4044 final long now = SystemClock.elapsedRealtime();
4045 fout.println("Active Sessions: " + mSessions.size());
4046 for (Session session : mSessions.values()) {
4047 fout.println(" " + session.toDebugString(now));
4048 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004049 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004050
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004051 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004052 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004053 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004054 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004055 }
4056
Amith Yamasani04e0d262012-02-14 11:50:53 -08004057 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004058 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004059 long identityToken = clearCallingIdentity();
4060 try {
4061 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4062 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4063 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004064
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004065 if (intent.getComponent() != null &&
4066 GrantCredentialsPermissionActivity.class.getName().equals(
4067 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004068 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004069 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004070 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004071 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004072 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004073 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004074 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004075 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004076 Notification n = new Notification.Builder(contextForUser)
4077 .setWhen(0)
4078 .setSmallIcon(android.R.drawable.stat_sys_warning)
4079 .setColor(contextForUser.getColor(
4080 com.android.internal.R.color.system_notification_accent_color))
4081 .setContentTitle(String.format(notificationTitleFormat, account.name))
4082 .setContentText(message)
4083 .setContentIntent(PendingIntent.getActivityAsUser(
4084 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4085 null, user))
4086 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004087 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004088 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004089 } finally {
4090 restoreCallingIdentity(identityToken);
4091 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004092 }
4093
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004094 protected void installNotification(final int notificationId, final Notification n,
4095 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004096 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004097 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004098 }
4099
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004100 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004101 long identityToken = clearCallingIdentity();
4102 try {
4103 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004104 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004105 } finally {
4106 restoreCallingIdentity(identityToken);
4107 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004108 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004109
Svetoslavf3f02ac2015-09-08 14:36:35 -07004110 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
Fred Quintanab38eb142010-02-24 13:40:54 -08004111 for (String perm : permissions) {
4112 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4113 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004114 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08004115 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004116 final int opCode = AppOpsManager.permissionToOpCode(perm);
4117 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4118 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4119 return true;
4120 }
Fred Quintanab38eb142010-02-24 13:40:54 -08004121 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004122 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004123 return false;
4124 }
4125
Amith Yamasani67df64b2012-12-14 12:09:36 -08004126 private int handleIncomingUser(int userId) {
4127 try {
4128 return ActivityManagerNative.getDefault().handleIncomingUser(
4129 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4130 } catch (RemoteException re) {
4131 // Shouldn't happen, local.
4132 }
4133 return userId;
4134 }
4135
Christopher Tateccbf84f2013-05-08 15:25:41 -07004136 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004137 final int callingUserId = UserHandle.getUserId(callingUid);
4138
4139 final PackageManager userPackageManager;
4140 try {
4141 userPackageManager = mContext.createPackageContextAsUser(
4142 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4143 } catch (NameNotFoundException e) {
4144 return false;
4145 }
4146
4147 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004148 for (String name : packages) {
4149 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004150 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004151 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004152 && (packageInfo.applicationInfo.privateFlags
4153 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004154 return true;
4155 }
4156 } catch (PackageManager.NameNotFoundException e) {
4157 return false;
4158 }
4159 }
4160 return false;
4161 }
4162
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004163 private boolean permissionIsGranted(
4164 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004165 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004166 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004167 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004168 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004169 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004170 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4171 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004172 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004173 + ": is authenticator? " + fromAuthenticator
4174 + ", has explicit permission? " + hasExplicitGrants);
4175 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004176 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004177 }
4178
Svetoslavf3f02ac2015-09-08 14:36:35 -07004179 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4180 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004181 if (accountType == null) {
4182 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004183 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004184 return getTypesVisibleToCaller(callingUid, userId,
4185 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004186 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004187 }
4188
4189 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4190 if (accountType == null) {
4191 return false;
4192 } else {
4193 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4194 }
4195 }
4196
Svetoslavf3f02ac2015-09-08 14:36:35 -07004197 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4198 String opPackageName) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004199 boolean isPermitted =
Svetoslavf3f02ac2015-09-08 14:36:35 -07004200 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004201 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004202 return getTypesForCaller(callingUid, userId, isPermitted);
4203 }
4204
4205 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4206 return getTypesForCaller(callingUid, userId, false);
4207 }
4208
4209 private List<String> getTypesForCaller(
4210 int callingUid, int userId, boolean isOtherwisePermitted) {
4211 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004212 long identityToken = Binder.clearCallingIdentity();
4213 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4214 try {
4215 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4216 } finally {
4217 Binder.restoreCallingIdentity(identityToken);
4218 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004219 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004220 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004221 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4222 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4223 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004224 }
4225 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004226 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004227 }
4228
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004229 private boolean isAccountPresentForCaller(String accountName, String accountType) {
4230 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4231 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4232 if (account.name.equals(accountName)) {
4233 return true;
4234 }
4235 }
4236 }
4237 return false;
4238 }
4239
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004240 private static void checkManageUsersPermission(String message) {
4241 if (ActivityManager.checkComponentPermission(
4242 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4243 != PackageManager.PERMISSION_GRANTED) {
4244 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4245 }
4246 }
4247
Amith Yamasani04e0d262012-02-14 11:50:53 -08004248 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4249 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004250 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004251 return true;
4252 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004253 UserAccounts accounts = getUserAccountsForCaller();
4254 synchronized (accounts.cacheLock) {
4255 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4256 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004257 account.name, account.type};
4258 final boolean permissionGranted =
4259 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4260 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4261 // TODO: Skip this check when running automated tests. Replace this
4262 // with a more general solution.
4263 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08004264 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004265 + " but ignoring since device is in test harness.");
4266 return true;
4267 }
4268 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004269 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004270 }
4271
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004272 private boolean isSystemUid(int callingUid) {
4273 String[] packages = null;
4274 long ident = Binder.clearCallingIdentity();
4275 try {
4276 packages = mPackageManager.getPackagesForUid(callingUid);
4277 } finally {
4278 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004279 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004280 if (packages != null) {
4281 for (String name : packages) {
4282 try {
4283 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4284 if (packageInfo != null
4285 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4286 != 0) {
4287 return true;
4288 }
4289 } catch (PackageManager.NameNotFoundException e) {
4290 Log.w(TAG, String.format("Could not find package [%s]", name), e);
4291 }
4292 }
4293 } else {
4294 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004295 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004296 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00004297 }
4298
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004299 /** Succeeds if any of the specified permissions are granted. */
4300 private void checkReadAccountsPermitted(
4301 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004302 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004303 int userId,
4304 String opPackageName) {
4305 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004306 String msg = String.format(
4307 "caller uid %s cannot access %s accounts",
4308 callingUid,
4309 accountType);
4310 Log.w(TAG, " " + msg);
4311 throw new SecurityException(msg);
4312 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004313 }
4314
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004315 private boolean canUserModifyAccounts(int userId) {
4316 if (getUserManager().getUserRestrictions(new UserHandle(userId))
4317 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
4318 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004319 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004320 return true;
4321 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004322
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004323 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004324 DevicePolicyManager dpm = (DevicePolicyManager) mContext
4325 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004326 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02004327 if (typesArray == null) {
4328 return true;
4329 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004330 for (String forbiddenType : typesArray) {
4331 if (forbiddenType.equals(accountType)) {
4332 return false;
4333 }
4334 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004335 return true;
4336 }
4337
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004338 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07004339 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
4340 throws RemoteException {
4341 final int callingUid = getCallingUid();
4342
Amith Yamasani27db4682013-03-30 17:07:47 -07004343 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07004344 throw new SecurityException();
4345 }
4346
4347 if (value) {
4348 grantAppPermission(account, authTokenType, uid);
4349 } else {
4350 revokeAppPermission(account, authTokenType, uid);
4351 }
4352 }
4353
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004354 /**
4355 * Allow callers with the given uid permission to get credentials for account/authTokenType.
4356 * <p>
4357 * Although this is public it can only be accessed via the AccountManagerService object
4358 * which is in the system. This means we don't need to protect it with permissions.
4359 * @hide
4360 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004361 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004362 if (account == null || authTokenType == null) {
4363 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004364 return;
4365 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004366 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004367 synchronized (accounts.cacheLock) {
4368 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004369 db.beginTransaction();
4370 try {
4371 long accountId = getAccountIdLocked(db, account);
4372 if (accountId >= 0) {
4373 ContentValues values = new ContentValues();
4374 values.put(GRANTS_ACCOUNTS_ID, accountId);
4375 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
4376 values.put(GRANTS_GRANTEE_UID, uid);
4377 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
4378 db.setTransactionSuccessful();
4379 }
4380 } finally {
4381 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004382 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004383 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4384 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004385 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004386 }
4387
4388 /**
4389 * Don't allow callers with the given uid permission to get credentials for
4390 * account/authTokenType.
4391 * <p>
4392 * Although this is public it can only be accessed via the AccountManagerService object
4393 * which is in the system. This means we don't need to protect it with permissions.
4394 * @hide
4395 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004396 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004397 if (account == null || authTokenType == null) {
4398 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004399 return;
4400 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004401 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004402 synchronized (accounts.cacheLock) {
4403 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004404 db.beginTransaction();
4405 try {
4406 long accountId = getAccountIdLocked(db, account);
4407 if (accountId >= 0) {
4408 db.delete(TABLE_GRANTS,
4409 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
4410 + GRANTS_GRANTEE_UID + "=?",
4411 new String[]{String.valueOf(accountId), authTokenType,
4412 String.valueOf(uid)});
4413 db.setTransactionSuccessful();
4414 }
4415 } finally {
4416 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004417 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004418 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4419 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004420 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004421 }
Fred Quintana56285a62010-12-02 14:20:51 -08004422
4423 static final private String stringArrayToString(String[] value) {
4424 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4425 }
4426
Amith Yamasani04e0d262012-02-14 11:50:53 -08004427 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4428 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004429 if (oldAccountsForType != null) {
4430 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4431 for (Account curAccount : oldAccountsForType) {
4432 if (!curAccount.equals(account)) {
4433 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004434 }
4435 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004436 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004437 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004438 } else {
4439 Account[] newAccountsForType = new Account[newAccountsList.size()];
4440 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004441 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004442 }
Fred Quintana56285a62010-12-02 14:20:51 -08004443 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004444 accounts.userDataCache.remove(account);
4445 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004446 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004447 }
4448
4449 /**
4450 * This assumes that the caller has already checked that the account is not already present.
4451 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004452 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4453 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004454 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4455 Account[] newAccountsForType = new Account[oldLength + 1];
4456 if (accountsForType != null) {
4457 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004458 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004459 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004460 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004461 }
4462
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004463 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004464 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004465 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004466 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004467 return unfiltered;
4468 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004469 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
4470 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004471 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004472 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004473 // otherwise return non-shared accounts only.
4474 // This might be a temporary way to specify a whitelist
4475 String whiteList = mContext.getResources().getString(
4476 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4477 for (String packageName : packages) {
4478 if (whiteList.contains(";" + packageName + ";")) {
4479 return unfiltered;
4480 }
4481 }
4482 ArrayList<Account> allowed = new ArrayList<Account>();
4483 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4484 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004485 String requiredAccountType = "";
4486 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004487 // If there's an explicit callingPackage specified, check if that package
4488 // opted in to see restricted accounts.
4489 if (callingPackage != null) {
4490 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004491 if (pi != null && pi.restrictedAccountType != null) {
4492 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004493 }
4494 } else {
4495 // Otherwise check if the callingUid has a package that has opted in
4496 for (String packageName : packages) {
4497 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4498 if (pi != null && pi.restrictedAccountType != null) {
4499 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004500 break;
4501 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004502 }
4503 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004504 } catch (NameNotFoundException nnfe) {
4505 }
4506 for (Account account : unfiltered) {
4507 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004508 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004509 } else {
4510 boolean found = false;
4511 for (Account shared : sharedAccounts) {
4512 if (shared.equals(account)) {
4513 found = true;
4514 break;
4515 }
4516 }
4517 if (!found) {
4518 allowed.add(account);
4519 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004520 }
4521 }
4522 Account[] filtered = new Account[allowed.size()];
4523 allowed.toArray(filtered);
4524 return filtered;
4525 } else {
4526 return unfiltered;
4527 }
4528 }
4529
Amith Yamasani27db4682013-03-30 17:07:47 -07004530 /*
4531 * packageName can be null. If not null, it should be used to filter out restricted accounts
4532 * that the package is not allowed to access.
4533 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004534 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004535 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004536 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004537 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004538 if (accounts == null) {
4539 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004540 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004541 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004542 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004543 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004544 } else {
4545 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004546 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004547 totalLength += accounts.length;
4548 }
4549 if (totalLength == 0) {
4550 return EMPTY_ACCOUNT_ARRAY;
4551 }
4552 Account[] accounts = new Account[totalLength];
4553 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004554 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004555 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4556 accountsOfType.length);
4557 totalLength += accountsOfType.length;
4558 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004559 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004560 }
4561 }
4562
Amith Yamasani04e0d262012-02-14 11:50:53 -08004563 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4564 Account account, String key, String value) {
4565 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004566 if (userDataForAccount == null) {
4567 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004568 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004569 }
4570 if (value == null) {
4571 userDataForAccount.remove(key);
4572 } else {
4573 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004574 }
4575 }
4576
Carlos Valdivia91979be2015-05-22 14:11:35 -07004577 protected String readCachedTokenInternal(
4578 UserAccounts accounts,
4579 Account account,
4580 String tokenType,
4581 String callingPackage,
4582 byte[] pkgSigDigest) {
4583 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004584 return accounts.accountTokenCaches.get(
4585 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004586 }
4587 }
4588
Amith Yamasani04e0d262012-02-14 11:50:53 -08004589 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4590 Account account, String key, String value) {
4591 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004592 if (authTokensForAccount == null) {
4593 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004594 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004595 }
4596 if (value == null) {
4597 authTokensForAccount.remove(key);
4598 } else {
4599 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004600 }
4601 }
4602
Amith Yamasani04e0d262012-02-14 11:50:53 -08004603 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4604 String authTokenType) {
4605 synchronized (accounts.cacheLock) {
4606 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004607 if (authTokensForAccount == null) {
4608 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004609 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004610 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004611 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004612 }
4613 return authTokensForAccount.get(authTokenType);
4614 }
4615 }
4616
Amith Yamasani04e0d262012-02-14 11:50:53 -08004617 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4618 synchronized (accounts.cacheLock) {
4619 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004620 if (userDataForAccount == null) {
4621 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004622 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004623 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004624 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004625 }
4626 return userDataForAccount.get(key);
4627 }
4628 }
4629
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004630 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4631 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004632 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004633 Cursor cursor = db.query(TABLE_EXTRAS,
4634 COLUMNS_EXTRAS_KEY_AND_VALUE,
4635 SELECTION_USERDATA_BY_ACCOUNT,
4636 new String[]{account.name, account.type},
4637 null, null, null);
4638 try {
4639 while (cursor.moveToNext()) {
4640 final String tmpkey = cursor.getString(0);
4641 final String value = cursor.getString(1);
4642 userDataForAccount.put(tmpkey, value);
4643 }
4644 } finally {
4645 cursor.close();
4646 }
4647 return userDataForAccount;
4648 }
4649
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004650 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4651 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004652 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004653 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4654 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4655 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4656 new String[]{account.name, account.type},
4657 null, null, null);
4658 try {
4659 while (cursor.moveToNext()) {
4660 final String type = cursor.getString(0);
4661 final String authToken = cursor.getString(1);
4662 authTokensForAccount.put(type, authToken);
4663 }
4664 } finally {
4665 cursor.close();
4666 }
4667 return authTokensForAccount;
4668 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004669
4670 private Context getContextForUser(UserHandle user) {
4671 try {
4672 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4673 } catch (NameNotFoundException e) {
4674 // Default to mContext, not finding the package system is running as is unlikely.
4675 return mContext;
4676 }
4677 }
Sandra Kwan78812282015-11-04 11:19:47 -08004678
4679 private void sendResponse(IAccountManagerResponse response, Bundle result) {
4680 try {
4681 response.onResult(result);
4682 } catch (RemoteException e) {
4683 // if the caller is dead then there is no one to care about remote
4684 // exceptions
4685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4686 Log.v(TAG, "failure while notifying response", e);
4687 }
4688 }
4689 }
4690
4691 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
4692 String errorMessage) {
4693 try {
4694 response.onError(errorCode, errorMessage);
4695 } catch (RemoteException e) {
4696 // if the caller is dead then there is no one to care about remote
4697 // exceptions
4698 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4699 Log.v(TAG, "failure while notifying response", e);
4700 }
4701 }
4702 }
Fred Quintana60307342009-03-24 22:48:12 -07004703}