AccountManagerService.java revision 1bb269d8fe9adbf41312e2203e08da34634ae863
1/*
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
17package com.android.server.accounts;
18
19import android.Manifest;
20import android.accounts.AbstractAccountAuthenticator;
21import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
26import android.accounts.CantAddAccountActivity;
27import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
32import android.annotation.NonNull;
33import android.app.ActivityManager;
34import android.app.ActivityManagerNative;
35import android.app.AppGlobals;
36import android.app.AppOpsManager;
37import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
40import android.app.admin.DeviceAdminInfo;
41import android.app.admin.DevicePolicyManager;
42import android.app.admin.DevicePolicyManagerInternal;
43import android.content.BroadcastReceiver;
44import android.content.ComponentName;
45import android.content.ContentValues;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
49import android.content.ServiceConnection;
50import android.content.pm.ActivityInfo;
51import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageInfo;
53import android.content.pm.PackageManager;
54import android.content.pm.PackageManager.NameNotFoundException;
55import android.content.pm.RegisteredServicesCache;
56import android.content.pm.RegisteredServicesCacheListener;
57import android.content.pm.ResolveInfo;
58import android.content.pm.Signature;
59import android.content.pm.UserInfo;
60import android.database.Cursor;
61import android.database.DatabaseUtils;
62import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteOpenHelper;
64import android.database.sqlite.SQLiteStatement;
65import android.os.Binder;
66import android.os.Bundle;
67import android.os.Environment;
68import android.os.FileUtils;
69import android.os.Handler;
70import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
73import android.os.Parcel;
74import android.os.Process;
75import android.os.RemoteException;
76import android.os.SystemClock;
77import android.os.UserHandle;
78import android.os.UserManager;
79import android.os.storage.StorageManager;
80import android.text.TextUtils;
81import android.util.Log;
82import android.util.Pair;
83import android.util.Slog;
84import android.util.SparseArray;
85import android.util.SparseBooleanArray;
86
87import com.android.internal.R;
88import com.android.internal.util.ArrayUtils;
89import com.android.internal.util.IndentingPrintWriter;
90import com.android.server.FgThread;
91import com.android.server.LocalServices;
92import com.google.android.collect.Lists;
93import com.google.android.collect.Sets;
94
95import java.io.File;
96import java.io.FileDescriptor;
97import java.io.IOException;
98import java.io.PrintWriter;
99import java.security.GeneralSecurityException;
100import java.security.MessageDigest;
101import java.security.NoSuchAlgorithmException;
102import java.text.SimpleDateFormat;
103import java.util.ArrayList;
104import java.util.Arrays;
105import java.util.Collection;
106import java.util.Date;
107import java.util.HashMap;
108import java.util.HashSet;
109import java.util.Iterator;
110import java.util.LinkedHashMap;
111import java.util.List;
112import java.util.Map;
113import java.util.Map.Entry;
114import java.util.concurrent.atomic.AtomicInteger;
115import java.util.concurrent.atomic.AtomicReference;
116
117/**
118 * A system service that provides  account, password, and authtoken management for all
119 * accounts on the device. Some of these calls are implemented with the help of the corresponding
120 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
121 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
122 *    AccountManager accountManager = AccountManager.get(context);
123 * @hide
124 */
125public class AccountManagerService
126        extends IAccountManager.Stub
127        implements RegisteredServicesCacheListener<AuthenticatorDescription> {
128
129    private static final String TAG = "AccountManagerService";
130
131    private static final String DATABASE_NAME = "accounts.db";
132    private static final int PRE_N_DATABASE_VERSION = 9;
133    private static final int CE_DATABASE_VERSION = 10;
134    private static final int DE_DATABASE_VERSION = 1;
135
136    private static final int MAX_DEBUG_DB_SIZE = 64;
137
138    private final Context mContext;
139
140    private final PackageManager mPackageManager;
141    private final AppOpsManager mAppOpsManager;
142    private UserManager mUserManager;
143
144    private final MessageHandler mMessageHandler;
145
146    // Messages that can be sent on mHandler
147    private static final int MESSAGE_TIMED_OUT = 3;
148    private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
149
150    private final IAccountAuthenticatorCache mAuthenticatorCache;
151
152    private static final String TABLE_ACCOUNTS = "accounts";
153    private static final String ACCOUNTS_ID = "_id";
154    private static final String ACCOUNTS_NAME = "name";
155    private static final String ACCOUNTS_TYPE = "type";
156    private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
157    private static final String ACCOUNTS_PASSWORD = "password";
158    private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
159    private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
160            "last_password_entry_time_millis_epoch";
161
162    private static final String TABLE_AUTHTOKENS = "authtokens";
163    private static final String AUTHTOKENS_ID = "_id";
164    private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
165    private static final String AUTHTOKENS_TYPE = "type";
166    private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
167
168    private static final String TABLE_GRANTS = "grants";
169    private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
170    private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
171    private static final String GRANTS_GRANTEE_UID = "uid";
172
173    private static final String TABLE_EXTRAS = "extras";
174    private static final String EXTRAS_ID = "_id";
175    private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
176    private static final String EXTRAS_KEY = "key";
177    private static final String EXTRAS_VALUE = "value";
178
179    private static final String TABLE_META = "meta";
180    private static final String META_KEY = "key";
181    private static final String META_VALUE = "value";
182
183    private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
184    private static final String SHARED_ACCOUNTS_ID = "_id";
185
186    private static final String PRE_N_DATABASE_NAME = "accounts.db";
187    private static final String CE_DATABASE_NAME = "accounts_ce.db";
188    private static final String DE_DATABASE_NAME = "accounts_de.db";
189    private static final String CE_DB_PREFIX = "ceDb.";
190    private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
191    private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
192    private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
193
194    private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
195            new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
196    private static final Intent ACCOUNTS_CHANGED_INTENT;
197
198    static {
199        ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
200        ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
201    }
202
203    private static final String COUNT_OF_MATCHING_GRANTS = ""
204            + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
205            + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
206            + " AND " + GRANTS_GRANTEE_UID + "=?"
207            + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
208            + " AND " + ACCOUNTS_NAME + "=?"
209            + " AND " + ACCOUNTS_TYPE + "=?";
210
211    private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
212            AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
213
214    private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
215            AUTHTOKENS_AUTHTOKEN};
216
217    private static final String SELECTION_USERDATA_BY_ACCOUNT =
218            EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
219    private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
220
221    private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
222            "auth_uid_for_type:";
223    private static final String META_KEY_DELIMITER = ":";
224    private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
225
226    private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
227    private final AtomicInteger mNotificationIds = new AtomicInteger(1);
228
229    static class UserAccounts {
230        private final int userId;
231        private final DeDatabaseHelper openHelper;
232        private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
233                credentialsPermissionNotificationIds =
234                new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
235        private final HashMap<Account, Integer> signinRequiredNotificationIds =
236                new HashMap<Account, Integer>();
237        private final Object cacheLock = new Object();
238        /** protected by the {@link #cacheLock} */
239        private final HashMap<String, Account[]> accountCache =
240                new LinkedHashMap<String, Account[]>();
241        /** protected by the {@link #cacheLock} */
242        private final HashMap<Account, HashMap<String, String>> userDataCache =
243                new HashMap<Account, HashMap<String, String>>();
244        /** protected by the {@link #cacheLock} */
245        private final HashMap<Account, HashMap<String, String>> authTokenCache =
246                new HashMap<Account, HashMap<String, String>>();
247
248        /** protected by the {@link #cacheLock} */
249        private final TokenCache accountTokenCaches = new TokenCache();
250
251        /**
252         * protected by the {@link #cacheLock}
253         *
254         * Caches the previous names associated with an account. Previous names
255         * should be cached because we expect that when an Account is renamed,
256         * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
257         * want to know if the accounts they care about have been renamed.
258         *
259         * The previous names are wrapped in an {@link AtomicReference} so that
260         * we can distinguish between those accounts with no previous names and
261         * those whose previous names haven't been cached (yet).
262         */
263        private final HashMap<Account, AtomicReference<String>> previousNameCache =
264                new HashMap<Account, AtomicReference<String>>();
265
266        private int debugDbInsertionPoint = -1;
267        private SQLiteStatement statementForLogging;
268
269        UserAccounts(Context context, int userId) {
270            this.userId = userId;
271            synchronized (cacheLock) {
272                openHelper = DeDatabaseHelper.create(context, userId);
273            }
274        }
275    }
276
277    private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
278    private final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
279
280    private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
281    private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
282
283    /**
284     * This should only be called by system code. One should only call this after the service
285     * has started.
286     * @return a reference to the AccountManagerService instance
287     * @hide
288     */
289    public static AccountManagerService getSingleton() {
290        return sThis.get();
291    }
292
293    public AccountManagerService(Context context) {
294        this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
295    }
296
297    public AccountManagerService(Context context, PackageManager packageManager,
298            IAccountAuthenticatorCache authenticatorCache) {
299        mContext = context;
300        mPackageManager = packageManager;
301        mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
302
303        mMessageHandler = new MessageHandler(FgThread.get().getLooper());
304
305        mAuthenticatorCache = authenticatorCache;
306        mAuthenticatorCache.setListener(this, null /* Handler */);
307
308        sThis.set(this);
309
310        IntentFilter intentFilter = new IntentFilter();
311        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
312        intentFilter.addDataScheme("package");
313        mContext.registerReceiver(new BroadcastReceiver() {
314            @Override
315            public void onReceive(Context context1, Intent intent) {
316                // Don't delete accounts when updating a authenticator's
317                // package.
318                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
319                    /* Purging data requires file io, don't block the main thread. This is probably
320                     * less than ideal because we are introducing a race condition where old grants
321                     * could be exercised until they are purged. But that race condition existed
322                     * anyway with the broadcast receiver.
323                     *
324                     * Ideally, we would completely clear the cache, purge data from the database,
325                     * and then rebuild the cache. All under the cache lock. But that change is too
326                     * large at this point.
327                     */
328                    Runnable r = new Runnable() {
329                        @Override
330                        public void run() {
331                            purgeOldGrantsAll();
332                        }
333                    };
334                    new Thread(r).start();
335                }
336            }
337        }, intentFilter);
338
339        IntentFilter userFilter = new IntentFilter();
340        userFilter.addAction(Intent.ACTION_USER_REMOVED);
341        userFilter.addAction(Intent.ACTION_USER_UNLOCKED);
342        mContext.registerReceiverAsUser(new BroadcastReceiver() {
343            @Override
344            public void onReceive(Context context, Intent intent) {
345                String action = intent.getAction();
346                if (Intent.ACTION_USER_REMOVED.equals(action)) {
347                    onUserRemoved(intent);
348                } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
349                    onUserUnlocked(intent);
350                }
351            }
352        }, UserHandle.ALL, userFilter, null, null);
353    }
354
355    @Override
356    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
357            throws RemoteException {
358        try {
359            return super.onTransact(code, data, reply, flags);
360        } catch (RuntimeException e) {
361            // The account manager only throws security exceptions, so let's
362            // log all others.
363            if (!(e instanceof SecurityException)) {
364                Slog.wtf(TAG, "Account Manager Crash", e);
365            }
366            throw e;
367        }
368    }
369
370    public void systemReady() {
371    }
372
373    private UserManager getUserManager() {
374        if (mUserManager == null) {
375            mUserManager = UserManager.get(mContext);
376        }
377        return mUserManager;
378    }
379
380    /**
381     * Validate internal set of accounts against installed authenticators for
382     * given user. Clears cached authenticators before validating.
383     */
384    public void validateAccounts(int userId) {
385        final UserAccounts accounts = getUserAccounts(userId);
386
387        // Invalidate user-specific cache to make sure we catch any
388        // removed authenticators.
389        validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
390    }
391
392    /**
393     * Validate internal set of accounts against installed authenticators for
394     * given user. Clear cached authenticators before validating when requested.
395     */
396    private void validateAccountsInternal(
397            UserAccounts accounts, boolean invalidateAuthenticatorCache) {
398        if (Log.isLoggable(TAG, Log.DEBUG)) {
399            Log.d(TAG, "validateAccountsInternal " + accounts.userId
400                    + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
401                    + " userLocked=" + mUnlockedUsers.get(accounts.userId));
402        }
403        if (invalidateAuthenticatorCache) {
404            mAuthenticatorCache.invalidateCache(accounts.userId);
405        }
406
407        final HashMap<String, Integer> knownAuth = new HashMap<>();
408        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
409                mAuthenticatorCache.getAllServices(accounts.userId)) {
410            knownAuth.put(service.type.type, service.uid);
411        }
412
413        synchronized (accounts.cacheLock) {
414            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
415            boolean accountDeleted = false;
416
417            // Get a list of stored authenticator type and UID
418            Cursor metaCursor = db.query(
419                    TABLE_META,
420                    new String[] {META_KEY, META_VALUE},
421                    SELECTION_META_BY_AUTHENTICATOR_TYPE,
422                    new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
423                    null /* groupBy */,
424                    null /* having */,
425                    META_KEY);
426            // Create a list of authenticator type whose previous uid no longer exists
427            HashSet<String> obsoleteAuthType = Sets.newHashSet();
428            try {
429                while (metaCursor.moveToNext()) {
430                    String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
431                    String uid = metaCursor.getString(1);
432                    if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
433                        // Should never happen.
434                        Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
435                                + ", uid empty: " + TextUtils.isEmpty(uid));
436                        continue;
437                    }
438                    Integer knownUid = knownAuth.get(type);
439                    if (knownUid != null && uid.equals(knownUid.toString())) {
440                        // Remove it from the knownAuth list if it's unchanged.
441                        knownAuth.remove(type);
442                    } else {
443                        // Only add it to the list if it no longer exists or uid different
444                        obsoleteAuthType.add(type);
445                        // And delete it from the TABLE_META
446                        db.delete(
447                                TABLE_META,
448                                META_KEY + "=? AND " + META_VALUE + "=?",
449                                new String[] {
450                                        META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
451                                        uid}
452                                );
453                    }
454                }
455            } finally {
456                metaCursor.close();
457            }
458
459            // Add the newly registered authenticator to TABLE_META
460            Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
461            while (iterator.hasNext()) {
462                Entry<String, Integer> entry = iterator.next();
463                ContentValues values = new ContentValues();
464                values.put(META_KEY,
465                        META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
466                values.put(META_VALUE, entry.getValue());
467                db.insert(TABLE_META, null, values);
468            }
469
470            Cursor cursor = db.query(TABLE_ACCOUNTS,
471                    new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
472                    null, null, null, null, ACCOUNTS_ID);
473            try {
474                accounts.accountCache.clear();
475                final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
476                while (cursor.moveToNext()) {
477                    final long accountId = cursor.getLong(0);
478                    final String accountType = cursor.getString(1);
479                    final String accountName = cursor.getString(2);
480
481                    if (obsoleteAuthType.contains(accountType)) {
482                        Slog.w(TAG, "deleting account " + accountName + " because type "
483                                + accountType + "'s registered authenticator no longer exist.");
484                        db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
485                        accountDeleted = true;
486
487                        logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
488                                accountId, accounts);
489
490                        final Account account = new Account(accountName, accountType);
491                        accounts.userDataCache.remove(account);
492                        accounts.authTokenCache.remove(account);
493                        accounts.accountTokenCaches.remove(account);
494                    } else {
495                        ArrayList<String> accountNames = accountNamesByType.get(accountType);
496                        if (accountNames == null) {
497                            accountNames = new ArrayList<String>();
498                            accountNamesByType.put(accountType, accountNames);
499                        }
500                        accountNames.add(accountName);
501                    }
502                }
503                for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
504                    final String accountType = cur.getKey();
505                    final ArrayList<String> accountNames = cur.getValue();
506                    final Account[] accountsForType = new Account[accountNames.size()];
507                    for (int i = 0; i < accountsForType.length; i++) {
508                        accountsForType[i] = new Account(accountNames.get(i), accountType);
509                    }
510                    accounts.accountCache.put(accountType, accountsForType);
511                }
512            } finally {
513                cursor.close();
514                if (accountDeleted) {
515                    sendAccountsChangedBroadcast(accounts.userId);
516                }
517            }
518        }
519    }
520
521    private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
522            Context context,
523            int userId) {
524        AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
525        HashMap<String, Integer> knownAuth = new HashMap<>();
526        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
527                .getAllServices(userId)) {
528            knownAuth.put(service.type.type, service.uid);
529        }
530        return knownAuth;
531    }
532
533    private UserAccounts getUserAccountsForCaller() {
534        return getUserAccounts(UserHandle.getCallingUserId());
535    }
536
537    protected UserAccounts getUserAccounts(int userId) {
538        synchronized (mUsers) {
539            UserAccounts accounts = mUsers.get(userId);
540            boolean validateAccounts = false;
541            if (accounts == null) {
542                accounts = new UserAccounts(mContext, userId);
543                initializeDebugDbSizeAndCompileSqlStatementForLogging(
544                        accounts.openHelper.getWritableDatabase(), accounts);
545                mUsers.append(userId, accounts);
546                purgeOldGrants(accounts);
547                validateAccounts = true;
548            }
549            // open CE database if necessary
550            if (!accounts.openHelper.isCeDatabaseAttached() && mUnlockedUsers.get(userId)) {
551                Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
552                synchronized (accounts.cacheLock) {
553                    CeDatabaseHelper.create(mContext, userId);
554                    accounts.openHelper.attachCeDatabase();
555                }
556                // TODO Synchronize accounts by removing CE account not available in DE
557            }
558            if (validateAccounts) {
559                validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
560            }
561            return accounts;
562        }
563    }
564
565    private void purgeOldGrantsAll() {
566        synchronized (mUsers) {
567            for (int i = 0; i < mUsers.size(); i++) {
568                purgeOldGrants(mUsers.valueAt(i));
569            }
570        }
571    }
572
573    private void purgeOldGrants(UserAccounts accounts) {
574        synchronized (accounts.cacheLock) {
575            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
576            final Cursor cursor = db.query(TABLE_GRANTS,
577                    new String[]{GRANTS_GRANTEE_UID},
578                    null, null, GRANTS_GRANTEE_UID, null, null);
579            try {
580                while (cursor.moveToNext()) {
581                    final int uid = cursor.getInt(0);
582                    final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
583                    if (packageExists) {
584                        continue;
585                    }
586                    Log.d(TAG, "deleting grants for UID " + uid
587                            + " because its package is no longer installed");
588                    db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
589                            new String[]{Integer.toString(uid)});
590                }
591            } finally {
592                cursor.close();
593            }
594        }
595    }
596
597    private void onUserRemoved(Intent intent) {
598        int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
599        if (userId < 1) return;
600
601        UserAccounts accounts;
602        boolean userUnlocked;
603        synchronized (mUsers) {
604            accounts = mUsers.get(userId);
605            mUsers.remove(userId);
606            userUnlocked = mUnlockedUsers.get(userId);
607            mUnlockedUsers.delete(userId);
608        }
609        if (accounts != null) {
610            synchronized (accounts.cacheLock) {
611                accounts.openHelper.close();
612            }
613        }
614        Log.i(TAG, "Removing database files for user " + userId);
615        File dbFile = new File(getDeDatabaseName(userId));
616
617        deleteDbFileWarnIfFailed(dbFile);
618        // Remove CE file if user is unlocked, or FBE is not enabled
619        boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
620        if (!fbeEnabled || userUnlocked) {
621            File ceDb = new File(getCeDatabaseName(userId));
622            if (ceDb.exists()) {
623                deleteDbFileWarnIfFailed(ceDb);
624            }
625        }
626    }
627
628    private static void deleteDbFileWarnIfFailed(File dbFile) {
629        if (!SQLiteDatabase.deleteDatabase(dbFile)) {
630            Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
631        }
632    }
633
634    private void onUserUnlocked(Intent intent) {
635        int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
636        if (Log.isLoggable(TAG, Log.VERBOSE)) {
637            Log.v(TAG, "onUserUnlocked " + userId);
638        }
639        synchronized (mUsers) {
640            mUnlockedUsers.put(userId, true);
641        }
642        if (userId < 1) return;
643        syncSharedAccounts(userId);
644    }
645
646    private void syncSharedAccounts(int userId) {
647        // Check if there's a shared account that needs to be created as an account
648        Account[] sharedAccounts = getSharedAccountsAsUser(userId);
649        if (sharedAccounts == null || sharedAccounts.length == 0) return;
650        Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
651        int parentUserId = UserManager.isSplitSystemUser()
652                ? getUserManager().getUserInfo(userId).restrictedProfileParentId
653                : UserHandle.USER_SYSTEM;
654        if (parentUserId < 0) {
655            Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
656            return;
657        }
658        for (Account sa : sharedAccounts) {
659            if (ArrayUtils.contains(accounts, sa)) continue;
660            // Account doesn't exist. Copy it now.
661            copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
662        }
663    }
664
665    @Override
666    public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
667        validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
668    }
669
670    @Override
671    public String getPassword(Account account) {
672        int callingUid = Binder.getCallingUid();
673        if (Log.isLoggable(TAG, Log.VERBOSE)) {
674            Log.v(TAG, "getPassword: " + account
675                    + ", caller's uid " + Binder.getCallingUid()
676                    + ", pid " + Binder.getCallingPid());
677        }
678        if (account == null) throw new IllegalArgumentException("account is null");
679        int userId = UserHandle.getCallingUserId();
680        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
681            String msg = String.format(
682                    "uid %s cannot get secrets for accounts of type: %s",
683                    callingUid,
684                    account.type);
685            throw new SecurityException(msg);
686        }
687        long identityToken = clearCallingIdentity();
688        try {
689            UserAccounts accounts = getUserAccounts(userId);
690            return readPasswordInternal(accounts, account);
691        } finally {
692            restoreCallingIdentity(identityToken);
693        }
694    }
695
696    private String readPasswordInternal(UserAccounts accounts, Account account) {
697        if (account == null) {
698            return null;
699        }
700        if (!isUserUnlocked(accounts.userId)) {
701            Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
702            return null;
703        }
704
705        synchronized (accounts.cacheLock) {
706            final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
707            return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
708                    account.type);
709        }
710    }
711
712    @Override
713    public String getPreviousName(Account account) {
714        if (Log.isLoggable(TAG, Log.VERBOSE)) {
715            Log.v(TAG, "getPreviousName: " + account
716                    + ", caller's uid " + Binder.getCallingUid()
717                    + ", pid " + Binder.getCallingPid());
718        }
719        if (account == null) throw new IllegalArgumentException("account is null");
720        int userId = UserHandle.getCallingUserId();
721        long identityToken = clearCallingIdentity();
722        try {
723            UserAccounts accounts = getUserAccounts(userId);
724            return readPreviousNameInternal(accounts, account);
725        } finally {
726            restoreCallingIdentity(identityToken);
727        }
728    }
729
730    private String readPreviousNameInternal(UserAccounts accounts, Account account) {
731        if  (account == null) {
732            return null;
733        }
734        synchronized (accounts.cacheLock) {
735            AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
736            if (previousNameRef == null) {
737                final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
738                Cursor cursor = db.query(
739                        TABLE_ACCOUNTS,
740                        new String[]{ ACCOUNTS_PREVIOUS_NAME },
741                        ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
742                        new String[] { account.name, account.type },
743                        null,
744                        null,
745                        null);
746                try {
747                    if (cursor.moveToNext()) {
748                        String previousName = cursor.getString(0);
749                        previousNameRef = new AtomicReference<>(previousName);
750                        accounts.previousNameCache.put(account, previousNameRef);
751                        return previousName;
752                    } else {
753                        return null;
754                    }
755                } finally {
756                    cursor.close();
757                }
758            } else {
759                return previousNameRef.get();
760            }
761        }
762    }
763
764    @Override
765    public String getUserData(Account account, String key) {
766        final int callingUid = Binder.getCallingUid();
767        if (Log.isLoggable(TAG, Log.VERBOSE)) {
768            String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
769                    account, key, callingUid, Binder.getCallingPid());
770            Log.v(TAG, msg);
771        }
772        if (account == null) throw new IllegalArgumentException("account is null");
773        if (key == null) throw new IllegalArgumentException("key is null");
774        int userId = UserHandle.getCallingUserId();
775        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
776            String msg = String.format(
777                    "uid %s cannot get user data for accounts of type: %s",
778                    callingUid,
779                    account.type);
780            throw new SecurityException(msg);
781        }
782        long identityToken = clearCallingIdentity();
783        try {
784            UserAccounts accounts = getUserAccounts(userId);
785            synchronized (accounts.cacheLock) {
786                if (!accountExistsCacheLocked(accounts, account)) {
787                    return null;
788                }
789                return readUserDataInternalLocked(accounts, account, key);
790            }
791        } finally {
792            restoreCallingIdentity(identityToken);
793        }
794    }
795
796    @Override
797    public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
798        int callingUid = Binder.getCallingUid();
799        if (Log.isLoggable(TAG, Log.VERBOSE)) {
800            Log.v(TAG, "getAuthenticatorTypes: "
801                    + "for user id " + userId
802                    + "caller's uid " + callingUid
803                    + ", pid " + Binder.getCallingPid());
804        }
805        // Only allow the system process to read accounts of other users
806        if (isCrossUser(callingUid, userId)) {
807            throw new SecurityException(
808                    String.format(
809                            "User %s tying to get authenticator types for %s" ,
810                            UserHandle.getCallingUserId(),
811                            userId));
812        }
813
814        final long identityToken = clearCallingIdentity();
815        try {
816            return getAuthenticatorTypesInternal(userId);
817
818        } finally {
819            restoreCallingIdentity(identityToken);
820        }
821    }
822
823    /**
824     * Should only be called inside of a clearCallingIdentity block.
825     */
826    private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
827        Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
828                authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
829        AuthenticatorDescription[] types =
830                new AuthenticatorDescription[authenticatorCollection.size()];
831        int i = 0;
832        for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
833                : authenticatorCollection) {
834            types[i] = authenticator.type;
835            i++;
836        }
837        return types;
838    }
839
840
841
842    private boolean isCrossUser(int callingUid, int userId) {
843        return (userId != UserHandle.getCallingUserId()
844                && callingUid != Process.myUid()
845                && mContext.checkCallingOrSelfPermission(
846                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
847                                != PackageManager.PERMISSION_GRANTED);
848    }
849
850    @Override
851    public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
852        Bundle.setDefusable(extras, true);
853        final int callingUid = Binder.getCallingUid();
854        if (Log.isLoggable(TAG, Log.VERBOSE)) {
855            Log.v(TAG, "addAccountExplicitly: " + account
856                    + ", caller's uid " + callingUid
857                    + ", pid " + Binder.getCallingPid());
858        }
859        if (account == null) throw new IllegalArgumentException("account is null");
860        int userId = UserHandle.getCallingUserId();
861        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
862            String msg = String.format(
863                    "uid %s cannot explicitly add accounts of type: %s",
864                    callingUid,
865                    account.type);
866            throw new SecurityException(msg);
867        }
868        /*
869         * Child users are not allowed to add accounts. Only the accounts that are
870         * shared by the parent profile can be added to child profile.
871         *
872         * TODO: Only allow accounts that were shared to be added by
873         *     a limited user.
874         */
875
876        // fails if the account already exists
877        long identityToken = clearCallingIdentity();
878        try {
879            UserAccounts accounts = getUserAccounts(userId);
880            return addAccountInternal(accounts, account, password, extras, callingUid);
881        } finally {
882            restoreCallingIdentity(identityToken);
883        }
884    }
885
886    @Override
887    public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
888            final int userFrom, int userTo) {
889        int callingUid = Binder.getCallingUid();
890        if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
891            throw new SecurityException("Calling copyAccountToUser requires "
892                    + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
893        }
894        final UserAccounts fromAccounts = getUserAccounts(userFrom);
895        final UserAccounts toAccounts = getUserAccounts(userTo);
896        if (fromAccounts == null || toAccounts == null) {
897            if (response != null) {
898                Bundle result = new Bundle();
899                result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
900                try {
901                    response.onResult(result);
902                } catch (RemoteException e) {
903                    Slog.w(TAG, "Failed to report error back to the client." + e);
904                }
905            }
906            return;
907        }
908
909        Slog.d(TAG, "Copying account " + account.name
910                + " from user " + userFrom + " to user " + userTo);
911        long identityToken = clearCallingIdentity();
912        try {
913            new Session(fromAccounts, response, account.type, false,
914                    false /* stripAuthTokenFromResult */, account.name,
915                    false /* authDetailsRequired */) {
916                @Override
917                protected String toDebugString(long now) {
918                    return super.toDebugString(now) + ", getAccountCredentialsForClone"
919                            + ", " + account.type;
920                }
921
922                @Override
923                public void run() throws RemoteException {
924                    mAuthenticator.getAccountCredentialsForCloning(this, account);
925                }
926
927                @Override
928                public void onResult(Bundle result) {
929                    Bundle.setDefusable(result, true);
930                    if (result != null
931                            && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
932                        // Create a Session for the target user and pass in the bundle
933                        completeCloningAccount(response, result, account, toAccounts, userFrom);
934                    } else {
935                        super.onResult(result);
936                    }
937                }
938            }.bind();
939        } finally {
940            restoreCallingIdentity(identityToken);
941        }
942    }
943
944    @Override
945    public boolean accountAuthenticated(final Account account) {
946        final int callingUid = Binder.getCallingUid();
947        if (Log.isLoggable(TAG, Log.VERBOSE)) {
948            String msg = String.format(
949                    "accountAuthenticated( account: %s, callerUid: %s)",
950                    account,
951                    callingUid);
952            Log.v(TAG, msg);
953        }
954        if (account == null) {
955            throw new IllegalArgumentException("account is null");
956        }
957        int userId = UserHandle.getCallingUserId();
958        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
959            String msg = String.format(
960                    "uid %s cannot notify authentication for accounts of type: %s",
961                    callingUid,
962                    account.type);
963            throw new SecurityException(msg);
964        }
965
966        if (!canUserModifyAccounts(userId, callingUid) ||
967                !canUserModifyAccountsForType(userId, account.type, callingUid)) {
968            return false;
969        }
970
971        long identityToken = clearCallingIdentity();
972        try {
973            UserAccounts accounts = getUserAccounts(userId);
974            return updateLastAuthenticatedTime(account);
975        } finally {
976            restoreCallingIdentity(identityToken);
977        }
978    }
979
980    private boolean updateLastAuthenticatedTime(Account account) {
981        final UserAccounts accounts = getUserAccountsForCaller();
982        synchronized (accounts.cacheLock) {
983            final ContentValues values = new ContentValues();
984            values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
985            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
986            int i = db.update(
987                    TABLE_ACCOUNTS,
988                    values,
989                    ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
990                    new String[] {
991                            account.name, account.type
992                    });
993            if (i > 0) {
994                return true;
995            }
996        }
997        return false;
998    }
999
1000    private void completeCloningAccount(IAccountManagerResponse response,
1001            final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1002            final int parentUserId){
1003        Bundle.setDefusable(accountCredentials, true);
1004        long id = clearCallingIdentity();
1005        try {
1006            new Session(targetUser, response, account.type, false,
1007                    false /* stripAuthTokenFromResult */, account.name,
1008                    false /* authDetailsRequired */) {
1009                @Override
1010                protected String toDebugString(long now) {
1011                    return super.toDebugString(now) + ", getAccountCredentialsForClone"
1012                            + ", " + account.type;
1013                }
1014
1015                @Override
1016                public void run() throws RemoteException {
1017                    // Confirm that the owner's account still exists before this step.
1018                    UserAccounts owner = getUserAccounts(parentUserId);
1019                    synchronized (owner.cacheLock) {
1020                        for (Account acc : getAccounts(parentUserId,
1021                                mContext.getOpPackageName())) {
1022                            if (acc.equals(account)) {
1023                                mAuthenticator.addAccountFromCredentials(
1024                                        this, account, accountCredentials);
1025                                break;
1026                            }
1027                        }
1028                    }
1029                }
1030
1031                @Override
1032                public void onResult(Bundle result) {
1033                    Bundle.setDefusable(result, true);
1034                    // TODO: Anything to do if if succedded?
1035                    // TODO: If it failed: Show error notification? Should we remove the shadow
1036                    // account to avoid retries?
1037                    super.onResult(result);
1038                }
1039
1040                @Override
1041                public void onError(int errorCode, String errorMessage) {
1042                    super.onError(errorCode,  errorMessage);
1043                    // TODO: Show error notification to user
1044                    // TODO: Should we remove the shadow account so that it doesn't keep trying?
1045                }
1046
1047            }.bind();
1048        } finally {
1049            restoreCallingIdentity(id);
1050        }
1051    }
1052
1053    private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
1054            Bundle extras, int callingUid) {
1055        Bundle.setDefusable(extras, true);
1056        if (account == null) {
1057            return false;
1058        }
1059        if (!isUserUnlocked(accounts.userId)) {
1060            Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1061                    + " is locked. callingUid=" + callingUid);
1062            return false;
1063        }
1064        synchronized (accounts.cacheLock) {
1065            final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1066            db.beginTransaction();
1067            try {
1068                long numMatches = DatabaseUtils.longForQuery(db,
1069                        "select count(*) from " + CE_TABLE_ACCOUNTS
1070                                + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1071                        new String[]{account.name, account.type});
1072                if (numMatches > 0) {
1073                    Log.w(TAG, "insertAccountIntoDatabase: " + account
1074                            + ", skipping since the account already exists");
1075                    return false;
1076                }
1077                ContentValues values = new ContentValues();
1078                values.put(ACCOUNTS_NAME, account.name);
1079                values.put(ACCOUNTS_TYPE, account.type);
1080                values.put(ACCOUNTS_PASSWORD, password);
1081                long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
1082                if (accountId < 0) {
1083                    Log.w(TAG, "insertAccountIntoDatabase: " + account
1084                            + ", skipping the DB insert failed");
1085                    return false;
1086                }
1087                // Insert into DE table
1088                values = new ContentValues();
1089                values.put(ACCOUNTS_ID, accountId);
1090                values.put(ACCOUNTS_NAME, account.name);
1091                values.put(ACCOUNTS_TYPE, account.type);
1092                values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1093                        System.currentTimeMillis());
1094                if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1095                    Log.w(TAG, "insertAccountIntoDatabase: " + account
1096                            + ", skipping the DB insert failed");
1097                    return false;
1098                }
1099                if (extras != null) {
1100                    for (String key : extras.keySet()) {
1101                        final String value = extras.getString(key);
1102                        if (insertExtraLocked(db, accountId, key, value) < 0) {
1103                            Log.w(TAG, "insertAccountIntoDatabase: " + account
1104                                    + ", skipping since insertExtra failed for key " + key);
1105                            return false;
1106                        }
1107                    }
1108                }
1109                db.setTransactionSuccessful();
1110
1111                logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1112                        accounts, callingUid);
1113
1114                insertAccountIntoCacheLocked(accounts, account);
1115            } finally {
1116                db.endTransaction();
1117            }
1118            sendAccountsChangedBroadcast(accounts.userId);
1119        }
1120        if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1121            addAccountToLinkedRestrictedUsers(account, accounts.userId);
1122        }
1123        return true;
1124    }
1125
1126    private boolean isUserUnlocked(int userId) {
1127        synchronized (mUsers) {
1128            return mUnlockedUsers.get(userId);
1129        }
1130    }
1131
1132    /**
1133     * Adds the account to all linked restricted users as shared accounts. If the user is currently
1134     * running, then clone the account too.
1135     * @param account the account to share with limited users
1136     *
1137     */
1138    private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
1139        List<UserInfo> users = getUserManager().getUsers();
1140        for (UserInfo user : users) {
1141            if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
1142                addSharedAccountAsUser(account, user.id);
1143                if (getUserManager().isUserUnlocked(user.id)) {
1144                    mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1145                            MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
1146                }
1147            }
1148        }
1149    }
1150
1151    private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
1152        ContentValues values = new ContentValues();
1153        values.put(EXTRAS_KEY, key);
1154        values.put(EXTRAS_ACCOUNTS_ID, accountId);
1155        values.put(EXTRAS_VALUE, value);
1156        return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
1157    }
1158
1159    @Override
1160    public void hasFeatures(IAccountManagerResponse response,
1161            Account account, String[] features, String opPackageName) {
1162        int callingUid = Binder.getCallingUid();
1163        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1164            Log.v(TAG, "hasFeatures: " + account
1165                    + ", response " + response
1166                    + ", features " + stringArrayToString(features)
1167                    + ", caller's uid " + callingUid
1168                    + ", pid " + Binder.getCallingPid());
1169        }
1170        if (response == null) throw new IllegalArgumentException("response is null");
1171        if (account == null) throw new IllegalArgumentException("account is null");
1172        if (features == null) throw new IllegalArgumentException("features is null");
1173        int userId = UserHandle.getCallingUserId();
1174        checkReadAccountsPermitted(callingUid, account.type, userId,
1175                opPackageName);
1176
1177        long identityToken = clearCallingIdentity();
1178        try {
1179            UserAccounts accounts = getUserAccounts(userId);
1180            new TestFeaturesSession(accounts, response, account, features).bind();
1181        } finally {
1182            restoreCallingIdentity(identityToken);
1183        }
1184    }
1185
1186    private class TestFeaturesSession extends Session {
1187        private final String[] mFeatures;
1188        private final Account mAccount;
1189
1190        public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
1191                Account account, String[] features) {
1192            super(accounts, response, account.type, false /* expectActivityLaunch */,
1193                    true /* stripAuthTokenFromResult */, account.name,
1194                    false /* authDetailsRequired */);
1195            mFeatures = features;
1196            mAccount = account;
1197        }
1198
1199        @Override
1200        public void run() throws RemoteException {
1201            try {
1202                mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1203            } catch (RemoteException e) {
1204                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1205            }
1206        }
1207
1208        @Override
1209        public void onResult(Bundle result) {
1210            Bundle.setDefusable(result, true);
1211            IAccountManagerResponse response = getResponseAndClose();
1212            if (response != null) {
1213                try {
1214                    if (result == null) {
1215                        response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
1216                        return;
1217                    }
1218                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
1219                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1220                                + response);
1221                    }
1222                    final Bundle newResult = new Bundle();
1223                    newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1224                            result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1225                    response.onResult(newResult);
1226                } catch (RemoteException e) {
1227                    // if the caller is dead then there is no one to care about remote exceptions
1228                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
1229                        Log.v(TAG, "failure while notifying response", e);
1230                    }
1231                }
1232            }
1233        }
1234
1235        @Override
1236        protected String toDebugString(long now) {
1237            return super.toDebugString(now) + ", hasFeatures"
1238                    + ", " + mAccount
1239                    + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1240        }
1241    }
1242
1243    @Override
1244    public void renameAccount(
1245            IAccountManagerResponse response, Account accountToRename, String newName) {
1246        final int callingUid = Binder.getCallingUid();
1247        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1248            Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
1249                + ", caller's uid " + callingUid
1250                + ", pid " + Binder.getCallingPid());
1251        }
1252        if (accountToRename == null) throw new IllegalArgumentException("account is null");
1253        int userId = UserHandle.getCallingUserId();
1254        if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
1255            String msg = String.format(
1256                    "uid %s cannot rename accounts of type: %s",
1257                    callingUid,
1258                    accountToRename.type);
1259            throw new SecurityException(msg);
1260        }
1261        long identityToken = clearCallingIdentity();
1262        try {
1263            UserAccounts accounts = getUserAccounts(userId);
1264            Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
1265            Bundle result = new Bundle();
1266            result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1267            result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1268            try {
1269                response.onResult(result);
1270            } catch (RemoteException e) {
1271                Log.w(TAG, e.getMessage());
1272            }
1273        } finally {
1274            restoreCallingIdentity(identityToken);
1275        }
1276    }
1277
1278    private Account renameAccountInternal(
1279            UserAccounts accounts, Account accountToRename, String newName) {
1280        Account resultAccount = null;
1281        /*
1282         * Cancel existing notifications. Let authenticators
1283         * re-post notifications as required. But we don't know if
1284         * the authenticators have bound their notifications to
1285         * now stale account name data.
1286         *
1287         * With a rename api, we might not need to do this anymore but it
1288         * shouldn't hurt.
1289         */
1290        cancelNotification(
1291                getSigninRequiredNotificationId(accounts, accountToRename),
1292                 new UserHandle(accounts.userId));
1293        synchronized(accounts.credentialsPermissionNotificationIds) {
1294            for (Pair<Pair<Account, String>, Integer> pair:
1295                    accounts.credentialsPermissionNotificationIds.keySet()) {
1296                if (accountToRename.equals(pair.first.first)) {
1297                    int id = accounts.credentialsPermissionNotificationIds.get(pair);
1298                    cancelNotification(id, new UserHandle(accounts.userId));
1299                }
1300            }
1301        }
1302        synchronized (accounts.cacheLock) {
1303            final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1304            db.beginTransaction();
1305            boolean isSuccessful = false;
1306            Account renamedAccount = new Account(newName, accountToRename.type);
1307            try {
1308                final long accountId = getAccountIdLocked(db, accountToRename);
1309                if (accountId >= 0) {
1310                    final ContentValues values = new ContentValues();
1311                    values.put(ACCOUNTS_NAME, newName);
1312                    final String[] argsAccountId = { String.valueOf(accountId) };
1313                    db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1314                    // Update NAME/PREVIOUS_NAME in DE accounts table
1315                    values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1316                    db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1317                    db.setTransactionSuccessful();
1318                    isSuccessful = true;
1319                    logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1320                            accounts);
1321                }
1322            } finally {
1323                db.endTransaction();
1324                if (isSuccessful) {
1325                    /*
1326                     * Database transaction was successful. Clean up cached
1327                     * data associated with the account in the user profile.
1328                     */
1329                    insertAccountIntoCacheLocked(accounts, renamedAccount);
1330                    /*
1331                     * Extract the data and token caches before removing the
1332                     * old account to preserve the user data associated with
1333                     * the account.
1334                     */
1335                    HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1336                    HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1337                    removeAccountFromCacheLocked(accounts, accountToRename);
1338                    /*
1339                     * Update the cached data associated with the renamed
1340                     * account.
1341                     */
1342                    accounts.userDataCache.put(renamedAccount, tmpData);
1343                    accounts.authTokenCache.put(renamedAccount, tmpTokens);
1344                    accounts.previousNameCache.put(
1345                          renamedAccount,
1346                          new AtomicReference<String>(accountToRename.name));
1347                    resultAccount = renamedAccount;
1348
1349                    int parentUserId = accounts.userId;
1350                    if (canHaveProfile(parentUserId)) {
1351                        /*
1352                         * Owner or system user account was renamed, rename the account for
1353                         * those users with which the account was shared.
1354                         */
1355                        List<UserInfo> users = getUserManager().getUsers(true);
1356                        for (UserInfo user : users) {
1357                            if (user.isRestricted()
1358                                    && (user.restrictedProfileParentId == parentUserId)) {
1359                                renameSharedAccountAsUser(accountToRename, newName, user.id);
1360                            }
1361                        }
1362                    }
1363                    sendAccountsChangedBroadcast(accounts.userId);
1364                }
1365            }
1366        }
1367        return resultAccount;
1368    }
1369
1370    private boolean canHaveProfile(final int parentUserId) {
1371        final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
1372        return userInfo != null && userInfo.canHaveProfile();
1373    }
1374
1375    @Override
1376    public void removeAccount(IAccountManagerResponse response, Account account,
1377            boolean expectActivityLaunch) {
1378        removeAccountAsUser(
1379                response,
1380                account,
1381                expectActivityLaunch,
1382                UserHandle.getCallingUserId());
1383    }
1384
1385    @Override
1386    public void removeAccountAsUser(IAccountManagerResponse response, Account account,
1387            boolean expectActivityLaunch, int userId) {
1388        final int callingUid = Binder.getCallingUid();
1389        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1390            Log.v(TAG, "removeAccount: " + account
1391                    + ", response " + response
1392                    + ", caller's uid " + callingUid
1393                    + ", pid " + Binder.getCallingPid()
1394                    + ", for user id " + userId);
1395        }
1396        if (response == null) throw new IllegalArgumentException("response is null");
1397        if (account == null) throw new IllegalArgumentException("account is null");
1398        // Only allow the system process to modify accounts of other users
1399        if (isCrossUser(callingUid, userId)) {
1400            throw new SecurityException(
1401                    String.format(
1402                            "User %s tying remove account for %s" ,
1403                            UserHandle.getCallingUserId(),
1404                            userId));
1405        }
1406        /*
1407         * Only the system or authenticator should be allowed to remove accounts for that
1408         * authenticator.  This will let users remove accounts (via Settings in the system) but not
1409         * arbitrary applications (like competing authenticators).
1410         */
1411        UserHandle user = UserHandle.of(userId);
1412        if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1413                && !isSystemUid(callingUid)) {
1414            String msg = String.format(
1415                    "uid %s cannot remove accounts of type: %s",
1416                    callingUid,
1417                    account.type);
1418            throw new SecurityException(msg);
1419        }
1420        if (!canUserModifyAccounts(userId, callingUid)) {
1421            try {
1422                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1423                        "User cannot modify accounts");
1424            } catch (RemoteException re) {
1425            }
1426            return;
1427        }
1428        if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
1429            try {
1430                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1431                        "User cannot modify accounts of this type (policy).");
1432            } catch (RemoteException re) {
1433            }
1434            return;
1435        }
1436        long identityToken = clearCallingIdentity();
1437        UserAccounts accounts = getUserAccounts(userId);
1438        cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
1439        synchronized(accounts.credentialsPermissionNotificationIds) {
1440            for (Pair<Pair<Account, String>, Integer> pair:
1441                accounts.credentialsPermissionNotificationIds.keySet()) {
1442                if (account.equals(pair.first.first)) {
1443                    int id = accounts.credentialsPermissionNotificationIds.get(pair);
1444                    cancelNotification(id, user);
1445                }
1446            }
1447        }
1448
1449        logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1450
1451        try {
1452            new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1453        } finally {
1454            restoreCallingIdentity(identityToken);
1455        }
1456    }
1457
1458    @Override
1459    public boolean removeAccountExplicitly(Account account) {
1460        final int callingUid = Binder.getCallingUid();
1461        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1462            Log.v(TAG, "removeAccountExplicitly: " + account
1463                    + ", caller's uid " + callingUid
1464                    + ", pid " + Binder.getCallingPid());
1465        }
1466        int userId = Binder.getCallingUserHandle().getIdentifier();
1467        if (account == null) {
1468            /*
1469             * Null accounts should result in returning false, as per
1470             * AccountManage.addAccountExplicitly(...) java doc.
1471             */
1472            Log.e(TAG, "account is null");
1473            return false;
1474        } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1475            String msg = String.format(
1476                    "uid %s cannot explicitly add accounts of type: %s",
1477                    callingUid,
1478                    account.type);
1479            throw new SecurityException(msg);
1480        }
1481        UserAccounts accounts = getUserAccountsForCaller();
1482        logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1483        long identityToken = clearCallingIdentity();
1484        try {
1485            return removeAccountInternal(accounts, account, callingUid);
1486        } finally {
1487            restoreCallingIdentity(identityToken);
1488        }
1489    }
1490
1491    private class RemoveAccountSession extends Session {
1492        final Account mAccount;
1493        public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
1494                Account account, boolean expectActivityLaunch) {
1495            super(accounts, response, account.type, expectActivityLaunch,
1496                    true /* stripAuthTokenFromResult */, account.name,
1497                    false /* authDetailsRequired */);
1498            mAccount = account;
1499        }
1500
1501        @Override
1502        protected String toDebugString(long now) {
1503            return super.toDebugString(now) + ", removeAccount"
1504                    + ", account " + mAccount;
1505        }
1506
1507        @Override
1508        public void run() throws RemoteException {
1509            mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1510        }
1511
1512        @Override
1513        public void onResult(Bundle result) {
1514            Bundle.setDefusable(result, true);
1515            if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1516                    && !result.containsKey(AccountManager.KEY_INTENT)) {
1517                final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1518                if (removalAllowed) {
1519                    removeAccountInternal(mAccounts, mAccount, getCallingUid());
1520                }
1521                IAccountManagerResponse response = getResponseAndClose();
1522                if (response != null) {
1523                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
1524                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1525                                + response);
1526                    }
1527                    Bundle result2 = new Bundle();
1528                    result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
1529                    try {
1530                        response.onResult(result2);
1531                    } catch (RemoteException e) {
1532                        // ignore
1533                    }
1534                }
1535            }
1536            super.onResult(result);
1537        }
1538    }
1539
1540    /* For testing */
1541    protected void removeAccountInternal(Account account) {
1542        removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
1543    }
1544
1545    private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
1546        // For now user is required to be unlocked. TODO: Handle both cases in the future
1547        int deleted;
1548        synchronized (accounts.cacheLock) {
1549            final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1550            final long accountId = getAccountIdLocked(db, account);
1551            deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1552                    + "=?",
1553                    new String[]{account.name, account.type});
1554            // Delete from CE table
1555            db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1556                    new String[]{account.name, account.type});
1557            removeAccountFromCacheLocked(accounts, account);
1558            sendAccountsChangedBroadcast(accounts.userId);
1559
1560            logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
1561        }
1562        long id = Binder.clearCallingIdentity();
1563        try {
1564            int parentUserId = accounts.userId;
1565            if (canHaveProfile(parentUserId)) {
1566                // Remove from any restricted profiles that are sharing this account.
1567                List<UserInfo> users = getUserManager().getUsers(true);
1568                for (UserInfo user : users) {
1569                    if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
1570                        removeSharedAccountAsUser(account, user.id, callingUid);
1571                    }
1572                }
1573            }
1574        } finally {
1575            Binder.restoreCallingIdentity(id);
1576        }
1577        return (deleted > 0);
1578    }
1579
1580    @Override
1581    public void invalidateAuthToken(String accountType, String authToken) {
1582        int callerUid = Binder.getCallingUid();
1583        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1584            Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1585                    + ", caller's uid " + callerUid
1586                    + ", pid " + Binder.getCallingPid());
1587        }
1588        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1589        if (authToken == null) throw new IllegalArgumentException("authToken is null");
1590        int userId = UserHandle.getCallingUserId();
1591        long identityToken = clearCallingIdentity();
1592        try {
1593            UserAccounts accounts = getUserAccounts(userId);
1594            synchronized (accounts.cacheLock) {
1595                final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1596                db.beginTransaction();
1597                try {
1598                    invalidateAuthTokenLocked(accounts, db, accountType, authToken);
1599                    invalidateCustomTokenLocked(accounts, accountType, authToken);
1600                    db.setTransactionSuccessful();
1601                } finally {
1602                    db.endTransaction();
1603                }
1604            }
1605        } finally {
1606            restoreCallingIdentity(identityToken);
1607        }
1608    }
1609
1610    private void invalidateCustomTokenLocked(
1611            UserAccounts accounts,
1612            String accountType,
1613            String authToken) {
1614        if (authToken == null || accountType == null) {
1615            return;
1616        }
1617        // Also wipe out cached token in memory.
1618        accounts.accountTokenCaches.remove(accountType, authToken);
1619    }
1620
1621    private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1622            String accountType, String authToken) {
1623        if (authToken == null || accountType == null) {
1624            return;
1625        }
1626        Cursor cursor = db.rawQuery(
1627                "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1628                        + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1629                        + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1630                        + " FROM " + CE_TABLE_ACCOUNTS
1631                        + " JOIN " + CE_TABLE_AUTHTOKENS
1632                        + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1633                        + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1634                        + " WHERE " + CE_TABLE_AUTHTOKENS + "."  + AUTHTOKENS_AUTHTOKEN
1635                        + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1636                new String[]{authToken, accountType});
1637        try {
1638            while (cursor.moveToNext()) {
1639                long authTokenId = cursor.getLong(0);
1640                String accountName = cursor.getString(1);
1641                String authTokenType = cursor.getString(2);
1642                db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
1643                writeAuthTokenIntoCacheLocked(
1644                        accounts,
1645                        db,
1646                        new Account(accountName, accountType),
1647                        authTokenType,
1648                        null);
1649            }
1650        } finally {
1651            cursor.close();
1652        }
1653    }
1654
1655    private void saveCachedToken(
1656            UserAccounts accounts,
1657            Account account,
1658            String callerPkg,
1659            byte[] callerSigDigest,
1660            String tokenType,
1661            String token,
1662            long expiryMillis) {
1663
1664        if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1665            return;
1666        }
1667        cancelNotification(getSigninRequiredNotificationId(accounts, account),
1668                UserHandle.of(accounts.userId));
1669        synchronized (accounts.cacheLock) {
1670            accounts.accountTokenCaches.put(
1671                    account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
1672        }
1673    }
1674
1675    private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1676            String authToken) {
1677        if (account == null || type == null) {
1678            return false;
1679        }
1680        cancelNotification(getSigninRequiredNotificationId(accounts, account),
1681                UserHandle.of(accounts.userId));
1682        synchronized (accounts.cacheLock) {
1683            final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1684            db.beginTransaction();
1685            try {
1686                long accountId = getAccountIdLocked(db, account);
1687                if (accountId < 0) {
1688                    return false;
1689                }
1690                db.delete(CE_TABLE_AUTHTOKENS,
1691                        AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1692                        new String[]{type});
1693                ContentValues values = new ContentValues();
1694                values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1695                values.put(AUTHTOKENS_TYPE, type);
1696                values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1697                if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1698                    db.setTransactionSuccessful();
1699                    writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
1700                    return true;
1701                }
1702                return false;
1703            } finally {
1704                db.endTransaction();
1705            }
1706        }
1707    }
1708
1709    @Override
1710    public String peekAuthToken(Account account, String authTokenType) {
1711        final int callingUid = Binder.getCallingUid();
1712        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1713            Log.v(TAG, "peekAuthToken: " + account
1714                    + ", authTokenType " + authTokenType
1715                    + ", caller's uid " + callingUid
1716                    + ", pid " + Binder.getCallingPid());
1717        }
1718        if (account == null) throw new IllegalArgumentException("account is null");
1719        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1720        int userId = UserHandle.getCallingUserId();
1721        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1722            String msg = String.format(
1723                    "uid %s cannot peek the authtokens associated with accounts of type: %s",
1724                    callingUid,
1725                    account.type);
1726            throw new SecurityException(msg);
1727        }
1728        long identityToken = clearCallingIdentity();
1729        try {
1730            UserAccounts accounts = getUserAccounts(userId);
1731            return readAuthTokenInternal(accounts, account, authTokenType);
1732        } finally {
1733            restoreCallingIdentity(identityToken);
1734        }
1735    }
1736
1737    @Override
1738    public void setAuthToken(Account account, String authTokenType, String authToken) {
1739        final int callingUid = Binder.getCallingUid();
1740        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1741            Log.v(TAG, "setAuthToken: " + account
1742                    + ", authTokenType " + authTokenType
1743                    + ", caller's uid " + callingUid
1744                    + ", pid " + Binder.getCallingPid());
1745        }
1746        if (account == null) throw new IllegalArgumentException("account is null");
1747        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1748        int userId = UserHandle.getCallingUserId();
1749        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1750            String msg = String.format(
1751                    "uid %s cannot set auth tokens associated with accounts of type: %s",
1752                    callingUid,
1753                    account.type);
1754            throw new SecurityException(msg);
1755        }
1756        long identityToken = clearCallingIdentity();
1757        try {
1758            UserAccounts accounts = getUserAccounts(userId);
1759            saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
1760        } finally {
1761            restoreCallingIdentity(identityToken);
1762        }
1763    }
1764
1765    @Override
1766    public void setPassword(Account account, String password) {
1767        final int callingUid = Binder.getCallingUid();
1768        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1769            Log.v(TAG, "setAuthToken: " + account
1770                    + ", caller's uid " + callingUid
1771                    + ", pid " + Binder.getCallingPid());
1772        }
1773        if (account == null) throw new IllegalArgumentException("account is null");
1774        int userId = UserHandle.getCallingUserId();
1775        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1776            String msg = String.format(
1777                    "uid %s cannot set secrets for accounts of type: %s",
1778                    callingUid,
1779                    account.type);
1780            throw new SecurityException(msg);
1781        }
1782        long identityToken = clearCallingIdentity();
1783        try {
1784            UserAccounts accounts = getUserAccounts(userId);
1785            setPasswordInternal(accounts, account, password, callingUid);
1786        } finally {
1787            restoreCallingIdentity(identityToken);
1788        }
1789    }
1790
1791    private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1792            int callingUid) {
1793        if (account == null) {
1794            return;
1795        }
1796        synchronized (accounts.cacheLock) {
1797            final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
1798            db.beginTransaction();
1799            try {
1800                final ContentValues values = new ContentValues();
1801                values.put(ACCOUNTS_PASSWORD, password);
1802                final long accountId = getAccountIdLocked(db, account);
1803                if (accountId >= 0) {
1804                    final String[] argsAccountId = {String.valueOf(accountId)};
1805                    db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1806                    db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
1807                    accounts.authTokenCache.remove(account);
1808                    accounts.accountTokenCaches.remove(account);
1809                    db.setTransactionSuccessful();
1810
1811                    String action = (password == null || password.length() == 0) ?
1812                            DebugDbHelper.ACTION_CLEAR_PASSWORD
1813                            : DebugDbHelper.ACTION_SET_PASSWORD;
1814                    logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
1815                }
1816            } finally {
1817                db.endTransaction();
1818            }
1819            sendAccountsChangedBroadcast(accounts.userId);
1820        }
1821    }
1822
1823    private void sendAccountsChangedBroadcast(int userId) {
1824        Log.i(TAG, "the accounts changed, sending broadcast of "
1825                + ACCOUNTS_CHANGED_INTENT.getAction());
1826        mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
1827    }
1828
1829    @Override
1830    public void clearPassword(Account account) {
1831        final int callingUid = Binder.getCallingUid();
1832        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1833            Log.v(TAG, "clearPassword: " + account
1834                    + ", caller's uid " + callingUid
1835                    + ", pid " + Binder.getCallingPid());
1836        }
1837        if (account == null) throw new IllegalArgumentException("account is null");
1838        int userId = UserHandle.getCallingUserId();
1839        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1840            String msg = String.format(
1841                    "uid %s cannot clear passwords for accounts of type: %s",
1842                    callingUid,
1843                    account.type);
1844            throw new SecurityException(msg);
1845        }
1846        long identityToken = clearCallingIdentity();
1847        try {
1848            UserAccounts accounts = getUserAccounts(userId);
1849            setPasswordInternal(accounts, account, null, callingUid);
1850        } finally {
1851            restoreCallingIdentity(identityToken);
1852        }
1853    }
1854
1855    @Override
1856    public void setUserData(Account account, String key, String value) {
1857        final int callingUid = Binder.getCallingUid();
1858        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1859            Log.v(TAG, "setUserData: " + account
1860                    + ", key " + key
1861                    + ", caller's uid " + callingUid
1862                    + ", pid " + Binder.getCallingPid());
1863        }
1864        if (key == null) throw new IllegalArgumentException("key is null");
1865        if (account == null) throw new IllegalArgumentException("account is null");
1866        int userId = UserHandle.getCallingUserId();
1867        if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
1868            String msg = String.format(
1869                    "uid %s cannot set user data for accounts of type: %s",
1870                    callingUid,
1871                    account.type);
1872            throw new SecurityException(msg);
1873        }
1874        long identityToken = clearCallingIdentity();
1875        try {
1876            UserAccounts accounts = getUserAccounts(userId);
1877            synchronized (accounts.cacheLock) {
1878                if (!accountExistsCacheLocked(accounts, account)) {
1879                    return;
1880                }
1881                setUserdataInternalLocked(accounts, account, key, value);
1882            }
1883        } finally {
1884            restoreCallingIdentity(identityToken);
1885        }
1886    }
1887
1888    private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
1889        if (accounts.accountCache.containsKey(account.type)) {
1890            for (Account acc : accounts.accountCache.get(account.type)) {
1891                if (acc.name.equals(account.name)) {
1892                    return true;
1893                }
1894            }
1895        }
1896        return false;
1897    }
1898
1899    private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
1900            String value) {
1901        if (account == null || key == null) {
1902            return;
1903        }
1904        final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1905        db.beginTransaction();
1906        try {
1907            long accountId = getAccountIdLocked(db, account);
1908            if (accountId < 0) {
1909                return;
1910            }
1911            long extrasId = getExtrasIdLocked(db, accountId, key);
1912            if (extrasId < 0) {
1913                extrasId = insertExtraLocked(db, accountId, key, value);
1914                if (extrasId < 0) {
1915                    return;
1916                }
1917            } else {
1918                ContentValues values = new ContentValues();
1919                values.put(EXTRAS_VALUE, value);
1920                if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1921                    return;
1922                }
1923            }
1924            writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1925            db.setTransactionSuccessful();
1926        } finally {
1927            db.endTransaction();
1928        }
1929    }
1930
1931    private void onResult(IAccountManagerResponse response, Bundle result) {
1932        if (result == null) {
1933            Log.e(TAG, "the result is unexpectedly null", new Exception());
1934        }
1935        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1936            Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1937                    + response);
1938        }
1939        try {
1940            response.onResult(result);
1941        } catch (RemoteException e) {
1942            // if the caller is dead then there is no one to care about remote
1943            // exceptions
1944            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1945                Log.v(TAG, "failure while notifying response", e);
1946            }
1947        }
1948    }
1949
1950    @Override
1951    public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1952                                  final String authTokenType)
1953            throws RemoteException {
1954        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1955        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1956
1957        final int callingUid = getCallingUid();
1958        clearCallingIdentity();
1959        if (callingUid != Process.SYSTEM_UID) {
1960            throw new SecurityException("can only call from system");
1961        }
1962        int userId = UserHandle.getUserId(callingUid);
1963        long identityToken = clearCallingIdentity();
1964        try {
1965            UserAccounts accounts = getUserAccounts(userId);
1966            new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1967                    false /* stripAuthTokenFromResult */,  null /* accountName */,
1968                    false /* authDetailsRequired */) {
1969                @Override
1970                protected String toDebugString(long now) {
1971                    return super.toDebugString(now) + ", getAuthTokenLabel"
1972                            + ", " + accountType
1973                            + ", authTokenType " + authTokenType;
1974                }
1975
1976                @Override
1977                public void run() throws RemoteException {
1978                    mAuthenticator.getAuthTokenLabel(this, authTokenType);
1979                }
1980
1981                @Override
1982                public void onResult(Bundle result) {
1983                    Bundle.setDefusable(result, true);
1984                    if (result != null) {
1985                        String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1986                        Bundle bundle = new Bundle();
1987                        bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1988                        super.onResult(bundle);
1989                        return;
1990                    } else {
1991                        super.onResult(result);
1992                    }
1993                }
1994            }.bind();
1995        } finally {
1996            restoreCallingIdentity(identityToken);
1997        }
1998    }
1999
2000    @Override
2001    public void getAuthToken(
2002            IAccountManagerResponse response,
2003            final Account account,
2004            final String authTokenType,
2005            final boolean notifyOnAuthFailure,
2006            final boolean expectActivityLaunch,
2007            final Bundle loginOptions) {
2008        Bundle.setDefusable(loginOptions, true);
2009        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2010            Log.v(TAG, "getAuthToken: " + account
2011                    + ", response " + response
2012                    + ", authTokenType " + authTokenType
2013                    + ", notifyOnAuthFailure " + notifyOnAuthFailure
2014                    + ", expectActivityLaunch " + expectActivityLaunch
2015                    + ", caller's uid " + Binder.getCallingUid()
2016                    + ", pid " + Binder.getCallingPid());
2017        }
2018        if (response == null) throw new IllegalArgumentException("response is null");
2019        try {
2020            if (account == null) {
2021                Slog.w(TAG, "getAuthToken called with null account");
2022                response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2023                return;
2024            }
2025            if (authTokenType == null) {
2026                Slog.w(TAG, "getAuthToken called with null authTokenType");
2027                response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2028                return;
2029            }
2030        } catch (RemoteException e) {
2031            Slog.w(TAG, "Failed to report error back to the client." + e);
2032            return;
2033        }
2034        int userId = UserHandle.getCallingUserId();
2035        long ident = Binder.clearCallingIdentity();
2036        final UserAccounts accounts;
2037        final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2038        try {
2039            accounts = getUserAccounts(userId);
2040            authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2041                    AuthenticatorDescription.newKey(account.type), accounts.userId);
2042        } finally {
2043            Binder.restoreCallingIdentity(ident);
2044        }
2045
2046        final boolean customTokens =
2047                authenticatorInfo != null && authenticatorInfo.type.customTokens;
2048
2049        // skip the check if customTokens
2050        final int callerUid = Binder.getCallingUid();
2051        final boolean permissionGranted =
2052                customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
2053
2054        // Get the calling package. We will use it for the purpose of caching.
2055        final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2056        List<String> callerOwnedPackageNames;
2057        ident = Binder.clearCallingIdentity();
2058        try {
2059            callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2060        } finally {
2061            Binder.restoreCallingIdentity(ident);
2062        }
2063        if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2064            String msg = String.format(
2065                    "Uid %s is attempting to illegally masquerade as package %s!",
2066                    callerUid,
2067                    callerPkg);
2068            throw new SecurityException(msg);
2069        }
2070
2071        // let authenticator know the identity of the caller
2072        loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2073        loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
2074
2075        if (notifyOnAuthFailure) {
2076            loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
2077        }
2078
2079        long identityToken = clearCallingIdentity();
2080        try {
2081            // Distill the caller's package signatures into a single digest.
2082            final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2083
2084            // if the caller has permission, do the peek. otherwise go the more expensive
2085            // route of starting a Session
2086            if (!customTokens && permissionGranted) {
2087                String authToken = readAuthTokenInternal(accounts, account, authTokenType);
2088                if (authToken != null) {
2089                    Bundle result = new Bundle();
2090                    result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2091                    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2092                    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2093                    onResult(response, result);
2094                    return;
2095                }
2096            }
2097
2098            if (customTokens) {
2099                /*
2100                 * Look up tokens in the new cache only if the loginOptions don't have parameters
2101                 * outside of those expected to be injected by the AccountManager, e.g.
2102                 * ANDORID_PACKAGE_NAME.
2103                 */
2104                String token = readCachedTokenInternal(
2105                        accounts,
2106                        account,
2107                        authTokenType,
2108                        callerPkg,
2109                        callerPkgSigDigest);
2110                if (token != null) {
2111                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2112                        Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2113                    }
2114                    Bundle result = new Bundle();
2115                    result.putString(AccountManager.KEY_AUTHTOKEN, token);
2116                    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2117                    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2118                    onResult(response, result);
2119                    return;
2120                }
2121            }
2122
2123            new Session(accounts, response, account.type, expectActivityLaunch,
2124                    false /* stripAuthTokenFromResult */, account.name,
2125                    false /* authDetailsRequired */) {
2126                @Override
2127                protected String toDebugString(long now) {
2128                    if (loginOptions != null) loginOptions.keySet();
2129                    return super.toDebugString(now) + ", getAuthToken"
2130                            + ", " + account
2131                            + ", authTokenType " + authTokenType
2132                            + ", loginOptions " + loginOptions
2133                            + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2134                }
2135
2136                @Override
2137                public void run() throws RemoteException {
2138                    // If the caller doesn't have permission then create and return the
2139                    // "grant permission" intent instead of the "getAuthToken" intent.
2140                    if (!permissionGranted) {
2141                        mAuthenticator.getAuthTokenLabel(this, authTokenType);
2142                    } else {
2143                        mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2144                    }
2145                }
2146
2147                @Override
2148                public void onResult(Bundle result) {
2149                    Bundle.setDefusable(result, true);
2150                    if (result != null) {
2151                        if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
2152                            Intent intent = newGrantCredentialsPermissionIntent(
2153                                    account,
2154                                    callerUid,
2155                                    new AccountAuthenticatorResponse(this),
2156                                    authTokenType);
2157                            Bundle bundle = new Bundle();
2158                            bundle.putParcelable(AccountManager.KEY_INTENT, intent);
2159                            onResult(bundle);
2160                            return;
2161                        }
2162                        String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
2163                        if (authToken != null) {
2164                            String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2165                            String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2166                            if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
2167                                onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2168                                        "the type and name should not be empty");
2169                                return;
2170                            }
2171                            Account resultAccount = new Account(name, type);
2172                            if (!customTokens) {
2173                                saveAuthTokenToDatabase(
2174                                        mAccounts,
2175                                        resultAccount,
2176                                        authTokenType,
2177                                        authToken);
2178                            }
2179                            long expiryMillis = result.getLong(
2180                                    AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2181                            if (customTokens
2182                                    && expiryMillis > System.currentTimeMillis()) {
2183                                saveCachedToken(
2184                                        mAccounts,
2185                                        account,
2186                                        callerPkg,
2187                                        callerPkgSigDigest,
2188                                        authTokenType,
2189                                        authToken,
2190                                        expiryMillis);
2191                            }
2192                        }
2193
2194                        Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
2195                        if (intent != null && notifyOnAuthFailure && !customTokens) {
2196                            doNotification(mAccounts,
2197                                    account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
2198                                    intent, accounts.userId);
2199                        }
2200                    }
2201                    super.onResult(result);
2202                }
2203            }.bind();
2204        } finally {
2205            restoreCallingIdentity(identityToken);
2206        }
2207    }
2208
2209    private byte[] calculatePackageSignatureDigest(String callerPkg) {
2210        MessageDigest digester;
2211        try {
2212            digester = MessageDigest.getInstance("SHA-256");
2213            PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2214                    callerPkg, PackageManager.GET_SIGNATURES);
2215            for (Signature sig : pkgInfo.signatures) {
2216                digester.update(sig.toByteArray());
2217            }
2218        } catch (NoSuchAlgorithmException x) {
2219            Log.wtf(TAG, "SHA-256 should be available", x);
2220            digester = null;
2221        } catch (NameNotFoundException e) {
2222            Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2223            digester = null;
2224        }
2225        return (digester == null) ? null : digester.digest();
2226    }
2227
2228    private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2229            int userId) {
2230        int uid = intent.getIntExtra(
2231                GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2232        String authTokenType = intent.getStringExtra(
2233                GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
2234        final String titleAndSubtitle =
2235                mContext.getString(R.string.permission_request_notification_with_subtitle,
2236                account.name);
2237        final int index = titleAndSubtitle.indexOf('\n');
2238        String title = titleAndSubtitle;
2239        String subtitle = "";
2240        if (index > 0) {
2241            title = titleAndSubtitle.substring(0, index);
2242            subtitle = titleAndSubtitle.substring(index + 1);
2243        }
2244        UserHandle user = new UserHandle(userId);
2245        Context contextForUser = getContextForUser(user);
2246        Notification n = new Notification.Builder(contextForUser)
2247                .setSmallIcon(android.R.drawable.stat_sys_warning)
2248                .setWhen(0)
2249                .setColor(contextForUser.getColor(
2250                        com.android.internal.R.color.system_notification_accent_color))
2251                .setContentTitle(title)
2252                .setContentText(subtitle)
2253                .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2254                        PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2255                .build();
2256        installNotification(getCredentialPermissionNotificationId(
2257                account, authTokenType, uid), n, user);
2258    }
2259
2260    private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
2261            AccountAuthenticatorResponse response, String authTokenType) {
2262
2263        Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
2264        // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
2265        // Since it was set in Eclair+ we can't change it without breaking apps using
2266        // the intent from a non-Activity context.
2267        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2268        intent.addCategory(
2269                String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
2270
2271        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
2272        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2273        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
2274        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
2275
2276        return intent;
2277    }
2278
2279    private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2280            int uid) {
2281        Integer id;
2282        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
2283        synchronized (accounts.credentialsPermissionNotificationIds) {
2284            final Pair<Pair<Account, String>, Integer> key =
2285                    new Pair<Pair<Account, String>, Integer>(
2286                            new Pair<Account, String>(account, authTokenType), uid);
2287            id = accounts.credentialsPermissionNotificationIds.get(key);
2288            if (id == null) {
2289                id = mNotificationIds.incrementAndGet();
2290                accounts.credentialsPermissionNotificationIds.put(key, id);
2291            }
2292        }
2293        return id;
2294    }
2295
2296    private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
2297        Integer id;
2298        synchronized (accounts.signinRequiredNotificationIds) {
2299            id = accounts.signinRequiredNotificationIds.get(account);
2300            if (id == null) {
2301                id = mNotificationIds.incrementAndGet();
2302                accounts.signinRequiredNotificationIds.put(account, id);
2303            }
2304        }
2305        return id;
2306    }
2307
2308    @Override
2309    public void addAccount(final IAccountManagerResponse response, final String accountType,
2310            final String authTokenType, final String[] requiredFeatures,
2311            final boolean expectActivityLaunch, final Bundle optionsIn) {
2312        Bundle.setDefusable(optionsIn, true);
2313        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2314            Log.v(TAG, "addAccount: accountType " + accountType
2315                    + ", response " + response
2316                    + ", authTokenType " + authTokenType
2317                    + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2318                    + ", expectActivityLaunch " + expectActivityLaunch
2319                    + ", caller's uid " + Binder.getCallingUid()
2320                    + ", pid " + Binder.getCallingPid());
2321        }
2322        if (response == null) throw new IllegalArgumentException("response is null");
2323        if (accountType == null) throw new IllegalArgumentException("accountType is null");
2324
2325        // Is user disallowed from modifying accounts?
2326        final int uid = Binder.getCallingUid();
2327        final int userId = UserHandle.getUserId(uid);
2328        if (!canUserModifyAccounts(userId, uid)) {
2329            try {
2330                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2331                        "User is not allowed to add an account!");
2332            } catch (RemoteException re) {
2333            }
2334            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2335            return;
2336        }
2337        if (!canUserModifyAccountsForType(userId, accountType, uid)) {
2338            try {
2339                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2340                        "User cannot modify accounts of this type (policy).");
2341            } catch (RemoteException re) {
2342            }
2343            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2344                    userId);
2345            return;
2346        }
2347
2348        final int pid = Binder.getCallingPid();
2349        final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2350        options.putInt(AccountManager.KEY_CALLER_UID, uid);
2351        options.putInt(AccountManager.KEY_CALLER_PID, pid);
2352
2353        int usrId = UserHandle.getCallingUserId();
2354        long identityToken = clearCallingIdentity();
2355        try {
2356            UserAccounts accounts = getUserAccounts(usrId);
2357            logRecordWithUid(
2358                    accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
2359            new Session(accounts, response, accountType, expectActivityLaunch,
2360                    true /* stripAuthTokenFromResult */, null /* accountName */,
2361                    false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
2362                @Override
2363                public void run() throws RemoteException {
2364                    mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2365                            options);
2366                }
2367
2368                @Override
2369                protected String toDebugString(long now) {
2370                    return super.toDebugString(now) + ", addAccount"
2371                            + ", accountType " + accountType
2372                            + ", requiredFeatures "
2373                            + (requiredFeatures != null
2374                              ? TextUtils.join(",", requiredFeatures)
2375                              : null);
2376                }
2377            }.bind();
2378        } finally {
2379            restoreCallingIdentity(identityToken);
2380        }
2381    }
2382
2383    @Override
2384    public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2385            final String authTokenType, final String[] requiredFeatures,
2386            final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
2387        Bundle.setDefusable(optionsIn, true);
2388        int callingUid = Binder.getCallingUid();
2389        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2390            Log.v(TAG, "addAccount: accountType " + accountType
2391                    + ", response " + response
2392                    + ", authTokenType " + authTokenType
2393                    + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2394                    + ", expectActivityLaunch " + expectActivityLaunch
2395                    + ", caller's uid " + Binder.getCallingUid()
2396                    + ", pid " + Binder.getCallingPid()
2397                    + ", for user id " + userId);
2398        }
2399        if (response == null) throw new IllegalArgumentException("response is null");
2400        if (accountType == null) throw new IllegalArgumentException("accountType is null");
2401        // Only allow the system process to add accounts of other users
2402        if (isCrossUser(callingUid, userId)) {
2403            throw new SecurityException(
2404                    String.format(
2405                            "User %s trying to add account for %s" ,
2406                            UserHandle.getCallingUserId(),
2407                            userId));
2408        }
2409
2410        // Is user disallowed from modifying accounts?
2411        if (!canUserModifyAccounts(userId, callingUid)) {
2412            try {
2413                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2414                        "User is not allowed to add an account!");
2415            } catch (RemoteException re) {
2416            }
2417            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2418            return;
2419        }
2420        if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
2421            try {
2422                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2423                        "User cannot modify accounts of this type (policy).");
2424            } catch (RemoteException re) {
2425            }
2426            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2427                    userId);
2428            return;
2429        }
2430
2431        final int pid = Binder.getCallingPid();
2432        final int uid = Binder.getCallingUid();
2433        final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2434        options.putInt(AccountManager.KEY_CALLER_UID, uid);
2435        options.putInt(AccountManager.KEY_CALLER_PID, pid);
2436
2437        long identityToken = clearCallingIdentity();
2438        try {
2439            UserAccounts accounts = getUserAccounts(userId);
2440            logRecordWithUid(
2441                    accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
2442            new Session(accounts, response, accountType, expectActivityLaunch,
2443                    true /* stripAuthTokenFromResult */, null /* accountName */,
2444                    false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
2445                @Override
2446                public void run() throws RemoteException {
2447                    mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2448                            options);
2449                }
2450
2451                @Override
2452                protected String toDebugString(long now) {
2453                    return super.toDebugString(now) + ", addAccount"
2454                            + ", accountType " + accountType
2455                            + ", requiredFeatures "
2456                            + (requiredFeatures != null
2457                              ? TextUtils.join(",", requiredFeatures)
2458                              : null);
2459                }
2460            }.bind();
2461        } finally {
2462            restoreCallingIdentity(identityToken);
2463        }
2464    }
2465
2466    @Override
2467    public void startAddAccountSession(
2468            final IAccountManagerResponse response,
2469            final String accountType,
2470            final String authTokenType,
2471            final String[] requiredFeatures,
2472            final boolean expectActivityLaunch,
2473            final Bundle optionsIn) {
2474        Bundle.setDefusable(optionsIn, true);
2475        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2476            Log.v(TAG,
2477                    "startAddAccountSession: accountType " + accountType
2478                    + ", response " + response
2479                    + ", authTokenType " + authTokenType
2480                    + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2481                    + ", expectActivityLaunch " + expectActivityLaunch
2482                    + ", caller's uid " + Binder.getCallingUid()
2483                    + ", pid " + Binder.getCallingPid());
2484        }
2485        if (response == null) {
2486            throw new IllegalArgumentException("response is null");
2487        }
2488        if (accountType == null) {
2489            throw new IllegalArgumentException("accountType is null");
2490        }
2491
2492        final int uid = Binder.getCallingUid();
2493        // Only allow system to start session
2494        if (!isSystemUid(uid)) {
2495            String msg = String.format(
2496                    "uid %s cannot stat add account session.",
2497                    uid);
2498            throw new SecurityException(msg);
2499        }
2500
2501        final int userId = UserHandle.getUserId(uid);
2502        if (!canUserModifyAccounts(userId, uid)) {
2503            try {
2504                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2505                        "User is not allowed to add an account!");
2506            } catch (RemoteException re) {
2507            }
2508            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2509            return;
2510        }
2511        if (!canUserModifyAccountsForType(userId, accountType, uid)) {
2512            try {
2513                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2514                        "User cannot modify accounts of this type (policy).");
2515            } catch (RemoteException re) {
2516            }
2517            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2518                    userId);
2519            return;
2520        }
2521        final int pid = Binder.getCallingPid();
2522        final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2523        options.putInt(AccountManager.KEY_CALLER_UID, uid);
2524        options.putInt(AccountManager.KEY_CALLER_PID, pid);
2525
2526        // Check to see if the Password should be included to the caller.
2527        String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2528        boolean isPasswordForwardingAllowed = isPermitted(
2529                callerPkg, uid, Manifest.permission.GET_PASSWORD_PRIVILEGED);
2530
2531        int usrId = UserHandle.getCallingUserId();
2532        long identityToken = clearCallingIdentity();
2533        try {
2534            UserAccounts accounts = getUserAccounts(usrId);
2535            logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2536                    TABLE_ACCOUNTS, uid);
2537            new StartAccountSession(
2538                    accounts,
2539                    response,
2540                    accountType,
2541                    expectActivityLaunch,
2542                    null /* accountName */,
2543                    false /* authDetailsRequired */,
2544                    true /* updateLastAuthenticationTime */,
2545                    isPasswordForwardingAllowed) {
2546                @Override
2547                public void run() throws RemoteException {
2548                    mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2549                            requiredFeatures, options);
2550                }
2551
2552                @Override
2553                protected String toDebugString(long now) {
2554                    String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2555                    return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2556                            + accountType + ", requiredFeatures "
2557                            + (requiredFeatures != null ? requiredFeaturesStr : null);
2558                }
2559            }.bind();
2560        } finally {
2561            restoreCallingIdentity(identityToken);
2562        }
2563    }
2564
2565    /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2566    private abstract class StartAccountSession extends Session {
2567
2568        private final boolean mIsPasswordForwardingAllowed;
2569
2570        public StartAccountSession(
2571                UserAccounts accounts,
2572                IAccountManagerResponse response,
2573                String accountType,
2574                boolean expectActivityLaunch,
2575                String accountName,
2576                boolean authDetailsRequired,
2577                boolean updateLastAuthenticationTime,
2578                boolean isPasswordForwardingAllowed) {
2579            super(accounts, response, accountType, expectActivityLaunch,
2580                    true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2581                    updateLastAuthenticationTime);
2582            mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
2583        }
2584
2585        @Override
2586        public void onResult(Bundle result) {
2587            Bundle.setDefusable(result, true);
2588            mNumResults++;
2589            Intent intent = null;
2590            if (result != null
2591                    && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2592                checkKeyIntent(
2593                        Binder.getCallingUid(),
2594                        intent);
2595                // Omit passwords if the caller isn't permitted to see them.
2596                if (!mIsPasswordForwardingAllowed) {
2597                    result.remove(AccountManager.KEY_PASSWORD);
2598                }
2599            }
2600            IAccountManagerResponse response;
2601            if (mExpectActivityLaunch && result != null
2602                    && result.containsKey(AccountManager.KEY_INTENT)) {
2603                response = mResponse;
2604            } else {
2605                response = getResponseAndClose();
2606            }
2607            if (response == null) {
2608                return;
2609            }
2610            if (result == null) {
2611                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2612                    Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2613                            + response);
2614                }
2615                sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2616                        "null bundle returned");
2617                return;
2618            }
2619
2620            if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2621                // All AccountManager error codes are greater
2622                // than 0
2623                sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2624                        result.getString(AccountManager.KEY_ERROR_MESSAGE));
2625                return;
2626            }
2627
2628            // Strip auth token from result.
2629            result.remove(AccountManager.KEY_AUTHTOKEN);
2630
2631            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2632                Log.v(TAG,
2633                        getClass().getSimpleName() + " calling onResult() on response " + response);
2634            }
2635
2636            // Get the session bundle created by authenticator. The
2637            // bundle contains data necessary for finishing the session
2638            // later. The session bundle will be encrypted here and
2639            // decrypted later when trying to finish the session.
2640            Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2641            if (sessionBundle != null) {
2642                String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2643                if (TextUtils.isEmpty(accountType)
2644                        || !mAccountType.equalsIgnoreCase(accountType)) {
2645                    Log.w(TAG, "Account type in session bundle doesn't match request.");
2646                }
2647                // Add accountType info to session bundle. This will
2648                // override any value set by authenticator.
2649                sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2650
2651                // Encrypt session bundle before returning to caller.
2652                try {
2653                    CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2654                    Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2655                    result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2656                } catch (GeneralSecurityException e) {
2657                    if (Log.isLoggable(TAG, Log.DEBUG)) {
2658                        Log.v(TAG, "Failed to encrypt session bundle!", e);
2659                    }
2660                    sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2661                            "failed to encrypt session bundle");
2662                    return;
2663                }
2664            }
2665
2666            sendResponse(response, result);
2667        }
2668    }
2669
2670    @Override
2671    public void finishSessionAsUser(IAccountManagerResponse response,
2672            @NonNull Bundle sessionBundle,
2673            boolean expectActivityLaunch,
2674            Bundle appInfo,
2675            int userId) {
2676        Bundle.setDefusable(sessionBundle, true);
2677        int callingUid = Binder.getCallingUid();
2678        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2679            Log.v(TAG,
2680                    "finishSession: response "+ response
2681                            + ", expectActivityLaunch " + expectActivityLaunch
2682                            + ", caller's uid " + callingUid
2683                            + ", caller's user id " + UserHandle.getCallingUserId()
2684                            + ", pid " + Binder.getCallingPid()
2685                            + ", for user id " + userId);
2686        }
2687        if (response == null) {
2688            throw new IllegalArgumentException("response is null");
2689        }
2690
2691        // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2692        // Account type is added to it before encryption.
2693        if (sessionBundle == null || sessionBundle.size() == 0) {
2694            throw new IllegalArgumentException("sessionBundle is empty");
2695        }
2696
2697        // Only allow the system process to finish session for other users
2698        if (isCrossUser(callingUid, userId)) {
2699            throw new SecurityException(
2700                    String.format(
2701                            "User %s trying to finish session for %s without cross user permission",
2702                            UserHandle.getCallingUserId(),
2703                            userId));
2704        }
2705
2706        // Only allow system to finish session
2707        if (!isSystemUid(callingUid)) {
2708            String msg = String.format(
2709                    "uid %s cannot finish session because it's not system uid.",
2710                    callingUid);
2711            throw new SecurityException(msg);
2712        }
2713
2714        if (!canUserModifyAccounts(userId, callingUid)) {
2715            sendErrorResponse(response,
2716                    AccountManager.ERROR_CODE_USER_RESTRICTED,
2717                    "User is not allowed to add an account!");
2718            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2719            return;
2720        }
2721
2722        final int pid = Binder.getCallingPid();
2723        final Bundle decryptedBundle;
2724        final String accountType;
2725        // First decrypt session bundle to get account type for checking permission.
2726        try {
2727            CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2728            decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2729            if (decryptedBundle == null) {
2730                sendErrorResponse(
2731                        response,
2732                        AccountManager.ERROR_CODE_BAD_REQUEST,
2733                        "failed to decrypt session bundle");
2734                return;
2735            }
2736            accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2737            // Account type cannot be null. This should not happen if session bundle was created
2738            // properly by #StartAccountSession.
2739            if (TextUtils.isEmpty(accountType)) {
2740                sendErrorResponse(
2741                        response,
2742                        AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2743                        "accountType is empty");
2744                return;
2745            }
2746
2747            // If by any chances, decryptedBundle contains colliding keys with
2748            // system info
2749            // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2750            // update credentials flow, we should replace with the new values of the current call.
2751            if (appInfo != null) {
2752                decryptedBundle.putAll(appInfo);
2753            }
2754
2755            // Add info that may be used by add account or update credentials flow.
2756            decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
2757            decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2758        } catch (GeneralSecurityException e) {
2759            if (Log.isLoggable(TAG, Log.DEBUG)) {
2760                Log.v(TAG, "Failed to decrypt session bundle!", e);
2761            }
2762            sendErrorResponse(
2763                    response,
2764                    AccountManager.ERROR_CODE_BAD_REQUEST,
2765                    "failed to decrypt session bundle");
2766            return;
2767        }
2768
2769        if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
2770            sendErrorResponse(
2771                    response,
2772                    AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2773                    "User cannot modify accounts of this type (policy).");
2774            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2775                    userId);
2776            return;
2777        }
2778
2779        long identityToken = clearCallingIdentity();
2780        try {
2781            UserAccounts accounts = getUserAccounts(userId);
2782            logRecordWithUid(
2783                    accounts,
2784                    DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2785                    TABLE_ACCOUNTS,
2786                    callingUid);
2787            new Session(
2788                    accounts,
2789                    response,
2790                    accountType,
2791                    expectActivityLaunch,
2792                    true /* stripAuthTokenFromResult */,
2793                    null /* accountName */,
2794                    false /* authDetailsRequired */,
2795                    true /* updateLastAuthenticationTime */) {
2796                @Override
2797                public void run() throws RemoteException {
2798                    mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2799                }
2800
2801                @Override
2802                protected String toDebugString(long now) {
2803                    return super.toDebugString(now)
2804                            + ", finishSession"
2805                            + ", accountType " + accountType;
2806                }
2807            }.bind();
2808        } finally {
2809            restoreCallingIdentity(identityToken);
2810        }
2811    }
2812
2813    private void showCantAddAccount(int errorCode, int userId) {
2814        Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2815        cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2816        cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2817        long identityToken = clearCallingIdentity();
2818        try {
2819            mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
2820        } finally {
2821            restoreCallingIdentity(identityToken);
2822        }
2823    }
2824
2825    @Override
2826    public void confirmCredentialsAsUser(
2827            IAccountManagerResponse response,
2828            final Account account,
2829            final Bundle options,
2830            final boolean expectActivityLaunch,
2831            int userId) {
2832        Bundle.setDefusable(options, true);
2833        int callingUid = Binder.getCallingUid();
2834        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2835            Log.v(TAG, "confirmCredentials: " + account
2836                    + ", response " + response
2837                    + ", expectActivityLaunch " + expectActivityLaunch
2838                    + ", caller's uid " + callingUid
2839                    + ", pid " + Binder.getCallingPid());
2840        }
2841        // Only allow the system process to read accounts of other users
2842        if (isCrossUser(callingUid, userId)) {
2843            throw new SecurityException(
2844                    String.format(
2845                            "User %s trying to confirm account credentials for %s" ,
2846                            UserHandle.getCallingUserId(),
2847                            userId));
2848        }
2849        if (response == null) throw new IllegalArgumentException("response is null");
2850        if (account == null) throw new IllegalArgumentException("account is null");
2851        long identityToken = clearCallingIdentity();
2852        try {
2853            UserAccounts accounts = getUserAccounts(userId);
2854            new Session(accounts, response, account.type, expectActivityLaunch,
2855                    true /* stripAuthTokenFromResult */, account.name,
2856                    true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
2857                @Override
2858                public void run() throws RemoteException {
2859                    mAuthenticator.confirmCredentials(this, account, options);
2860                }
2861                @Override
2862                protected String toDebugString(long now) {
2863                    return super.toDebugString(now) + ", confirmCredentials"
2864                            + ", " + account;
2865                }
2866            }.bind();
2867        } finally {
2868            restoreCallingIdentity(identityToken);
2869        }
2870    }
2871
2872    @Override
2873    public void updateCredentials(IAccountManagerResponse response, final Account account,
2874            final String authTokenType, final boolean expectActivityLaunch,
2875            final Bundle loginOptions) {
2876        Bundle.setDefusable(loginOptions, true);
2877        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2878            Log.v(TAG, "updateCredentials: " + account
2879                    + ", response " + response
2880                    + ", authTokenType " + authTokenType
2881                    + ", expectActivityLaunch " + expectActivityLaunch
2882                    + ", caller's uid " + Binder.getCallingUid()
2883                    + ", pid " + Binder.getCallingPid());
2884        }
2885        if (response == null) throw new IllegalArgumentException("response is null");
2886        if (account == null) throw new IllegalArgumentException("account is null");
2887        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2888        int userId = UserHandle.getCallingUserId();
2889        long identityToken = clearCallingIdentity();
2890        try {
2891            UserAccounts accounts = getUserAccounts(userId);
2892            new Session(accounts, response, account.type, expectActivityLaunch,
2893                    true /* stripAuthTokenFromResult */, account.name,
2894                    false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
2895                @Override
2896                public void run() throws RemoteException {
2897                    mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2898                }
2899                @Override
2900                protected String toDebugString(long now) {
2901                    if (loginOptions != null) loginOptions.keySet();
2902                    return super.toDebugString(now) + ", updateCredentials"
2903                            + ", " + account
2904                            + ", authTokenType " + authTokenType
2905                            + ", loginOptions " + loginOptions;
2906                }
2907            }.bind();
2908        } finally {
2909            restoreCallingIdentity(identityToken);
2910        }
2911    }
2912
2913    @Override
2914    public void startUpdateCredentialsSession(
2915            IAccountManagerResponse response,
2916            final Account account,
2917            final String authTokenType,
2918            final boolean expectActivityLaunch,
2919            final Bundle loginOptions) {
2920        Bundle.setDefusable(loginOptions, true);
2921        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2922            Log.v(TAG,
2923                    "startUpdateCredentialsSession: " + account + ", response " + response
2924                            + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2925                            + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2926                            + ", pid " + Binder.getCallingPid());
2927        }
2928        if (response == null) {
2929            throw new IllegalArgumentException("response is null");
2930        }
2931        if (account == null) {
2932            throw new IllegalArgumentException("account is null");
2933        }
2934
2935        final int uid = Binder.getCallingUid();
2936        // Only allow system to start session
2937        if (!isSystemUid(uid)) {
2938            String msg = String.format(
2939                    "uid %s cannot start update credentials session.",
2940                    uid);
2941            throw new SecurityException(msg);
2942        }
2943
2944        int userId = UserHandle.getCallingUserId();
2945
2946        // Check to see if the Password should be included to the caller.
2947        String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2948        boolean isPasswordForwardingAllowed = isPermitted(
2949                callerPkg, uid, Manifest.permission.GET_PASSWORD_PRIVILEGED);
2950
2951        long identityToken = clearCallingIdentity();
2952        try {
2953            UserAccounts accounts = getUserAccounts(userId);
2954            new StartAccountSession(
2955                    accounts,
2956                    response,
2957                    account.type,
2958                    expectActivityLaunch,
2959                    account.name,
2960                    false /* authDetailsRequired */,
2961                    true /* updateLastCredentialTime */,
2962                    isPasswordForwardingAllowed) {
2963                @Override
2964                public void run() throws RemoteException {
2965                    mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2966                            loginOptions);
2967                }
2968
2969                @Override
2970                protected String toDebugString(long now) {
2971                    if (loginOptions != null)
2972                        loginOptions.keySet();
2973                    return super.toDebugString(now)
2974                            + ", startUpdateCredentialsSession"
2975                            + ", " + account
2976                            + ", authTokenType " + authTokenType
2977                            + ", loginOptions " + loginOptions;
2978                }
2979            }.bind();
2980        } finally {
2981            restoreCallingIdentity(identityToken);
2982        }
2983    }
2984
2985    @Override
2986    public void isCredentialsUpdateSuggested(
2987            IAccountManagerResponse response,
2988            final Account account,
2989            final String statusToken) {
2990        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2991            Log.v(TAG,
2992                    "isCredentialsUpdateSuggested: " + account + ", response " + response
2993                            + ", caller's uid " + Binder.getCallingUid()
2994                            + ", pid " + Binder.getCallingPid());
2995        }
2996        if (response == null) {
2997            throw new IllegalArgumentException("response is null");
2998        }
2999        if (account == null) {
3000            throw new IllegalArgumentException("account is null");
3001        }
3002        if (TextUtils.isEmpty(statusToken)) {
3003            throw new IllegalArgumentException("status token is empty");
3004        }
3005
3006        int uid = Binder.getCallingUid();
3007        // Only allow system to start session
3008        if (!isSystemUid(uid)) {
3009            String msg = String.format(
3010                    "uid %s cannot stat add account session.",
3011                    uid);
3012            throw new SecurityException(msg);
3013        }
3014
3015        int usrId = UserHandle.getCallingUserId();
3016        long identityToken = clearCallingIdentity();
3017        try {
3018            UserAccounts accounts = getUserAccounts(usrId);
3019            new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3020                    false /* stripAuthTokenFromResult */, account.name,
3021                    false /* authDetailsRequired */) {
3022                @Override
3023                protected String toDebugString(long now) {
3024                    return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3025                            + ", " + account;
3026                }
3027
3028                @Override
3029                public void run() throws RemoteException {
3030                    mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3031                }
3032
3033                @Override
3034                public void onResult(Bundle result) {
3035                    Bundle.setDefusable(result, true);
3036                    IAccountManagerResponse response = getResponseAndClose();
3037                    if (response == null) {
3038                        return;
3039                    }
3040
3041                    if (result == null) {
3042                        sendErrorResponse(
3043                                response,
3044                                AccountManager.ERROR_CODE_INVALID_RESPONSE,
3045                                "null bundle");
3046                        return;
3047                    }
3048
3049                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3050                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3051                                + response);
3052                    }
3053                    // Check to see if an error occurred. We know if an error occurred because all
3054                    // error codes are greater than 0.
3055                    if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3056                        sendErrorResponse(response,
3057                                result.getInt(AccountManager.KEY_ERROR_CODE),
3058                                result.getString(AccountManager.KEY_ERROR_MESSAGE));
3059                        return;
3060                    }
3061                    if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3062                        sendErrorResponse(
3063                                response,
3064                                AccountManager.ERROR_CODE_INVALID_RESPONSE,
3065                                "no result in response");
3066                        return;
3067                    }
3068                    final Bundle newResult = new Bundle();
3069                    newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3070                            result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3071                    sendResponse(response, newResult);
3072                }
3073            }.bind();
3074        } finally {
3075            restoreCallingIdentity(identityToken);
3076        }
3077    }
3078
3079    @Override
3080    public void editProperties(IAccountManagerResponse response, final String accountType,
3081            final boolean expectActivityLaunch) {
3082        final int callingUid = Binder.getCallingUid();
3083        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3084            Log.v(TAG, "editProperties: accountType " + accountType
3085                    + ", response " + response
3086                    + ", expectActivityLaunch " + expectActivityLaunch
3087                    + ", caller's uid " + callingUid
3088                    + ", pid " + Binder.getCallingPid());
3089        }
3090        if (response == null) throw new IllegalArgumentException("response is null");
3091        if (accountType == null) throw new IllegalArgumentException("accountType is null");
3092        int userId = UserHandle.getCallingUserId();
3093        if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
3094            String msg = String.format(
3095                    "uid %s cannot edit authenticator properites for account type: %s",
3096                    callingUid,
3097                    accountType);
3098            throw new SecurityException(msg);
3099        }
3100        long identityToken = clearCallingIdentity();
3101        try {
3102            UserAccounts accounts = getUserAccounts(userId);
3103            new Session(accounts, response, accountType, expectActivityLaunch,
3104                    true /* stripAuthTokenFromResult */, null /* accountName */,
3105                    false /* authDetailsRequired */) {
3106                @Override
3107                public void run() throws RemoteException {
3108                    mAuthenticator.editProperties(this, mAccountType);
3109                }
3110                @Override
3111                protected String toDebugString(long now) {
3112                    return super.toDebugString(now) + ", editProperties"
3113                            + ", accountType " + accountType;
3114                }
3115            }.bind();
3116        } finally {
3117            restoreCallingIdentity(identityToken);
3118        }
3119    }
3120
3121    @Override
3122    public boolean someUserHasAccount(@NonNull final Account account) {
3123        if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3124            throw new SecurityException("Only system can check for accounts across users");
3125        }
3126        final long token = Binder.clearCallingIdentity();
3127        try {
3128            AccountAndUser[] allAccounts = getAllAccounts();
3129            for (int i = allAccounts.length - 1; i >= 0; i--) {
3130                if (allAccounts[i].account.equals(account)) {
3131                    return true;
3132                }
3133            }
3134            return false;
3135        } finally {
3136            Binder.restoreCallingIdentity(token);
3137        }
3138    }
3139
3140    private class GetAccountsByTypeAndFeatureSession extends Session {
3141        private final String[] mFeatures;
3142        private volatile Account[] mAccountsOfType = null;
3143        private volatile ArrayList<Account> mAccountsWithFeatures = null;
3144        private volatile int mCurrentAccount = 0;
3145        private final int mCallingUid;
3146
3147        public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
3148                IAccountManagerResponse response, String type, String[] features, int callingUid) {
3149            super(accounts, response, type, false /* expectActivityLaunch */,
3150                    true /* stripAuthTokenFromResult */, null /* accountName */,
3151                    false /* authDetailsRequired */);
3152            mCallingUid = callingUid;
3153            mFeatures = features;
3154        }
3155
3156        @Override
3157        public void run() throws RemoteException {
3158            synchronized (mAccounts.cacheLock) {
3159                mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3160                        null);
3161            }
3162            // check whether each account matches the requested features
3163            mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3164            mCurrentAccount = 0;
3165
3166            checkAccount();
3167        }
3168
3169        public void checkAccount() {
3170            if (mCurrentAccount >= mAccountsOfType.length) {
3171                sendResult();
3172                return;
3173            }
3174
3175            final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3176            if (accountAuthenticator == null) {
3177                // It is possible that the authenticator has died, which is indicated by
3178                // mAuthenticator being set to null. If this happens then just abort.
3179                // There is no need to send back a result or error in this case since
3180                // that already happened when mAuthenticator was cleared.
3181                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3182                    Log.v(TAG, "checkAccount: aborting session since we are no longer"
3183                            + " connected to the authenticator, " + toDebugString());
3184                }
3185                return;
3186            }
3187            try {
3188                accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
3189            } catch (RemoteException e) {
3190                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
3191            }
3192        }
3193
3194        @Override
3195        public void onResult(Bundle result) {
3196            Bundle.setDefusable(result, true);
3197            mNumResults++;
3198            if (result == null) {
3199                onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
3200                return;
3201            }
3202            if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
3203                mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3204            }
3205            mCurrentAccount++;
3206            checkAccount();
3207        }
3208
3209        public void sendResult() {
3210            IAccountManagerResponse response = getResponseAndClose();
3211            if (response != null) {
3212                try {
3213                    Account[] accounts = new Account[mAccountsWithFeatures.size()];
3214                    for (int i = 0; i < accounts.length; i++) {
3215                        accounts[i] = mAccountsWithFeatures.get(i);
3216                    }
3217                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3218                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3219                                + response);
3220                    }
3221                    Bundle result = new Bundle();
3222                    result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3223                    response.onResult(result);
3224                } catch (RemoteException e) {
3225                    // if the caller is dead then there is no one to care about remote exceptions
3226                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3227                        Log.v(TAG, "failure while notifying response", e);
3228                    }
3229                }
3230            }
3231        }
3232
3233
3234        @Override
3235        protected String toDebugString(long now) {
3236            return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3237                    + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3238        }
3239    }
3240
3241    /**
3242     * Returns the accounts visible to the client within the context of a specific user
3243     * @hide
3244     */
3245    @NonNull
3246    public Account[] getAccounts(int userId, String opPackageName) {
3247        int callingUid = Binder.getCallingUid();
3248        List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3249                opPackageName);
3250        if (visibleAccountTypes.isEmpty()) {
3251            return new Account[0];
3252        }
3253        long identityToken = clearCallingIdentity();
3254        try {
3255            UserAccounts accounts = getUserAccounts(userId);
3256            return getAccountsInternal(
3257                    accounts,
3258                    callingUid,
3259                    null,  // packageName
3260                    visibleAccountTypes);
3261        } finally {
3262            restoreCallingIdentity(identityToken);
3263        }
3264    }
3265
3266    /**
3267     * Returns accounts for all running users.
3268     *
3269     * @hide
3270     */
3271    @NonNull
3272    public AccountAndUser[] getRunningAccounts() {
3273        final int[] runningUserIds;
3274        try {
3275            runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3276        } catch (RemoteException e) {
3277            // Running in system_server; should never happen
3278            throw new RuntimeException(e);
3279        }
3280        return getAccounts(runningUserIds);
3281    }
3282
3283    /** {@hide} */
3284    @NonNull
3285    public AccountAndUser[] getAllAccounts() {
3286        final List<UserInfo> users = getUserManager().getUsers();
3287        final int[] userIds = new int[users.size()];
3288        for (int i = 0; i < userIds.length; i++) {
3289            userIds[i] = users.get(i).id;
3290        }
3291        return getAccounts(userIds);
3292    }
3293
3294    @NonNull
3295    private AccountAndUser[] getAccounts(int[] userIds) {
3296        final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
3297        for (int userId : userIds) {
3298            UserAccounts userAccounts = getUserAccounts(userId);
3299            if (userAccounts == null) continue;
3300            synchronized (userAccounts.cacheLock) {
3301                Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3302                        Binder.getCallingUid(), null);
3303                for (int a = 0; a < accounts.length; a++) {
3304                    runningAccounts.add(new AccountAndUser(accounts[a], userId));
3305                }
3306            }
3307        }
3308
3309        AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3310        return runningAccounts.toArray(accountsArray);
3311    }
3312
3313    @Override
3314    @NonNull
3315    public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3316        return getAccountsAsUser(type, userId, null, -1, opPackageName);
3317    }
3318
3319    @NonNull
3320    private Account[] getAccountsAsUser(
3321            String type,
3322            int userId,
3323            String callingPackage,
3324            int packageUid,
3325            String opPackageName) {
3326        int callingUid = Binder.getCallingUid();
3327        // Only allow the system process to read accounts of other users
3328        if (userId != UserHandle.getCallingUserId()
3329                && callingUid != Process.myUid()
3330                && mContext.checkCallingOrSelfPermission(
3331                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3332                    != PackageManager.PERMISSION_GRANTED) {
3333            throw new SecurityException("User " + UserHandle.getCallingUserId()
3334                    + " trying to get account for " + userId);
3335        }
3336
3337        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3338            Log.v(TAG, "getAccounts: accountType " + type
3339                    + ", caller's uid " + Binder.getCallingUid()
3340                    + ", pid " + Binder.getCallingPid());
3341        }
3342        // If the original calling app was using the framework account chooser activity, we'll
3343        // be passed in the original caller's uid here, which is what should be used for filtering.
3344        if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3345            callingUid = packageUid;
3346            opPackageName = callingPackage;
3347        }
3348
3349        List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3350                opPackageName);
3351        if (visibleAccountTypes.isEmpty()
3352                || (type != null && !visibleAccountTypes.contains(type))) {
3353            return new Account[0];
3354        } else if (visibleAccountTypes.contains(type)) {
3355            // Prune the list down to just the requested type.
3356            visibleAccountTypes = new ArrayList<>();
3357            visibleAccountTypes.add(type);
3358        } // else aggregate all the visible accounts (it won't matter if the
3359          // list is empty).
3360
3361        long identityToken = clearCallingIdentity();
3362        try {
3363            UserAccounts accounts = getUserAccounts(userId);
3364            return getAccountsInternal(
3365                    accounts,
3366                    callingUid,
3367                    callingPackage,
3368                    visibleAccountTypes);
3369        } finally {
3370            restoreCallingIdentity(identityToken);
3371        }
3372    }
3373
3374    @NonNull
3375    private Account[] getAccountsInternal(
3376            UserAccounts userAccounts,
3377            int callingUid,
3378            String callingPackage,
3379            List<String> visibleAccountTypes) {
3380        synchronized (userAccounts.cacheLock) {
3381            ArrayList<Account> visibleAccounts = new ArrayList<>();
3382            for (String visibleType : visibleAccountTypes) {
3383                Account[] accountsForType = getAccountsFromCacheLocked(
3384                        userAccounts, visibleType, callingUid, callingPackage);
3385                if (accountsForType != null) {
3386                    visibleAccounts.addAll(Arrays.asList(accountsForType));
3387                }
3388            }
3389            Account[] result = new Account[visibleAccounts.size()];
3390            for (int i = 0; i < visibleAccounts.size(); i++) {
3391                result[i] = visibleAccounts.get(i);
3392            }
3393            return result;
3394        }
3395    }
3396
3397    @Override
3398    public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3399        checkManageUsersPermission("addSharedAccountsFromParentUser");
3400        Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3401        for (Account account : accounts) {
3402            addSharedAccountAsUser(account, userId);
3403        }
3404    }
3405
3406    private boolean addSharedAccountAsUser(Account account, int userId) {
3407        userId = handleIncomingUser(userId);
3408        UserAccounts accounts = getUserAccounts(userId);
3409        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3410        ContentValues values = new ContentValues();
3411        values.put(ACCOUNTS_NAME, account.name);
3412        values.put(ACCOUNTS_TYPE, account.type);
3413        db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3414                new String[] {account.name, account.type});
3415        long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3416        if (accountId < 0) {
3417            Log.w(TAG, "insertAccountIntoDatabase: " + account
3418                    + ", skipping the DB insert failed");
3419            return false;
3420        }
3421        logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
3422        return true;
3423    }
3424
3425    @Override
3426    public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3427        userId = handleIncomingUser(userId);
3428        UserAccounts accounts = getUserAccounts(userId);
3429        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3430        long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
3431        final ContentValues values = new ContentValues();
3432        values.put(ACCOUNTS_NAME, newName);
3433        int r = db.update(
3434                TABLE_SHARED_ACCOUNTS,
3435                values,
3436                ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3437                new String[] { account.name, account.type });
3438        if (r > 0) {
3439            int callingUid = getCallingUid();
3440            logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3441                    sharedTableAccountId, accounts, callingUid);
3442            // Recursively rename the account.
3443            renameAccountInternal(accounts, account, newName);
3444        }
3445        return r > 0;
3446    }
3447
3448    @Override
3449    public boolean removeSharedAccountAsUser(Account account, int userId) {
3450        return removeSharedAccountAsUser(account, userId, getCallingUid());
3451    }
3452
3453    private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
3454        userId = handleIncomingUser(userId);
3455        UserAccounts accounts = getUserAccounts(userId);
3456        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3457        long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
3458        int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3459                new String[] {account.name, account.type});
3460        if (r > 0) {
3461            logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3462                    sharedTableAccountId, accounts, callingUid);
3463            removeAccountInternal(accounts, account, callingUid);
3464        }
3465        return r > 0;
3466    }
3467
3468    @Override
3469    public Account[] getSharedAccountsAsUser(int userId) {
3470        userId = handleIncomingUser(userId);
3471        UserAccounts accounts = getUserAccounts(userId);
3472        ArrayList<Account> accountList = new ArrayList<>();
3473        Cursor cursor = null;
3474        try {
3475            cursor = accounts.openHelper.getReadableDatabase()
3476                    .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3477                    null, null, null, null, null);
3478            if (cursor != null && cursor.moveToFirst()) {
3479                int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3480                int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3481                do {
3482                    accountList.add(new Account(cursor.getString(nameIndex),
3483                            cursor.getString(typeIndex)));
3484                } while (cursor.moveToNext());
3485            }
3486        } finally {
3487            if (cursor != null) {
3488                cursor.close();
3489            }
3490        }
3491        Account[] accountArray = new Account[accountList.size()];
3492        accountList.toArray(accountArray);
3493        return accountArray;
3494    }
3495
3496    @Override
3497    @NonNull
3498    public Account[] getAccounts(String type, String opPackageName) {
3499        return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
3500    }
3501
3502    @Override
3503    @NonNull
3504    public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
3505        int callingUid = Binder.getCallingUid();
3506        if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3507            throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3508                    + callingUid + " with uid=" + uid);
3509        }
3510        return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3511                opPackageName);
3512    }
3513
3514    @Override
3515    @NonNull
3516    public Account[] getAccountsByTypeForPackage(String type, String packageName,
3517            String opPackageName) {
3518        int packageUid = -1;
3519        try {
3520            packageUid = AppGlobals.getPackageManager().getPackageUid(
3521                    packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3522                    UserHandle.getCallingUserId());
3523        } catch (RemoteException re) {
3524            Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3525            return new Account[0];
3526        }
3527        return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3528                packageUid, opPackageName);
3529    }
3530
3531    @Override
3532    public void getAccountsByFeatures(
3533            IAccountManagerResponse response,
3534            String type,
3535            String[] features,
3536            String opPackageName) {
3537        int callingUid = Binder.getCallingUid();
3538        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3539            Log.v(TAG, "getAccounts: accountType " + type
3540                    + ", response " + response
3541                    + ", features " + stringArrayToString(features)
3542                    + ", caller's uid " + callingUid
3543                    + ", pid " + Binder.getCallingPid());
3544        }
3545        if (response == null) throw new IllegalArgumentException("response is null");
3546        if (type == null) throw new IllegalArgumentException("accountType is null");
3547        int userId = UserHandle.getCallingUserId();
3548
3549        List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3550                opPackageName);
3551        if (!visibleAccountTypes.contains(type)) {
3552            Bundle result = new Bundle();
3553            // Need to return just the accounts that are from matching signatures.
3554            result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3555            try {
3556                response.onResult(result);
3557            } catch (RemoteException e) {
3558                Log.e(TAG, "Cannot respond to caller do to exception." , e);
3559            }
3560            return;
3561        }
3562        long identityToken = clearCallingIdentity();
3563        try {
3564            UserAccounts userAccounts = getUserAccounts(userId);
3565            if (features == null || features.length == 0) {
3566                Account[] accounts;
3567                synchronized (userAccounts.cacheLock) {
3568                    accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
3569                }
3570                Bundle result = new Bundle();
3571                result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3572                onResult(response, result);
3573                return;
3574            }
3575            new GetAccountsByTypeAndFeatureSession(
3576                    userAccounts,
3577                    response,
3578                    type,
3579                    features,
3580                    callingUid).bind();
3581        } finally {
3582            restoreCallingIdentity(identityToken);
3583        }
3584    }
3585
3586    private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3587        Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3588                "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3589        try {
3590            if (cursor.moveToNext()) {
3591                return cursor.getLong(0);
3592            }
3593            return -1;
3594        } finally {
3595            cursor.close();
3596        }
3597    }
3598
3599    private long getAccountIdLocked(SQLiteDatabase db, Account account) {
3600        Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
3601                "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3602        try {
3603            if (cursor.moveToNext()) {
3604                return cursor.getLong(0);
3605            }
3606            return -1;
3607        } finally {
3608            cursor.close();
3609        }
3610    }
3611
3612    private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
3613        Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
3614                EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3615                new String[]{key}, null, null, null);
3616        try {
3617            if (cursor.moveToNext()) {
3618                return cursor.getLong(0);
3619            }
3620            return -1;
3621        } finally {
3622            cursor.close();
3623        }
3624    }
3625
3626    private abstract class Session extends IAccountAuthenticatorResponse.Stub
3627            implements IBinder.DeathRecipient, ServiceConnection {
3628        IAccountManagerResponse mResponse;
3629        final String mAccountType;
3630        final boolean mExpectActivityLaunch;
3631        final long mCreationTime;
3632        final String mAccountName;
3633        // Indicates if we need to add auth details(like last credential time)
3634        final boolean mAuthDetailsRequired;
3635        // If set, we need to update the last authenticated time. This is
3636        // currently
3637        // used on
3638        // successful confirming credentials.
3639        final boolean mUpdateLastAuthenticatedTime;
3640
3641        public int mNumResults = 0;
3642        private int mNumRequestContinued = 0;
3643        private int mNumErrors = 0;
3644
3645        IAccountAuthenticator mAuthenticator = null;
3646
3647        private final boolean mStripAuthTokenFromResult;
3648        protected final UserAccounts mAccounts;
3649
3650        public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3651                boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3652                boolean authDetailsRequired) {
3653            this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3654                    accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3655        }
3656
3657        public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3658                boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3659                boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
3660            super();
3661            //if (response == null) throw new IllegalArgumentException("response is null");
3662            if (accountType == null) throw new IllegalArgumentException("accountType is null");
3663            mAccounts = accounts;
3664            mStripAuthTokenFromResult = stripAuthTokenFromResult;
3665            mResponse = response;
3666            mAccountType = accountType;
3667            mExpectActivityLaunch = expectActivityLaunch;
3668            mCreationTime = SystemClock.elapsedRealtime();
3669            mAccountName = accountName;
3670            mAuthDetailsRequired = authDetailsRequired;
3671            mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
3672
3673            synchronized (mSessions) {
3674                mSessions.put(toString(), this);
3675            }
3676            if (response != null) {
3677                try {
3678                    response.asBinder().linkToDeath(this, 0 /* flags */);
3679                } catch (RemoteException e) {
3680                    mResponse = null;
3681                    binderDied();
3682                }
3683            }
3684        }
3685
3686        IAccountManagerResponse getResponseAndClose() {
3687            if (mResponse == null) {
3688                // this session has already been closed
3689                return null;
3690            }
3691            IAccountManagerResponse response = mResponse;
3692            close(); // this clears mResponse so we need to save the response before this call
3693            return response;
3694        }
3695
3696        /**
3697         * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3698         * security policy.
3699         *
3700         * In particular we want to make sure that the Authenticator doesn't try to trick users
3701         * into launching aribtrary intents on the device via by tricking to click authenticator
3702         * supplied entries in the system Settings app.
3703         */
3704        protected void checkKeyIntent(
3705                int authUid,
3706                Intent intent) throws SecurityException {
3707            long bid = Binder.clearCallingIdentity();
3708            try {
3709                PackageManager pm = mContext.getPackageManager();
3710                ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3711                ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3712                int targetUid = targetActivityInfo.applicationInfo.uid;
3713                if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3714                    String pkgName = targetActivityInfo.packageName;
3715                    String activityName = targetActivityInfo.name;
3716                    String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3717                            + "does not share a signature with the supplying authenticator (%s).";
3718                    throw new SecurityException(
3719                            String.format(tmpl, activityName, pkgName, mAccountType));
3720                }
3721            } finally {
3722                Binder.restoreCallingIdentity(bid);
3723            }
3724        }
3725
3726        private void close() {
3727            synchronized (mSessions) {
3728                if (mSessions.remove(toString()) == null) {
3729                    // the session was already closed, so bail out now
3730                    return;
3731                }
3732            }
3733            if (mResponse != null) {
3734                // stop listening for response deaths
3735                mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3736
3737                // clear this so that we don't accidentally send any further results
3738                mResponse = null;
3739            }
3740            cancelTimeout();
3741            unbind();
3742        }
3743
3744        @Override
3745        public void binderDied() {
3746            mResponse = null;
3747            close();
3748        }
3749
3750        protected String toDebugString() {
3751            return toDebugString(SystemClock.elapsedRealtime());
3752        }
3753
3754        protected String toDebugString(long now) {
3755            return "Session: expectLaunch " + mExpectActivityLaunch
3756                    + ", connected " + (mAuthenticator != null)
3757                    + ", stats (" + mNumResults + "/" + mNumRequestContinued
3758                    + "/" + mNumErrors + ")"
3759                    + ", lifetime " + ((now - mCreationTime) / 1000.0);
3760        }
3761
3762        void bind() {
3763            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3764                Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3765            }
3766            if (!bindToAuthenticator(mAccountType)) {
3767                Log.d(TAG, "bind attempt failed for " + toDebugString());
3768                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
3769            }
3770        }
3771
3772        private void unbind() {
3773            if (mAuthenticator != null) {
3774                mAuthenticator = null;
3775                mContext.unbindService(this);
3776            }
3777        }
3778
3779        public void cancelTimeout() {
3780            mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3781        }
3782
3783        @Override
3784        public void onServiceConnected(ComponentName name, IBinder service) {
3785            mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
3786            try {
3787                run();
3788            } catch (RemoteException e) {
3789                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3790                        "remote exception");
3791            }
3792        }
3793
3794        @Override
3795        public void onServiceDisconnected(ComponentName name) {
3796            mAuthenticator = null;
3797            IAccountManagerResponse response = getResponseAndClose();
3798            if (response != null) {
3799                try {
3800                    response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3801                            "disconnected");
3802                } catch (RemoteException e) {
3803                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3804                        Log.v(TAG, "Session.onServiceDisconnected: "
3805                                + "caught RemoteException while responding", e);
3806                    }
3807                }
3808            }
3809        }
3810
3811        public abstract void run() throws RemoteException;
3812
3813        public void onTimedOut() {
3814            IAccountManagerResponse response = getResponseAndClose();
3815            if (response != null) {
3816                try {
3817                    response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3818                            "timeout");
3819                } catch (RemoteException e) {
3820                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3821                        Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3822                                e);
3823                    }
3824                }
3825            }
3826        }
3827
3828        @Override
3829        public void onResult(Bundle result) {
3830            Bundle.setDefusable(result, true);
3831            mNumResults++;
3832            Intent intent = null;
3833            if (result != null) {
3834                boolean isSuccessfulConfirmCreds = result.getBoolean(
3835                        AccountManager.KEY_BOOLEAN_RESULT, false);
3836                boolean isSuccessfulUpdateCredsOrAddAccount =
3837                        result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3838                        && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
3839                // We should only update lastAuthenticated time, if
3840                // mUpdateLastAuthenticatedTime is true and the confirmRequest
3841                // or updateRequest was successful
3842                boolean needUpdate = mUpdateLastAuthenticatedTime
3843                        && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
3844                if (needUpdate || mAuthDetailsRequired) {
3845                    boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3846                    if (needUpdate && accountPresent) {
3847                        updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3848                    }
3849                    if (mAuthDetailsRequired) {
3850                        long lastAuthenticatedTime = -1;
3851                        if (accountPresent) {
3852                            lastAuthenticatedTime = DatabaseUtils.longForQuery(
3853                                    mAccounts.openHelper.getReadableDatabase(),
3854                                    "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3855                                            + " FROM " +
3856                                            TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3857                                            + ACCOUNTS_TYPE + "=?",
3858                                    new String[] {
3859                                            mAccountName, mAccountType
3860                                    });
3861                        }
3862                        result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
3863                                lastAuthenticatedTime);
3864                    }
3865                }
3866            }
3867            if (result != null
3868                    && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
3869                checkKeyIntent(
3870                        Binder.getCallingUid(),
3871                        intent);
3872            }
3873            if (result != null
3874                    && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
3875                String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3876                String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
3877                if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3878                    Account account = new Account(accountName, accountType);
3879                    cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3880                            new UserHandle(mAccounts.userId));
3881                }
3882            }
3883            IAccountManagerResponse response;
3884            if (mExpectActivityLaunch && result != null
3885                    && result.containsKey(AccountManager.KEY_INTENT)) {
3886                response = mResponse;
3887            } else {
3888                response = getResponseAndClose();
3889            }
3890            if (response != null) {
3891                try {
3892                    if (result == null) {
3893                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3894                            Log.v(TAG, getClass().getSimpleName()
3895                                    + " calling onError() on response " + response);
3896                        }
3897                        response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
3898                                "null bundle returned");
3899                    } else {
3900                        if (mStripAuthTokenFromResult) {
3901                            result.remove(AccountManager.KEY_AUTHTOKEN);
3902                        }
3903                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3904                            Log.v(TAG, getClass().getSimpleName()
3905                                    + " calling onResult() on response " + response);
3906                        }
3907                        if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3908                                (intent == null)) {
3909                            // All AccountManager error codes are greater than 0
3910                            response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3911                                    result.getString(AccountManager.KEY_ERROR_MESSAGE));
3912                        } else {
3913                            response.onResult(result);
3914                        }
3915                    }
3916                } catch (RemoteException e) {
3917                    // if the caller is dead then there is no one to care about remote exceptions
3918                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3919                        Log.v(TAG, "failure while notifying response", e);
3920                    }
3921                }
3922            }
3923        }
3924
3925        @Override
3926        public void onRequestContinued() {
3927            mNumRequestContinued++;
3928        }
3929
3930        @Override
3931        public void onError(int errorCode, String errorMessage) {
3932            mNumErrors++;
3933            IAccountManagerResponse response = getResponseAndClose();
3934            if (response != null) {
3935                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3936                    Log.v(TAG, getClass().getSimpleName()
3937                            + " calling onError() on response " + response);
3938                }
3939                try {
3940                    response.onError(errorCode, errorMessage);
3941                } catch (RemoteException e) {
3942                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
3943                        Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3944                    }
3945                }
3946            } else {
3947                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3948                    Log.v(TAG, "Session.onError: already closed");
3949                }
3950            }
3951        }
3952
3953        /**
3954         * find the component name for the authenticator and initiate a bind
3955         * if no authenticator or the bind fails then return false, otherwise return true
3956         */
3957        private boolean bindToAuthenticator(String authenticatorType) {
3958            final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3959            authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3960                    AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
3961            if (authenticatorInfo == null) {
3962                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3963                    Log.v(TAG, "there is no authenticator for " + authenticatorType
3964                            + ", bailing out");
3965                }
3966                return false;
3967            }
3968
3969            final ActivityManager am = mContext.getSystemService(ActivityManager.class);
3970            if (am.isUserRunningAndLocked(mAccounts.userId)
3971                    && !authenticatorInfo.componentInfo.directBootAware) {
3972                Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
3973                        + " which isn't encryption aware");
3974                return false;
3975            }
3976
3977            Intent intent = new Intent();
3978            intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3979            intent.setComponent(authenticatorInfo.componentName);
3980            if (Log.isLoggable(TAG, Log.VERBOSE)) {
3981                Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3982            }
3983            if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3984                    UserHandle.of(mAccounts.userId))) {
3985                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3986                    Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3987                }
3988                return false;
3989            }
3990
3991            return true;
3992        }
3993    }
3994
3995    private class MessageHandler extends Handler {
3996        MessageHandler(Looper looper) {
3997            super(looper);
3998        }
3999
4000        @Override
4001        public void handleMessage(Message msg) {
4002            switch (msg.what) {
4003                case MESSAGE_TIMED_OUT:
4004                    Session session = (Session)msg.obj;
4005                    session.onTimedOut();
4006                    break;
4007
4008                case MESSAGE_COPY_SHARED_ACCOUNT:
4009                    copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
4010                    break;
4011
4012                default:
4013                    throw new IllegalStateException("unhandled message: " + msg.what);
4014            }
4015        }
4016    }
4017
4018    static String getPreNDatabaseName(int userId) {
4019        File systemDir = Environment.getDataSystemDirectory();
4020        File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4021                PRE_N_DATABASE_NAME);
4022        if (userId == 0) {
4023            // Migrate old file, if it exists, to the new location.
4024            // Make sure the new file doesn't already exist. A dummy file could have been
4025            // accidentally created in the old location, causing the new one to become corrupted
4026            // as well.
4027            File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
4028            if (oldFile.exists() && !databaseFile.exists()) {
4029                // Check for use directory; create if it doesn't exist, else renameTo will fail
4030                File userDir = Environment.getUserSystemDirectory(userId);
4031                if (!userDir.exists()) {
4032                    if (!userDir.mkdirs()) {
4033                        throw new IllegalStateException("User dir cannot be created: " + userDir);
4034                    }
4035                }
4036                if (!oldFile.renameTo(databaseFile)) {
4037                    throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4038                }
4039            }
4040        }
4041        return databaseFile.getPath();
4042    }
4043
4044    static String getDeDatabaseName(int userId) {
4045        File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4046                DE_DATABASE_NAME);
4047        return databaseFile.getPath();
4048    }
4049
4050    static String getCeDatabaseName(int userId) {
4051        File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4052                CE_DATABASE_NAME);
4053        return databaseFile.getPath();
4054    }
4055
4056    private static class DebugDbHelper{
4057        private DebugDbHelper() {
4058        }
4059
4060        private static String TABLE_DEBUG = "debug_table";
4061
4062        // Columns for the table
4063        private static String ACTION_TYPE = "action_type";
4064        private static String TIMESTAMP = "time";
4065        private static String CALLER_UID = "caller_uid";
4066        private static String TABLE_NAME = "table_name";
4067        private static String KEY = "primary_key";
4068
4069        // These actions correspond to the occurrence of real actions. Since
4070        // these are called by the authenticators, the uid associated will be
4071        // of the authenticator.
4072        private static String ACTION_SET_PASSWORD = "action_set_password";
4073        private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4074        private static String ACTION_ACCOUNT_ADD = "action_account_add";
4075        private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
4076        private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4077        private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4078
4079        // These actions don't necessarily correspond to any action on
4080        // accountDb taking place. As an example, there might be a request for
4081        // addingAccount, which might not lead to addition of account on grounds
4082        // of bad authentication. We will still be logging it to keep track of
4083        // who called.
4084        private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4085        private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
4086
4087        //This action doesn't add account to accountdb. Account is only
4088        // added in finishSession which may be in a different user profile.
4089        private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
4090        private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4091                "action_called_account_session_finish";
4092
4093        private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4094
4095        private static void createDebugTable(SQLiteDatabase db) {
4096            db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4097                    + ACCOUNTS_ID + " INTEGER,"
4098                    + ACTION_TYPE + " TEXT NOT NULL, "
4099                    + TIMESTAMP + " DATETIME,"
4100                    + CALLER_UID + " INTEGER NOT NULL,"
4101                    + TABLE_NAME + " TEXT NOT NULL,"
4102                    + KEY + " INTEGER PRIMARY KEY)");
4103            db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4104        }
4105    }
4106
4107    private void logRecord(UserAccounts accounts, String action, String tableName) {
4108        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4109        logRecord(db, action, tableName, -1, accounts);
4110    }
4111
4112    private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4113        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4114        logRecord(db, action, tableName, -1, accounts, uid);
4115    }
4116
4117    /*
4118     * This function receives an opened writable database.
4119     */
4120    private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4121            UserAccounts userAccount) {
4122        logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4123    }
4124
4125    /*
4126     * This function receives an opened writable database.
4127     */
4128    private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4129            UserAccounts userAccount, int callingUid) {
4130        SQLiteStatement logStatement = userAccount.statementForLogging;
4131        logStatement.bindLong(1, accountId);
4132        logStatement.bindString(2, action);
4133        logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4134        logStatement.bindLong(4, callingUid);
4135        logStatement.bindString(5, tableName);
4136        logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4137        logStatement.execute();
4138        logStatement.clearBindings();
4139        userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4140                % MAX_DEBUG_DB_SIZE;
4141    }
4142
4143    /*
4144     * This should only be called once to compile the sql statement for logging
4145     * and to find the insertion point.
4146     */
4147    private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4148            UserAccounts userAccount) {
4149        // Initialize the count if not done earlier.
4150        int size = (int) getDebugTableRowCount(db);
4151        if (size >= MAX_DEBUG_DB_SIZE) {
4152            // Table is full, and we need to find the point where to insert.
4153            userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4154        } else {
4155            userAccount.debugDbInsertionPoint = size;
4156        }
4157        compileSqlStatementForLogging(db, userAccount);
4158    }
4159
4160    private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4161        String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4162                + " VALUES (?,?,?,?,?,?)";
4163        userAccount.statementForLogging = db.compileStatement(sql);
4164    }
4165
4166    private long getDebugTableRowCount(SQLiteDatabase db) {
4167        String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4168        return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4169    }
4170
4171    /*
4172     * Finds the row key where the next insertion should take place. This should
4173     * be invoked only if the table has reached its full capacity.
4174     */
4175    private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4176        // This query finds the smallest timestamp value (and if 2 records have
4177        // same timestamp, the choose the lower id).
4178        String queryCountDebugDbRows = new StringBuilder()
4179                .append("SELECT ").append(DebugDbHelper.KEY)
4180                .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4181                .append(" ORDER BY ")
4182                .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4183                .append(" LIMIT 1")
4184                .toString();
4185        return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4186    }
4187
4188    static class PreNDatabaseHelper extends SQLiteOpenHelper {
4189
4190        private final Context mContext;
4191        private final int mUserId;
4192
4193        public PreNDatabaseHelper(Context context, int userId) {
4194            super(context, AccountManagerService.getPreNDatabaseName(userId), null,
4195                    PRE_N_DATABASE_VERSION);
4196            mContext = context;
4197            mUserId = userId;
4198        }
4199
4200        @Override
4201        public void onCreate(SQLiteDatabase db) {
4202            // We use PreNDatabaseHelper only if pre-N db exists
4203            throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
4204        }
4205
4206        private void createSharedAccountsTable(SQLiteDatabase db) {
4207            db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4208                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4209                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
4210                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4211                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4212        }
4213
4214        private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4215            db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4216                    + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4217        }
4218
4219        private void addOldAccountNameColumn(SQLiteDatabase db) {
4220            db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4221        }
4222
4223        private void addDebugTable(SQLiteDatabase db) {
4224            DebugDbHelper.createDebugTable(db);
4225        }
4226
4227        private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4228            db.execSQL(""
4229                    + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4230                    + " BEGIN"
4231                    + "   DELETE FROM " + TABLE_AUTHTOKENS
4232                    + "     WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4233                    + "   DELETE FROM " + TABLE_EXTRAS
4234                    + "     WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4235                    + "   DELETE FROM " + TABLE_GRANTS
4236                    + "     WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4237                    + " END");
4238        }
4239
4240        private void createGrantsTable(SQLiteDatabase db) {
4241            db.execSQL("CREATE TABLE " + TABLE_GRANTS + " (  "
4242                    + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4243                    + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL,  "
4244                    + GRANTS_GRANTEE_UID + " INTEGER NOT NULL,  "
4245                    + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4246                    +   "," + GRANTS_GRANTEE_UID + "))");
4247        }
4248
4249        private void populateMetaTableWithAuthTypeAndUID(
4250                SQLiteDatabase db,
4251                Map<String, Integer> authTypeAndUIDMap) {
4252            Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4253            while (iterator.hasNext()) {
4254                Entry<String, Integer> entry = iterator.next();
4255                ContentValues values = new ContentValues();
4256                values.put(META_KEY,
4257                        META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4258                values.put(META_VALUE, entry.getValue());
4259                db.insert(TABLE_META, null, values);
4260            }
4261        }
4262
4263        /**
4264         * Pre-N database may need an upgrade before splitting
4265         */
4266        @Override
4267        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4268            Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4269
4270            if (oldVersion == 1) {
4271                // no longer need to do anything since the work is done
4272                // when upgrading from version 2
4273                oldVersion++;
4274            }
4275
4276            if (oldVersion == 2) {
4277                createGrantsTable(db);
4278                db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4279                createAccountsDeletionTrigger(db);
4280                oldVersion++;
4281            }
4282
4283            if (oldVersion == 3) {
4284                db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4285                        " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4286                oldVersion++;
4287            }
4288
4289            if (oldVersion == 4) {
4290                createSharedAccountsTable(db);
4291                oldVersion++;
4292            }
4293
4294            if (oldVersion == 5) {
4295                addOldAccountNameColumn(db);
4296                oldVersion++;
4297            }
4298
4299            if (oldVersion == 6) {
4300                addLastSuccessfullAuthenticatedTimeColumn(db);
4301                oldVersion++;
4302            }
4303
4304            if (oldVersion == 7) {
4305                addDebugTable(db);
4306                oldVersion++;
4307            }
4308
4309            if (oldVersion == 8) {
4310                populateMetaTableWithAuthTypeAndUID(
4311                        db,
4312                        AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4313                oldVersion++;
4314            }
4315
4316            if (oldVersion != newVersion) {
4317                Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4318            }
4319        }
4320
4321        @Override
4322        public void onOpen(SQLiteDatabase db) {
4323            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4324        }
4325    }
4326
4327    static class DeDatabaseHelper extends SQLiteOpenHelper {
4328
4329        private final int mUserId;
4330        private volatile boolean mCeAttached;
4331
4332        private DeDatabaseHelper(Context context, int userId) {
4333            super(context, getDeDatabaseName(userId), null, DE_DATABASE_VERSION);
4334            mUserId = userId;
4335        }
4336
4337        /**
4338         * This call needs to be made while the mCacheLock is held. The way to
4339         * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4340         * @param db The database.
4341         */
4342        @Override
4343        public void onCreate(SQLiteDatabase db) {
4344            Log.i(TAG, "Creating DE database for user " + mUserId);
4345            db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4346                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4347                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
4348                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4349                    + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4350                    + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4351                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4352
4353            db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4354                    + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4355                    + META_VALUE + " TEXT)");
4356
4357            createGrantsTable(db);
4358            createSharedAccountsTable(db);
4359            createAccountsDeletionTrigger(db);
4360            DebugDbHelper.createDebugTable(db);
4361        }
4362
4363        private void createSharedAccountsTable(SQLiteDatabase db) {
4364            db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4365                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4366                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
4367                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4368                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4369        }
4370
4371        private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4372            db.execSQL(""
4373                    + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4374                    + " BEGIN"
4375                    + "   DELETE FROM " + TABLE_GRANTS
4376                    + "     WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4377                    + " END");
4378        }
4379
4380        private void createGrantsTable(SQLiteDatabase db) {
4381            db.execSQL("CREATE TABLE " + TABLE_GRANTS + " (  "
4382                    + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4383                    + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL,  "
4384                    + GRANTS_GRANTEE_UID + " INTEGER NOT NULL,  "
4385                    + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4386                    +   "," + GRANTS_GRANTEE_UID + "))");
4387        }
4388
4389        @Override
4390        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4391            Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4392
4393            if (oldVersion != newVersion) {
4394                Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4395            }
4396        }
4397
4398        public void attachCeDatabase() {
4399            File ceDbFile = new File(getCeDatabaseName(mUserId));
4400            SQLiteDatabase db = getWritableDatabase();
4401            db.execSQL("ATTACH DATABASE '" +  ceDbFile.getPath()+ "' AS ceDb");
4402            mCeAttached = true;
4403        }
4404
4405        public boolean isCeDatabaseAttached() {
4406            return mCeAttached;
4407        }
4408
4409
4410        public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4411            if(!mCeAttached) {
4412                Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user "
4413                        + mUserId + " is still locked ", new Throwable());
4414            }
4415            return super.getReadableDatabase();
4416        }
4417
4418        public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4419            if(!mCeAttached) {
4420                Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
4421                        + " is still locked ", new Throwable());
4422            }
4423            return super.getWritableDatabase();
4424        }
4425
4426        @Override
4427        public void onOpen(SQLiteDatabase db) {
4428            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4429        }
4430
4431        private void migratePreNDbToDe(File preNDbFile) {
4432            Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4433            SQLiteDatabase db = getWritableDatabase();
4434            db.execSQL("ATTACH DATABASE '" +  preNDbFile.getPath() + "' AS preNDb");
4435            db.beginTransaction();
4436            // Copy accounts fields
4437            db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4438                    + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4439                    + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4440                    + ") "
4441                    + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4442                    + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4443                    + " FROM preNDb." + TABLE_ACCOUNTS);
4444            // Copy SHARED_ACCOUNTS
4445            db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4446                    + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4447                    "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4448                    + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4449            // Copy DEBUG_TABLE
4450            db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4451                    + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4452                    + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4453                    + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4454                    "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4455                    + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4456                    + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4457                    + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4458            // Copy GRANTS
4459            db.execSQL("INSERT INTO " + TABLE_GRANTS
4460                    + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4461                    + GRANTS_GRANTEE_UID + ") " +
4462                    "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4463                    + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4464            // Copy META
4465            db.execSQL("INSERT INTO " + TABLE_META
4466                    + "(" + META_KEY + "," + META_VALUE + ") "
4467                    + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4468            db.setTransactionSuccessful();
4469            db.endTransaction();
4470
4471            db.execSQL("DETACH DATABASE preNDb");
4472        }
4473
4474        static DeDatabaseHelper create(Context context, int userId) {
4475            File oldDb = new File(getPreNDatabaseName(userId));
4476            File newDb = new File(getDeDatabaseName(userId));
4477            boolean newDbExists = newDb.exists();
4478            DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId);
4479            // If the db just created, and there is a legacy db, migrate it
4480            if (!newDbExists && oldDb.exists()) {
4481                // Migrate legacy db to the latest version -  PRE_N_DATABASE_VERSION
4482                PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId);
4483                // Open the database to force upgrade if required
4484                preNDatabaseHelper.getWritableDatabase();
4485                preNDatabaseHelper.close();
4486                // Move data without SPII to DE
4487                deDatabaseHelper.migratePreNDbToDe(oldDb);
4488            }
4489            return deDatabaseHelper;
4490        }
4491    }
4492
4493    static class CeDatabaseHelper extends SQLiteOpenHelper {
4494
4495        public CeDatabaseHelper(Context context, int userId) {
4496            super(context, getCeDatabaseName(userId), null, CE_DATABASE_VERSION);
4497        }
4498
4499        /**
4500         * This call needs to be made while the mCacheLock is held.
4501         * @param db The database.
4502         */
4503        @Override
4504        public void onCreate(SQLiteDatabase db) {
4505            Log.i(TAG, "Creating CE database " + getDatabaseName());
4506            db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4507                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4508                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
4509                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4510                    + ACCOUNTS_PASSWORD + " TEXT, "
4511                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4512
4513            db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " (  "
4514                    + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,  "
4515                    + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4516                    + AUTHTOKENS_TYPE + " TEXT NOT NULL,  "
4517                    + AUTHTOKENS_AUTHTOKEN + " TEXT,  "
4518                    + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4519
4520            db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4521                    + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4522                    + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4523                    + EXTRAS_KEY + " TEXT NOT NULL, "
4524                    + EXTRAS_VALUE + " TEXT, "
4525                    + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4526
4527            createAccountsDeletionTrigger(db);
4528        }
4529
4530        private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4531            db.execSQL(""
4532                    + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4533                    + " BEGIN"
4534                    + "   DELETE FROM " + TABLE_AUTHTOKENS
4535                    + "     WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4536                    + "   DELETE FROM " + TABLE_EXTRAS
4537                    + "     WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4538                    + " END");
4539        }
4540
4541        @Override
4542        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4543            Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4544
4545            if (oldVersion == 9) {
4546                if (Log.isLoggable(TAG, Log.VERBOSE)) {
4547                    Log.v(TAG, "onUpgrade upgrading to v10");
4548                }
4549                db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4550                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4551                // Recreate the trigger, since the old one references the table to be removed
4552                db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4553                createAccountsDeletionTrigger(db);
4554                db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4555                db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4556                oldVersion ++;
4557            }
4558
4559            if (oldVersion != newVersion) {
4560                Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4561            }
4562        }
4563
4564        @Override
4565        public void onOpen(SQLiteDatabase db) {
4566            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4567        }
4568
4569        static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4570                String type) {
4571            Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4572                    ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4573                    new String[]{name, type}, null, null, null);
4574            try {
4575                if (cursor.moveToNext()) {
4576                    return cursor.getString(0);
4577                }
4578                return null;
4579            } finally {
4580                cursor.close();
4581            }
4582        }
4583
4584        /**
4585         * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4586         * it also performs migration to the new CE database.
4587         * @param context
4588         * @param userId id of the user where the database is located
4589         */
4590        static CeDatabaseHelper create(Context context, int userId) {
4591
4592            File oldDatabaseFile = new File(getPreNDatabaseName(userId));
4593            File ceDatabaseFile = new File(getCeDatabaseName(userId));
4594            boolean newDbExists = ceDatabaseFile.exists();
4595            if (Log.isLoggable(TAG, Log.VERBOSE)) {
4596                Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
4597                        + oldDatabaseFile.exists() + " newDbExists=" + newDbExists);
4598            }
4599            boolean removeOldDb = false;
4600            if (!newDbExists && oldDatabaseFile.exists()) {
4601                removeOldDb = migratePreNDbToCe(oldDatabaseFile, ceDatabaseFile);
4602            }
4603            // Try to open and upgrade if necessary
4604            CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, userId);
4605            ceHelper.getWritableDatabase();
4606            ceHelper.close();
4607            if (removeOldDb) {
4608                // TODO STOPSHIP - backup file during testing. Remove file before the release
4609                Log.i(TAG, "Migration complete - creating backup of old db " + oldDatabaseFile);
4610                renameToBakFile(oldDatabaseFile);
4611            }
4612            return ceHelper;
4613        }
4614
4615        private static void renameToBakFile(File file) {
4616            File bakFile = new File(file.getPath() + ".bak");
4617            if (!file.renameTo(bakFile)) {
4618                Log.e(TAG, "Cannot move file to " + bakFile);
4619            }
4620        }
4621
4622        private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
4623            Log.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
4624            try {
4625                FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4626            } catch (IOException e) {
4627                Log.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
4628                // Try to remove potentially damaged file if I/O error occurred
4629                deleteDbFileWarnIfFailed(ceDbFile);
4630                return false;
4631            }
4632            return true;
4633        }
4634    }
4635
4636    public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
4637        return asBinder();
4638    }
4639
4640    /**
4641     * Searches array of arguments for the specified string
4642     * @param args array of argument strings
4643     * @param value value to search for
4644     * @return true if the value is contained in the array
4645     */
4646    private static boolean scanArgs(String[] args, String value) {
4647        if (args != null) {
4648            for (String arg : args) {
4649                if (value.equals(arg)) {
4650                    return true;
4651                }
4652            }
4653        }
4654        return false;
4655    }
4656
4657    @Override
4658    protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
4659        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4660                != PackageManager.PERMISSION_GRANTED) {
4661            fout.println("Permission Denial: can't dump AccountsManager from from pid="
4662                    + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4663                    + " without permission " + android.Manifest.permission.DUMP);
4664            return;
4665        }
4666        final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
4667        final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, "  ");
4668
4669        final List<UserInfo> users = getUserManager().getUsers();
4670        for (UserInfo user : users) {
4671            ipw.println("User " + user + ":");
4672            ipw.increaseIndent();
4673            dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4674            ipw.println();
4675            ipw.decreaseIndent();
4676        }
4677    }
4678
4679    private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4680            String[] args, boolean isCheckinRequest) {
4681        synchronized (userAccounts.cacheLock) {
4682            final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
4683
4684            if (isCheckinRequest) {
4685                // This is a checkin request. *Only* upload the account types and the count of each.
4686                Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4687                        null, null, ACCOUNTS_TYPE, null, null);
4688                try {
4689                    while (cursor.moveToNext()) {
4690                        // print type,count
4691                        fout.println(cursor.getString(0) + "," + cursor.getString(1));
4692                    }
4693                } finally {
4694                    if (cursor != null) {
4695                        cursor.close();
4696                    }
4697                }
4698            } else {
4699                Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
4700                        Process.myUid(), null);
4701                fout.println("Accounts: " + accounts.length);
4702                for (Account account : accounts) {
4703                    fout.println("  " + account);
4704                }
4705
4706                // Add debug information.
4707                fout.println();
4708                Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4709                        null, null, null, null, DebugDbHelper.TIMESTAMP);
4710                fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4711                fout.println("Accounts History");
4712                try {
4713                    while (cursor.moveToNext()) {
4714                        // print type,count
4715                        fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4716                                cursor.getString(2) + "," + cursor.getString(3) + ","
4717                                + cursor.getString(4) + "," + cursor.getString(5));
4718                    }
4719                } finally {
4720                    cursor.close();
4721                }
4722
4723                fout.println();
4724                synchronized (mSessions) {
4725                    final long now = SystemClock.elapsedRealtime();
4726                    fout.println("Active Sessions: " + mSessions.size());
4727                    for (Session session : mSessions.values()) {
4728                        fout.println("  " + session.toDebugString(now));
4729                    }
4730                }
4731
4732                fout.println();
4733                mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
4734            }
4735        }
4736    }
4737
4738    private void doNotification(UserAccounts accounts, Account account, CharSequence message,
4739            Intent intent, int userId) {
4740        long identityToken = clearCallingIdentity();
4741        try {
4742            if (Log.isLoggable(TAG, Log.VERBOSE)) {
4743                Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4744            }
4745
4746            if (intent.getComponent() != null &&
4747                    GrantCredentialsPermissionActivity.class.getName().equals(
4748                            intent.getComponent().getClassName())) {
4749                createNoCredentialsPermissionNotification(account, intent, userId);
4750            } else {
4751                final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
4752                intent.addCategory(String.valueOf(notificationId));
4753                UserHandle user = new UserHandle(userId);
4754                Context contextForUser = getContextForUser(user);
4755                final String notificationTitleFormat =
4756                        contextForUser.getText(R.string.notification_title).toString();
4757                Notification n = new Notification.Builder(contextForUser)
4758                        .setWhen(0)
4759                        .setSmallIcon(android.R.drawable.stat_sys_warning)
4760                        .setColor(contextForUser.getColor(
4761                                com.android.internal.R.color.system_notification_accent_color))
4762                        .setContentTitle(String.format(notificationTitleFormat, account.name))
4763                        .setContentText(message)
4764                        .setContentIntent(PendingIntent.getActivityAsUser(
4765                                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4766                                null, user))
4767                        .build();
4768                installNotification(notificationId, n, user);
4769            }
4770        } finally {
4771            restoreCallingIdentity(identityToken);
4772        }
4773    }
4774
4775    protected void installNotification(final int notificationId, final Notification n,
4776            UserHandle user) {
4777        ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
4778                .notifyAsUser(null, notificationId, n, user);
4779    }
4780
4781    protected void cancelNotification(int id, UserHandle user) {
4782        long identityToken = clearCallingIdentity();
4783        try {
4784            ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
4785                .cancelAsUser(null, id, user);
4786        } finally {
4787            restoreCallingIdentity(identityToken);
4788        }
4789    }
4790
4791    private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4792        for (String perm : permissions) {
4793            if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4794                if (Log.isLoggable(TAG, Log.VERBOSE)) {
4795                    Log.v(TAG, "  caller uid " + callingUid + " has " + perm);
4796                }
4797                final int opCode = AppOpsManager.permissionToOpCode(perm);
4798                if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4799                        opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4800                    return true;
4801                }
4802            }
4803        }
4804        return false;
4805    }
4806
4807    private int handleIncomingUser(int userId) {
4808        try {
4809            return ActivityManagerNative.getDefault().handleIncomingUser(
4810                    Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4811        } catch (RemoteException re) {
4812            // Shouldn't happen, local.
4813        }
4814        return userId;
4815    }
4816
4817    private boolean isPrivileged(int callingUid) {
4818        final int callingUserId = UserHandle.getUserId(callingUid);
4819
4820        final PackageManager userPackageManager;
4821        try {
4822            userPackageManager = mContext.createPackageContextAsUser(
4823                    "android", 0, new UserHandle(callingUserId)).getPackageManager();
4824        } catch (NameNotFoundException e) {
4825            return false;
4826        }
4827
4828        String[] packages = userPackageManager.getPackagesForUid(callingUid);
4829        for (String name : packages) {
4830            try {
4831                PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
4832                if (packageInfo != null
4833                        && (packageInfo.applicationInfo.privateFlags
4834                                & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4835                    return true;
4836                }
4837            } catch (PackageManager.NameNotFoundException e) {
4838                return false;
4839            }
4840        }
4841        return false;
4842    }
4843
4844    private boolean permissionIsGranted(
4845            Account account, String authTokenType, int callerUid, int userId) {
4846        final boolean isPrivileged = isPrivileged(callerUid);
4847        final boolean fromAuthenticator = account != null
4848                && isAccountManagedByCaller(account.type, callerUid, userId);
4849        final boolean hasExplicitGrants = account != null
4850                && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
4851        if (Log.isLoggable(TAG, Log.VERBOSE)) {
4852            Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
4853                    + callerUid + ", " + account
4854                    + ": is authenticator? " + fromAuthenticator
4855                    + ", has explicit permission? " + hasExplicitGrants);
4856        }
4857        return fromAuthenticator || hasExplicitGrants || isPrivileged;
4858    }
4859
4860    private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4861            String opPackageName) {
4862        if (accountType == null) {
4863            return false;
4864        } else {
4865            return getTypesVisibleToCaller(callingUid, userId,
4866                    opPackageName).contains(accountType);
4867        }
4868    }
4869
4870    private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4871        if (accountType == null) {
4872            return false;
4873        } else {
4874            return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4875        }
4876    }
4877
4878    private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4879            String opPackageName) {
4880        boolean isPermitted =
4881                isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
4882                        Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
4883        return getTypesForCaller(callingUid, userId, isPermitted);
4884    }
4885
4886    private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4887        return getTypesForCaller(callingUid, userId, false);
4888    }
4889
4890    private List<String> getTypesForCaller(
4891            int callingUid, int userId, boolean isOtherwisePermitted) {
4892        List<String> managedAccountTypes = new ArrayList<>();
4893        long identityToken = Binder.clearCallingIdentity();
4894        Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4895        try {
4896            serviceInfos = mAuthenticatorCache.getAllServices(userId);
4897        } finally {
4898            Binder.restoreCallingIdentity(identityToken);
4899        }
4900        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
4901                serviceInfos) {
4902            final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4903            if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4904                managedAccountTypes.add(serviceInfo.type.type);
4905            }
4906        }
4907        return managedAccountTypes;
4908    }
4909
4910    private boolean isAccountPresentForCaller(String accountName, String accountType) {
4911        if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4912            for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4913                if (account.name.equals(accountName)) {
4914                    return true;
4915                }
4916            }
4917        }
4918        return false;
4919    }
4920
4921    private static void checkManageUsersPermission(String message) {
4922        if (ActivityManager.checkComponentPermission(
4923                android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4924                != PackageManager.PERMISSION_GRANTED) {
4925            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4926        }
4927    }
4928
4929    private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4930            int callerUid) {
4931        if (callerUid == Process.SYSTEM_UID) {
4932            return true;
4933        }
4934        UserAccounts accounts = getUserAccountsForCaller();
4935        synchronized (accounts.cacheLock) {
4936            final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4937            String[] args = { String.valueOf(callerUid), authTokenType,
4938                    account.name, account.type};
4939            final boolean permissionGranted =
4940                    DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4941            if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4942                // TODO: Skip this check when running automated tests. Replace this
4943                // with a more general solution.
4944                Log.d(TAG, "no credentials permission for usage of " + account + ", "
4945                        + authTokenType + " by uid " + callerUid
4946                        + " but ignoring since device is in test harness.");
4947                return true;
4948            }
4949            return permissionGranted;
4950        }
4951    }
4952
4953    private boolean isSystemUid(int callingUid) {
4954        String[] packages = null;
4955        long ident = Binder.clearCallingIdentity();
4956        try {
4957            packages = mPackageManager.getPackagesForUid(callingUid);
4958        } finally {
4959            Binder.restoreCallingIdentity(ident);
4960        }
4961        if (packages != null) {
4962            for (String name : packages) {
4963                try {
4964                    PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4965                    if (packageInfo != null
4966                            && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4967                                    != 0) {
4968                        return true;
4969                    }
4970                } catch (PackageManager.NameNotFoundException e) {
4971                    Log.w(TAG, String.format("Could not find package [%s]", name), e);
4972                }
4973            }
4974        } else {
4975            Log.w(TAG, "No known packages with uid " + callingUid);
4976        }
4977        return false;
4978    }
4979
4980    /** Succeeds if any of the specified permissions are granted. */
4981    private void checkReadAccountsPermitted(
4982            int callingUid,
4983            String accountType,
4984            int userId,
4985            String opPackageName) {
4986        if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
4987            String msg = String.format(
4988                    "caller uid %s cannot access %s accounts",
4989                    callingUid,
4990                    accountType);
4991            Log.w(TAG, "  " + msg);
4992            throw new SecurityException(msg);
4993        }
4994    }
4995
4996    private boolean canUserModifyAccounts(int userId, int callingUid) {
4997        // the managing app can always modify accounts
4998        if (isProfileOwner(callingUid)) {
4999            return true;
5000        }
5001        if (getUserManager().getUserRestrictions(new UserHandle(userId))
5002                .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5003            return false;
5004        }
5005        return true;
5006    }
5007
5008    private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5009        // the managing app can always modify accounts
5010        if (isProfileOwner(callingUid)) {
5011            return true;
5012        }
5013        DevicePolicyManager dpm = (DevicePolicyManager) mContext
5014                .getSystemService(Context.DEVICE_POLICY_SERVICE);
5015        String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
5016        if (typesArray == null) {
5017            return true;
5018        }
5019        for (String forbiddenType : typesArray) {
5020            if (forbiddenType.equals(accountType)) {
5021                return false;
5022            }
5023        }
5024        return true;
5025    }
5026
5027    private boolean isProfileOwner(int uid) {
5028        final DevicePolicyManagerInternal dpmi =
5029                LocalServices.getService(DevicePolicyManagerInternal.class);
5030        return (dpmi != null)
5031                && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5032    }
5033
5034    @Override
5035    public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5036            throws RemoteException {
5037        final int callingUid = getCallingUid();
5038
5039        if (callingUid != Process.SYSTEM_UID) {
5040            throw new SecurityException();
5041        }
5042
5043        if (value) {
5044            grantAppPermission(account, authTokenType, uid);
5045        } else {
5046            revokeAppPermission(account, authTokenType, uid);
5047        }
5048    }
5049
5050    /**
5051     * Allow callers with the given uid permission to get credentials for account/authTokenType.
5052     * <p>
5053     * Although this is public it can only be accessed via the AccountManagerService object
5054     * which is in the system. This means we don't need to protect it with permissions.
5055     * @hide
5056     */
5057    private void grantAppPermission(Account account, String authTokenType, int uid) {
5058        if (account == null || authTokenType == null) {
5059            Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
5060            return;
5061        }
5062        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
5063        synchronized (accounts.cacheLock) {
5064            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
5065            db.beginTransaction();
5066            try {
5067                long accountId = getAccountIdLocked(db, account);
5068                if (accountId >= 0) {
5069                    ContentValues values = new ContentValues();
5070                    values.put(GRANTS_ACCOUNTS_ID, accountId);
5071                    values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5072                    values.put(GRANTS_GRANTEE_UID, uid);
5073                    db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5074                    db.setTransactionSuccessful();
5075                }
5076            } finally {
5077                db.endTransaction();
5078            }
5079            cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5080                    UserHandle.of(accounts.userId));
5081        }
5082    }
5083
5084    /**
5085     * Don't allow callers with the given uid permission to get credentials for
5086     * account/authTokenType.
5087     * <p>
5088     * Although this is public it can only be accessed via the AccountManagerService object
5089     * which is in the system. This means we don't need to protect it with permissions.
5090     * @hide
5091     */
5092    private void revokeAppPermission(Account account, String authTokenType, int uid) {
5093        if (account == null || authTokenType == null) {
5094            Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
5095            return;
5096        }
5097        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
5098        synchronized (accounts.cacheLock) {
5099            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
5100            db.beginTransaction();
5101            try {
5102                long accountId = getAccountIdLocked(db, account);
5103                if (accountId >= 0) {
5104                    db.delete(TABLE_GRANTS,
5105                            GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5106                                    + GRANTS_GRANTEE_UID + "=?",
5107                            new String[]{String.valueOf(accountId), authTokenType,
5108                                    String.valueOf(uid)});
5109                    db.setTransactionSuccessful();
5110                }
5111            } finally {
5112                db.endTransaction();
5113            }
5114            cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5115                    new UserHandle(accounts.userId));
5116        }
5117    }
5118
5119    static final private String stringArrayToString(String[] value) {
5120        return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5121    }
5122
5123    private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5124        final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
5125        if (oldAccountsForType != null) {
5126            ArrayList<Account> newAccountsList = new ArrayList<Account>();
5127            for (Account curAccount : oldAccountsForType) {
5128                if (!curAccount.equals(account)) {
5129                    newAccountsList.add(curAccount);
5130                }
5131            }
5132            if (newAccountsList.isEmpty()) {
5133                accounts.accountCache.remove(account.type);
5134            } else {
5135                Account[] newAccountsForType = new Account[newAccountsList.size()];
5136                newAccountsForType = newAccountsList.toArray(newAccountsForType);
5137                accounts.accountCache.put(account.type, newAccountsForType);
5138            }
5139        }
5140        accounts.userDataCache.remove(account);
5141        accounts.authTokenCache.remove(account);
5142        accounts.previousNameCache.remove(account);
5143    }
5144
5145    /**
5146     * This assumes that the caller has already checked that the account is not already present.
5147     */
5148    private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5149        Account[] accountsForType = accounts.accountCache.get(account.type);
5150        int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5151        Account[] newAccountsForType = new Account[oldLength + 1];
5152        if (accountsForType != null) {
5153            System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
5154        }
5155        newAccountsForType[oldLength] = account;
5156        accounts.accountCache.put(account.type, newAccountsForType);
5157    }
5158
5159    private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
5160            int callingUid, String callingPackage) {
5161        if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
5162                || callingUid == Process.myUid()) {
5163            return unfiltered;
5164        }
5165        UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
5166        if (user != null && user.isRestricted()) {
5167            String[] packages = mPackageManager.getPackagesForUid(callingUid);
5168            // If any of the packages is a white listed package, return the full set,
5169            // otherwise return non-shared accounts only.
5170            // This might be a temporary way to specify a whitelist
5171            String whiteList = mContext.getResources().getString(
5172                    com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5173            for (String packageName : packages) {
5174                if (whiteList.contains(";" + packageName + ";")) {
5175                    return unfiltered;
5176                }
5177            }
5178            ArrayList<Account> allowed = new ArrayList<Account>();
5179            Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5180            if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
5181            String requiredAccountType = "";
5182            try {
5183                // If there's an explicit callingPackage specified, check if that package
5184                // opted in to see restricted accounts.
5185                if (callingPackage != null) {
5186                    PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
5187                    if (pi != null && pi.restrictedAccountType != null) {
5188                        requiredAccountType = pi.restrictedAccountType;
5189                    }
5190                } else {
5191                    // Otherwise check if the callingUid has a package that has opted in
5192                    for (String packageName : packages) {
5193                        PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5194                        if (pi != null && pi.restrictedAccountType != null) {
5195                            requiredAccountType = pi.restrictedAccountType;
5196                            break;
5197                        }
5198                    }
5199                }
5200            } catch (NameNotFoundException nnfe) {
5201            }
5202            for (Account account : unfiltered) {
5203                if (account.type.equals(requiredAccountType)) {
5204                    allowed.add(account);
5205                } else {
5206                    boolean found = false;
5207                    for (Account shared : sharedAccounts) {
5208                        if (shared.equals(account)) {
5209                            found = true;
5210                            break;
5211                        }
5212                    }
5213                    if (!found) {
5214                        allowed.add(account);
5215                    }
5216                }
5217            }
5218            Account[] filtered = new Account[allowed.size()];
5219            allowed.toArray(filtered);
5220            return filtered;
5221        } else {
5222            return unfiltered;
5223        }
5224    }
5225
5226    /*
5227     * packageName can be null. If not null, it should be used to filter out restricted accounts
5228     * that the package is not allowed to access.
5229     */
5230    protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
5231            int callingUid, String callingPackage) {
5232        if (accountType != null) {
5233            final Account[] accounts = userAccounts.accountCache.get(accountType);
5234            if (accounts == null) {
5235                return EMPTY_ACCOUNT_ARRAY;
5236            } else {
5237                return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5238                        callingUid, callingPackage);
5239            }
5240        } else {
5241            int totalLength = 0;
5242            for (Account[] accounts : userAccounts.accountCache.values()) {
5243                totalLength += accounts.length;
5244            }
5245            if (totalLength == 0) {
5246                return EMPTY_ACCOUNT_ARRAY;
5247            }
5248            Account[] accounts = new Account[totalLength];
5249            totalLength = 0;
5250            for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5251                System.arraycopy(accountsOfType, 0, accounts, totalLength,
5252                        accountsOfType.length);
5253                totalLength += accountsOfType.length;
5254            }
5255            return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
5256        }
5257    }
5258
5259    protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5260            Account account, String key, String value) {
5261        HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5262        if (userDataForAccount == null) {
5263            userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5264            accounts.userDataCache.put(account, userDataForAccount);
5265        }
5266        if (value == null) {
5267            userDataForAccount.remove(key);
5268        } else {
5269            userDataForAccount.put(key, value);
5270        }
5271    }
5272
5273    protected String readCachedTokenInternal(
5274            UserAccounts accounts,
5275            Account account,
5276            String tokenType,
5277            String callingPackage,
5278            byte[] pkgSigDigest) {
5279        synchronized (accounts.cacheLock) {
5280            return accounts.accountTokenCaches.get(
5281                    account, tokenType, callingPackage, pkgSigDigest);
5282        }
5283    }
5284
5285    protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5286            Account account, String key, String value) {
5287        HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5288        if (authTokensForAccount == null) {
5289            authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
5290            accounts.authTokenCache.put(account, authTokensForAccount);
5291        }
5292        if (value == null) {
5293            authTokensForAccount.remove(key);
5294        } else {
5295            authTokensForAccount.put(key, value);
5296        }
5297    }
5298
5299    protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5300            String authTokenType) {
5301        synchronized (accounts.cacheLock) {
5302            HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5303            if (authTokensForAccount == null) {
5304                // need to populate the cache for this account
5305                final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
5306                authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
5307                accounts.authTokenCache.put(account, authTokensForAccount);
5308            }
5309            return authTokensForAccount.get(authTokenType);
5310        }
5311    }
5312
5313    protected String readUserDataInternalLocked(
5314            UserAccounts accounts, Account account, String key) {
5315        HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5316        if (userDataForAccount == null) {
5317            // need to populate the cache for this account
5318            final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5319            userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5320            accounts.userDataCache.put(account, userDataForAccount);
5321        }
5322        return userDataForAccount.get(key);
5323    }
5324
5325    protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5326            final SQLiteDatabase db, Account account) {
5327        HashMap<String, String> userDataForAccount = new HashMap<>();
5328        Cursor cursor = db.query(CE_TABLE_EXTRAS,
5329                COLUMNS_EXTRAS_KEY_AND_VALUE,
5330                SELECTION_USERDATA_BY_ACCOUNT,
5331                new String[]{account.name, account.type},
5332                null, null, null);
5333        try {
5334            while (cursor.moveToNext()) {
5335                final String tmpkey = cursor.getString(0);
5336                final String value = cursor.getString(1);
5337                userDataForAccount.put(tmpkey, value);
5338            }
5339        } finally {
5340            cursor.close();
5341        }
5342        return userDataForAccount;
5343    }
5344
5345    protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5346            final SQLiteDatabase db, Account account) {
5347        HashMap<String, String> authTokensForAccount = new HashMap<>();
5348        Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
5349                COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5350                SELECTION_AUTHTOKENS_BY_ACCOUNT,
5351                new String[]{account.name, account.type},
5352                null, null, null);
5353        try {
5354            while (cursor.moveToNext()) {
5355                final String type = cursor.getString(0);
5356                final String authToken = cursor.getString(1);
5357                authTokensForAccount.put(type, authToken);
5358            }
5359        } finally {
5360            cursor.close();
5361        }
5362        return authTokensForAccount;
5363    }
5364
5365    private Context getContextForUser(UserHandle user) {
5366        try {
5367            return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5368        } catch (NameNotFoundException e) {
5369            // Default to mContext, not finding the package system is running as is unlikely.
5370            return mContext;
5371        }
5372    }
5373
5374    private void sendResponse(IAccountManagerResponse response, Bundle result) {
5375        try {
5376            response.onResult(result);
5377        } catch (RemoteException e) {
5378            // if the caller is dead then there is no one to care about remote
5379            // exceptions
5380            if (Log.isLoggable(TAG, Log.VERBOSE)) {
5381                Log.v(TAG, "failure while notifying response", e);
5382            }
5383        }
5384    }
5385
5386    private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5387            String errorMessage) {
5388        try {
5389            response.onError(errorCode, errorMessage);
5390        } catch (RemoteException e) {
5391            // if the caller is dead then there is no one to care about remote
5392            // exceptions
5393            if (Log.isLoggable(TAG, Log.VERBOSE)) {
5394                Log.v(TAG, "failure while notifying response", e);
5395            }
5396        }
5397    }
5398}
5399