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