AccountManagerService.java revision 4e68b6572306fb4a44e78b3cf2b48fb943e69cbe
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.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
25import android.accounts.CantAddAccountActivity;
26import android.accounts.GrantCredentialsPermissionActivity;
27import android.accounts.IAccountAuthenticator;
28import android.accounts.IAccountAuthenticatorResponse;
29import android.accounts.IAccountManager;
30import android.accounts.IAccountManagerResponse;
31import android.app.ActivityManager;
32import android.app.ActivityManagerNative;
33import android.app.AppGlobals;
34import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
37import android.app.admin.DevicePolicyManager;
38import android.content.BroadcastReceiver;
39import android.content.ComponentName;
40import android.content.ContentValues;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.ServiceConnection;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageInfo;
47import android.content.pm.PackageManager;
48import android.content.pm.PackageManager.NameNotFoundException;
49import android.content.pm.RegisteredServicesCache;
50import android.content.pm.RegisteredServicesCacheListener;
51import android.content.pm.ResolveInfo;
52import android.content.pm.UserInfo;
53import android.database.Cursor;
54import android.database.DatabaseUtils;
55import android.database.sqlite.SQLiteDatabase;
56import android.database.sqlite.SQLiteOpenHelper;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Environment;
60import android.os.Handler;
61import android.os.IBinder;
62import android.os.Looper;
63import android.os.Message;
64import android.os.Parcel;
65import android.os.Process;
66import android.os.RemoteException;
67import android.os.SystemClock;
68import android.os.UserHandle;
69import android.os.UserManager;
70import android.text.TextUtils;
71import android.util.Log;
72import android.util.Pair;
73import android.util.Slog;
74import android.util.SparseArray;
75
76import com.android.internal.R;
77import com.android.internal.util.ArrayUtils;
78import com.android.internal.util.IndentingPrintWriter;
79import com.android.server.FgThread;
80
81import com.google.android.collect.Lists;
82import com.google.android.collect.Sets;
83
84import java.io.File;
85import java.io.FileDescriptor;
86import java.io.PrintWriter;
87import java.util.ArrayList;
88import java.util.Arrays;
89import java.util.Collection;
90import java.util.HashMap;
91import java.util.HashSet;
92import java.util.LinkedHashMap;
93import java.util.List;
94import java.util.Map;
95import java.util.concurrent.atomic.AtomicInteger;
96import java.util.concurrent.atomic.AtomicReference;
97
98/**
99 * A system service that provides  account, password, and authtoken management for all
100 * accounts on the device. Some of these calls are implemented with the help of the corresponding
101 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
102 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
103 *    AccountManager accountManager = AccountManager.get(context);
104 * @hide
105 */
106public class AccountManagerService
107        extends IAccountManager.Stub
108        implements RegisteredServicesCacheListener<AuthenticatorDescription> {
109    private static final String TAG = "AccountManagerService";
110
111    private static final int TIMEOUT_DELAY_MS = 1000 * 60;
112    private static final String DATABASE_NAME = "accounts.db";
113    private static final int DATABASE_VERSION = 6;
114
115    private final Context mContext;
116
117    private final PackageManager mPackageManager;
118    private UserManager mUserManager;
119
120    private final MessageHandler mMessageHandler;
121
122    // Messages that can be sent on mHandler
123    private static final int MESSAGE_TIMED_OUT = 3;
124    private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
125
126    private final IAccountAuthenticatorCache mAuthenticatorCache;
127
128    private static final String TABLE_ACCOUNTS = "accounts";
129    private static final String ACCOUNTS_ID = "_id";
130    private static final String ACCOUNTS_NAME = "name";
131    private static final String ACCOUNTS_TYPE = "type";
132    private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
133    private static final String ACCOUNTS_PASSWORD = "password";
134    private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
135
136    private static final String TABLE_AUTHTOKENS = "authtokens";
137    private static final String AUTHTOKENS_ID = "_id";
138    private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
139    private static final String AUTHTOKENS_TYPE = "type";
140    private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
141
142    private static final String TABLE_GRANTS = "grants";
143    private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
144    private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
145    private static final String GRANTS_GRANTEE_UID = "uid";
146
147    private static final String TABLE_EXTRAS = "extras";
148    private static final String EXTRAS_ID = "_id";
149    private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
150    private static final String EXTRAS_KEY = "key";
151    private static final String EXTRAS_VALUE = "value";
152
153    private static final String TABLE_META = "meta";
154    private static final String META_KEY = "key";
155    private static final String META_VALUE = "value";
156
157    private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
158
159    private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
160            new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
161    private static final Intent ACCOUNTS_CHANGED_INTENT;
162
163    private static final String COUNT_OF_MATCHING_GRANTS = ""
164            + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
165            + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
166            + " AND " + GRANTS_GRANTEE_UID + "=?"
167            + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
168            + " AND " + ACCOUNTS_NAME + "=?"
169            + " AND " + ACCOUNTS_TYPE + "=?";
170
171    private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
172            AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
173    private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
174            AUTHTOKENS_AUTHTOKEN};
175
176    private static final String SELECTION_USERDATA_BY_ACCOUNT =
177            EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
178    private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
179
180    private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
181    private final AtomicInteger mNotificationIds = new AtomicInteger(1);
182
183    static class UserAccounts {
184        private final int userId;
185        private final DatabaseHelper openHelper;
186        private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
187                credentialsPermissionNotificationIds =
188                new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
189        private final HashMap<Account, Integer> signinRequiredNotificationIds =
190                new HashMap<Account, Integer>();
191        private final Object cacheLock = new Object();
192        /** protected by the {@link #cacheLock} */
193        private final HashMap<String, Account[]> accountCache =
194                new LinkedHashMap<String, Account[]>();
195        /** protected by the {@link #cacheLock} */
196        private final HashMap<Account, HashMap<String, String>> userDataCache =
197                new HashMap<Account, HashMap<String, String>>();
198        /** protected by the {@link #cacheLock} */
199        private final HashMap<Account, HashMap<String, String>> authTokenCache =
200                new HashMap<Account, HashMap<String, String>>();
201        /**
202         * protected by the {@link #cacheLock}
203         *
204         * Caches the previous names associated with an account. Previous names
205         * should be cached because we expect that when an Account is renamed,
206         * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
207         * want to know if the accounts they care about have been renamed.
208         *
209         * The previous names are wrapped in an {@link AtomicReference} so that
210         * we can distinguish between those accounts with no previous names and
211         * those whose previous names haven't been cached (yet).
212         */
213        private final HashMap<Account, AtomicReference<String>> previousNameCache =
214                new HashMap<Account, AtomicReference<String>>();
215
216        UserAccounts(Context context, int userId) {
217            this.userId = userId;
218            synchronized (cacheLock) {
219                openHelper = new DatabaseHelper(context, userId);
220            }
221        }
222    }
223
224    private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
225
226    private static AtomicReference<AccountManagerService> sThis =
227            new AtomicReference<AccountManagerService>();
228    private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
229
230    static {
231        ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
232        ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
233    }
234
235
236    /**
237     * This should only be called by system code. One should only call this after the service
238     * has started.
239     * @return a reference to the AccountManagerService instance
240     * @hide
241     */
242    public static AccountManagerService getSingleton() {
243        return sThis.get();
244    }
245
246    public AccountManagerService(Context context) {
247        this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
248    }
249
250    public AccountManagerService(Context context, PackageManager packageManager,
251            IAccountAuthenticatorCache authenticatorCache) {
252        mContext = context;
253        mPackageManager = packageManager;
254
255        mMessageHandler = new MessageHandler(FgThread.get().getLooper());
256
257        mAuthenticatorCache = authenticatorCache;
258        mAuthenticatorCache.setListener(this, null /* Handler */);
259
260        sThis.set(this);
261
262        IntentFilter intentFilter = new IntentFilter();
263        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
264        intentFilter.addDataScheme("package");
265        mContext.registerReceiver(new BroadcastReceiver() {
266            @Override
267            public void onReceive(Context context1, Intent intent) {
268                purgeOldGrantsAll();
269            }
270        }, intentFilter);
271
272        IntentFilter userFilter = new IntentFilter();
273        userFilter.addAction(Intent.ACTION_USER_REMOVED);
274        userFilter.addAction(Intent.ACTION_USER_STARTED);
275        mContext.registerReceiverAsUser(new BroadcastReceiver() {
276            @Override
277            public void onReceive(Context context, Intent intent) {
278                String action = intent.getAction();
279                if (Intent.ACTION_USER_REMOVED.equals(action)) {
280                    onUserRemoved(intent);
281                } else if (Intent.ACTION_USER_STARTED.equals(action)) {
282                    onUserStarted(intent);
283                }
284            }
285        }, UserHandle.ALL, userFilter, null, null);
286    }
287
288    @Override
289    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
290            throws RemoteException {
291        try {
292            return super.onTransact(code, data, reply, flags);
293        } catch (RuntimeException e) {
294            // The account manager only throws security exceptions, so let's
295            // log all others.
296            if (!(e instanceof SecurityException)) {
297                Slog.wtf(TAG, "Account Manager Crash", e);
298            }
299            throw e;
300        }
301    }
302
303    public void systemReady() {
304    }
305
306    private UserManager getUserManager() {
307        if (mUserManager == null) {
308            mUserManager = UserManager.get(mContext);
309        }
310        return mUserManager;
311    }
312
313    /* Caller should lock mUsers */
314    private UserAccounts initUserLocked(int userId) {
315        UserAccounts accounts = mUsers.get(userId);
316        if (accounts == null) {
317            accounts = new UserAccounts(mContext, userId);
318            mUsers.append(userId, accounts);
319            purgeOldGrants(accounts);
320            validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
321        }
322        return accounts;
323    }
324
325    private void purgeOldGrantsAll() {
326        synchronized (mUsers) {
327            for (int i = 0; i < mUsers.size(); i++) {
328                purgeOldGrants(mUsers.valueAt(i));
329            }
330        }
331    }
332
333    private void purgeOldGrants(UserAccounts accounts) {
334        synchronized (accounts.cacheLock) {
335            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
336            final Cursor cursor = db.query(TABLE_GRANTS,
337                    new String[]{GRANTS_GRANTEE_UID},
338                    null, null, GRANTS_GRANTEE_UID, null, null);
339            try {
340                while (cursor.moveToNext()) {
341                    final int uid = cursor.getInt(0);
342                    final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
343                    if (packageExists) {
344                        continue;
345                    }
346                    Log.d(TAG, "deleting grants for UID " + uid
347                            + " because its package is no longer installed");
348                    db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
349                            new String[]{Integer.toString(uid)});
350                }
351            } finally {
352                cursor.close();
353            }
354        }
355    }
356
357    /**
358     * Validate internal set of accounts against installed authenticators for
359     * given user. Clears cached authenticators before validating.
360     */
361    public void validateAccounts(int userId) {
362        final UserAccounts accounts = getUserAccounts(userId);
363
364        // Invalidate user-specific cache to make sure we catch any
365        // removed authenticators.
366        validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
367    }
368
369    /**
370     * Validate internal set of accounts against installed authenticators for
371     * given user. Clear cached authenticators before validating when requested.
372     */
373    private void validateAccountsInternal(
374            UserAccounts accounts, boolean invalidateAuthenticatorCache) {
375        if (invalidateAuthenticatorCache) {
376            mAuthenticatorCache.invalidateCache(accounts.userId);
377        }
378
379        final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
380        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
381                mAuthenticatorCache.getAllServices(accounts.userId)) {
382            knownAuth.add(service.type);
383        }
384
385        synchronized (accounts.cacheLock) {
386            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
387            boolean accountDeleted = false;
388            Cursor cursor = db.query(TABLE_ACCOUNTS,
389                    new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
390                    null, null, null, null, null);
391            try {
392                accounts.accountCache.clear();
393                final HashMap<String, ArrayList<String>> accountNamesByType =
394                        new LinkedHashMap<String, ArrayList<String>>();
395                while (cursor.moveToNext()) {
396                    final long accountId = cursor.getLong(0);
397                    final String accountType = cursor.getString(1);
398                    final String accountName = cursor.getString(2);
399
400                    if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
401                        Slog.w(TAG, "deleting account " + accountName + " because type "
402                                + accountType + " no longer has a registered authenticator");
403                        db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
404                        accountDeleted = true;
405                        final Account account = new Account(accountName, accountType);
406                        accounts.userDataCache.remove(account);
407                        accounts.authTokenCache.remove(account);
408                    } else {
409                        ArrayList<String> accountNames = accountNamesByType.get(accountType);
410                        if (accountNames == null) {
411                            accountNames = new ArrayList<String>();
412                            accountNamesByType.put(accountType, accountNames);
413                        }
414                        accountNames.add(accountName);
415                    }
416                }
417                for (Map.Entry<String, ArrayList<String>> cur
418                        : accountNamesByType.entrySet()) {
419                    final String accountType = cur.getKey();
420                    final ArrayList<String> accountNames = cur.getValue();
421                    final Account[] accountsForType = new Account[accountNames.size()];
422                    int i = 0;
423                    for (String accountName : accountNames) {
424                        accountsForType[i] = new Account(accountName, accountType);
425                        ++i;
426                    }
427                    accounts.accountCache.put(accountType, accountsForType);
428                }
429            } finally {
430                cursor.close();
431                if (accountDeleted) {
432                    sendAccountsChangedBroadcast(accounts.userId);
433                }
434            }
435        }
436    }
437
438    private UserAccounts getUserAccountsForCaller() {
439        return getUserAccounts(UserHandle.getCallingUserId());
440    }
441
442    protected UserAccounts getUserAccounts(int userId) {
443        synchronized (mUsers) {
444            UserAccounts accounts = mUsers.get(userId);
445            if (accounts == null) {
446                accounts = initUserLocked(userId);
447                mUsers.append(userId, accounts);
448            }
449            return accounts;
450        }
451    }
452
453    private void onUserRemoved(Intent intent) {
454        int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
455        if (userId < 1) return;
456
457        UserAccounts accounts;
458        synchronized (mUsers) {
459            accounts = mUsers.get(userId);
460            mUsers.remove(userId);
461        }
462        if (accounts == null) {
463            File dbFile = new File(getDatabaseName(userId));
464            dbFile.delete();
465            return;
466        }
467
468        synchronized (accounts.cacheLock) {
469            accounts.openHelper.close();
470            File dbFile = new File(getDatabaseName(userId));
471            dbFile.delete();
472        }
473    }
474
475    private void onUserStarted(Intent intent) {
476        int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
477        if (userId < 1) return;
478
479        // Check if there's a shared account that needs to be created as an account
480        Account[] sharedAccounts = getSharedAccountsAsUser(userId);
481        if (sharedAccounts == null || sharedAccounts.length == 0) return;
482        Account[] accounts = getAccountsAsUser(null, userId);
483        for (Account sa : sharedAccounts) {
484            if (ArrayUtils.contains(accounts, sa)) continue;
485            // Account doesn't exist. Copy it now.
486            copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
487        }
488    }
489
490    @Override
491    public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
492        validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
493    }
494
495    @Override
496    public String getPassword(Account account) {
497        if (Log.isLoggable(TAG, Log.VERBOSE)) {
498            Log.v(TAG, "getPassword: " + account
499                    + ", caller's uid " + Binder.getCallingUid()
500                    + ", pid " + Binder.getCallingPid());
501        }
502        if (account == null) throw new IllegalArgumentException("account is null");
503        checkAuthenticateAccountsPermission(account);
504
505        UserAccounts accounts = getUserAccountsForCaller();
506        long identityToken = clearCallingIdentity();
507        try {
508            return readPasswordInternal(accounts, account);
509        } finally {
510            restoreCallingIdentity(identityToken);
511        }
512    }
513
514    private String readPasswordInternal(UserAccounts accounts, Account account) {
515        if (account == null) {
516            return null;
517        }
518
519        synchronized (accounts.cacheLock) {
520            final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
521            Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
522                    ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
523                    new String[]{account.name, account.type}, null, null, null);
524            try {
525                if (cursor.moveToNext()) {
526                    return cursor.getString(0);
527                }
528                return null;
529            } finally {
530                cursor.close();
531            }
532        }
533    }
534
535    @Override
536    public String getPreviousName(Account account) {
537        if (Log.isLoggable(TAG, Log.VERBOSE)) {
538            Log.v(TAG, "getPreviousName: " + account
539                    + ", caller's uid " + Binder.getCallingUid()
540                    + ", pid " + Binder.getCallingPid());
541        }
542        if (account == null) throw new IllegalArgumentException("account is null");
543        UserAccounts accounts = getUserAccountsForCaller();
544        long identityToken = clearCallingIdentity();
545        try {
546            return readPreviousNameInternal(accounts, account);
547        } finally {
548            restoreCallingIdentity(identityToken);
549        }
550    }
551
552    private String readPreviousNameInternal(UserAccounts accounts, Account account) {
553        if  (account == null) {
554            return null;
555        }
556        synchronized (accounts.cacheLock) {
557            AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
558            if (previousNameRef == null) {
559                final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
560                Cursor cursor = db.query(
561                        TABLE_ACCOUNTS,
562                        new String[]{ ACCOUNTS_PREVIOUS_NAME },
563                        ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
564                        new String[] { account.name, account.type },
565                        null,
566                        null,
567                        null);
568                try {
569                    if (cursor.moveToNext()) {
570                        String previousName = cursor.getString(0);
571                        previousNameRef = new AtomicReference<String>(previousName);
572                        accounts.previousNameCache.put(account, previousNameRef);
573                        return previousName;
574                    } else {
575                        return null;
576                    }
577                } finally {
578                    cursor.close();
579                }
580            } else {
581                return previousNameRef.get();
582            }
583        }
584    }
585
586    @Override
587    public String getUserData(Account account, String key) {
588        if (Log.isLoggable(TAG, Log.VERBOSE)) {
589            Log.v(TAG, "getUserData: " + account
590                    + ", key " + key
591                    + ", caller's uid " + Binder.getCallingUid()
592                    + ", pid " + Binder.getCallingPid());
593        }
594        if (account == null) throw new IllegalArgumentException("account is null");
595        if (key == null) throw new IllegalArgumentException("key is null");
596        checkAuthenticateAccountsPermission(account);
597        UserAccounts accounts = getUserAccountsForCaller();
598        long identityToken = clearCallingIdentity();
599        try {
600            return readUserDataInternal(accounts, account, key);
601        } finally {
602            restoreCallingIdentity(identityToken);
603        }
604    }
605
606    @Override
607    public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
608        if (Log.isLoggable(TAG, Log.VERBOSE)) {
609            Log.v(TAG, "getAuthenticatorTypes: "
610                    + "for user id " + userId
611                    + "caller's uid " + Binder.getCallingUid()
612                    + ", pid " + Binder.getCallingPid());
613        }
614        // Only allow the system process to read accounts of other users
615        enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
616                + " trying get authenticator types for " + userId);
617        final long identityToken = clearCallingIdentity();
618        try {
619            Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
620                    authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
621            AuthenticatorDescription[] types =
622                    new AuthenticatorDescription[authenticatorCollection.size()];
623            int i = 0;
624            for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
625                    : authenticatorCollection) {
626                types[i] = authenticator.type;
627                i++;
628            }
629            return types;
630        } finally {
631            restoreCallingIdentity(identityToken);
632        }
633    }
634
635    private void enforceCrossUserPermission(int userId, String errorMessage) {
636        if (userId != UserHandle.getCallingUserId()
637                && Binder.getCallingUid() != Process.myUid()
638                && mContext.checkCallingOrSelfPermission(
639                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
640                    != PackageManager.PERMISSION_GRANTED) {
641            throw new SecurityException(errorMessage);
642        }
643    }
644
645    @Override
646    public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
647        if (Log.isLoggable(TAG, Log.VERBOSE)) {
648            Log.v(TAG, "addAccountExplicitly: " + account
649                    + ", caller's uid " + Binder.getCallingUid()
650                    + ", pid " + Binder.getCallingPid());
651        }
652        if (account == null) throw new IllegalArgumentException("account is null");
653        checkAuthenticateAccountsPermission(account);
654        /*
655         * Child users are not allowed to add accounts. Only the accounts that are
656         * shared by the parent profile can be added to child profile.
657         *
658         * TODO: Only allow accounts that were shared to be added by
659         *     a limited user.
660         */
661
662        UserAccounts accounts = getUserAccountsForCaller();
663        // fails if the account already exists
664        long identityToken = clearCallingIdentity();
665        try {
666            return addAccountInternal(accounts, account, password, extras, false);
667        } finally {
668            restoreCallingIdentity(identityToken);
669        }
670    }
671
672    private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
673        final UserAccounts fromAccounts = getUserAccounts(userFrom);
674        final UserAccounts toAccounts = getUserAccounts(userTo);
675        if (fromAccounts == null || toAccounts == null) {
676            return false;
677        }
678
679        long identityToken = clearCallingIdentity();
680        try {
681            new Session(fromAccounts, null, account.type, false,
682                    false /* stripAuthTokenFromResult */) {
683                @Override
684                protected String toDebugString(long now) {
685                    return super.toDebugString(now) + ", getAccountCredentialsForClone"
686                            + ", " + account.type;
687                }
688
689                @Override
690                public void run() throws RemoteException {
691                    mAuthenticator.getAccountCredentialsForCloning(this, account);
692                }
693
694                @Override
695                public void onResult(Bundle result) {
696                    if (result != null) {
697                        if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
698                            // Create a Session for the target user and pass in the bundle
699                            completeCloningAccount(result, account, toAccounts);
700                        }
701                        return;
702                    } else {
703                        super.onResult(result);
704                    }
705                }
706            }.bind();
707        } finally {
708            restoreCallingIdentity(identityToken);
709        }
710        return true;
711    }
712
713    void completeCloningAccount(final Bundle result, final Account account,
714            final UserAccounts targetUser) {
715        long id = clearCallingIdentity();
716        try {
717            new Session(targetUser, null, account.type, false,
718                    false /* stripAuthTokenFromResult */) {
719                @Override
720                protected String toDebugString(long now) {
721                    return super.toDebugString(now) + ", getAccountCredentialsForClone"
722                            + ", " + account.type;
723                }
724
725                @Override
726                public void run() throws RemoteException {
727                    // Confirm that the owner's account still exists before this step.
728                    UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
729                    synchronized (owner.cacheLock) {
730                        Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
731                        for (Account acc : ownerAccounts) {
732                            if (acc.equals(account)) {
733                                mAuthenticator.addAccountFromCredentials(this, account, result);
734                                break;
735                            }
736                        }
737                    }
738                }
739
740                @Override
741                public void onResult(Bundle result) {
742                    if (result != null) {
743                        if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
744                            // TODO: Anything?
745                        } else {
746                            // TODO: Show error notification
747                            // TODO: Should we remove the shadow account to avoid retries?
748                        }
749                        return;
750                    } else {
751                        super.onResult(result);
752                    }
753                }
754
755                @Override
756                public void onError(int errorCode, String errorMessage) {
757                    super.onError(errorCode,  errorMessage);
758                    // TODO: Show error notification to user
759                    // TODO: Should we remove the shadow account so that it doesn't keep trying?
760                }
761
762            }.bind();
763        } finally {
764            restoreCallingIdentity(id);
765        }
766    }
767
768    private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
769            Bundle extras, boolean restricted) {
770        if (account == null) {
771            return false;
772        }
773        synchronized (accounts.cacheLock) {
774            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
775            db.beginTransaction();
776            try {
777                long numMatches = DatabaseUtils.longForQuery(db,
778                        "select count(*) from " + TABLE_ACCOUNTS
779                                + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
780                        new String[]{account.name, account.type});
781                if (numMatches > 0) {
782                    Log.w(TAG, "insertAccountIntoDatabase: " + account
783                            + ", skipping since the account already exists");
784                    return false;
785                }
786                ContentValues values = new ContentValues();
787                values.put(ACCOUNTS_NAME, account.name);
788                values.put(ACCOUNTS_TYPE, account.type);
789                values.put(ACCOUNTS_PASSWORD, password);
790                long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
791                if (accountId < 0) {
792                    Log.w(TAG, "insertAccountIntoDatabase: " + account
793                            + ", skipping the DB insert failed");
794                    return false;
795                }
796                if (extras != null) {
797                    for (String key : extras.keySet()) {
798                        final String value = extras.getString(key);
799                        if (insertExtraLocked(db, accountId, key, value) < 0) {
800                            Log.w(TAG, "insertAccountIntoDatabase: " + account
801                                    + ", skipping since insertExtra failed for key " + key);
802                            return false;
803                        }
804                    }
805                }
806                db.setTransactionSuccessful();
807                insertAccountIntoCacheLocked(accounts, account);
808            } finally {
809                db.endTransaction();
810            }
811            sendAccountsChangedBroadcast(accounts.userId);
812        }
813        if (accounts.userId == UserHandle.USER_OWNER) {
814            addAccountToLimitedUsers(account);
815        }
816        return true;
817    }
818
819    /**
820     * Adds the account to all limited users as shared accounts. If the user is currently
821     * running, then clone the account too.
822     * @param account the account to share with limited users
823     */
824    private void addAccountToLimitedUsers(Account account) {
825        List<UserInfo> users = getUserManager().getUsers();
826        for (UserInfo user : users) {
827            if (user.isRestricted()) {
828                addSharedAccountAsUser(account, user.id);
829                try {
830                    if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
831                        mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
832                                MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
833                                account));
834                    }
835                } catch (RemoteException re) {
836                    // Shouldn't happen
837                }
838            }
839        }
840    }
841
842    private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
843        ContentValues values = new ContentValues();
844        values.put(EXTRAS_KEY, key);
845        values.put(EXTRAS_ACCOUNTS_ID, accountId);
846        values.put(EXTRAS_VALUE, value);
847        return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
848    }
849
850    @Override
851    public void hasFeatures(IAccountManagerResponse response,
852            Account account, String[] features) {
853        if (Log.isLoggable(TAG, Log.VERBOSE)) {
854            Log.v(TAG, "hasFeatures: " + account
855                    + ", response " + response
856                    + ", features " + stringArrayToString(features)
857                    + ", caller's uid " + Binder.getCallingUid()
858                    + ", pid " + Binder.getCallingPid());
859        }
860        if (response == null) throw new IllegalArgumentException("response is null");
861        if (account == null) throw new IllegalArgumentException("account is null");
862        if (features == null) throw new IllegalArgumentException("features is null");
863        checkReadAccountsPermission();
864        UserAccounts accounts = getUserAccountsForCaller();
865        long identityToken = clearCallingIdentity();
866        try {
867            new TestFeaturesSession(accounts, response, account, features).bind();
868        } finally {
869            restoreCallingIdentity(identityToken);
870        }
871    }
872
873    private class TestFeaturesSession extends Session {
874        private final String[] mFeatures;
875        private final Account mAccount;
876
877        public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
878                Account account, String[] features) {
879            super(accounts, response, account.type, false /* expectActivityLaunch */,
880                    true /* stripAuthTokenFromResult */);
881            mFeatures = features;
882            mAccount = account;
883        }
884
885        @Override
886        public void run() throws RemoteException {
887            try {
888                mAuthenticator.hasFeatures(this, mAccount, mFeatures);
889            } catch (RemoteException e) {
890                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
891            }
892        }
893
894        @Override
895        public void onResult(Bundle result) {
896            IAccountManagerResponse response = getResponseAndClose();
897            if (response != null) {
898                try {
899                    if (result == null) {
900                        response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
901                        return;
902                    }
903                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
904                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
905                                + response);
906                    }
907                    final Bundle newResult = new Bundle();
908                    newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
909                            result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
910                    response.onResult(newResult);
911                } catch (RemoteException e) {
912                    // if the caller is dead then there is no one to care about remote exceptions
913                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
914                        Log.v(TAG, "failure while notifying response", e);
915                    }
916                }
917            }
918        }
919
920        @Override
921        protected String toDebugString(long now) {
922            return super.toDebugString(now) + ", hasFeatures"
923                    + ", " + mAccount
924                    + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
925        }
926    }
927
928    @Override
929    public void renameAccount(
930            IAccountManagerResponse response, Account accountToRename, String newName) {
931        if (Log.isLoggable(TAG, Log.VERBOSE)) {
932            Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
933                + ", caller's uid " + Binder.getCallingUid()
934                + ", pid " + Binder.getCallingPid());
935        }
936        if (accountToRename == null) throw new IllegalArgumentException("account is null");
937        checkAuthenticateAccountsPermission(accountToRename);
938        UserAccounts accounts = getUserAccountsForCaller();
939        long identityToken = clearCallingIdentity();
940        try {
941            Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
942            Bundle result = new Bundle();
943            result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
944            result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
945            try {
946                response.onResult(result);
947            } catch (RemoteException e) {
948                Log.w(TAG, e.getMessage());
949            }
950        } finally {
951            restoreCallingIdentity(identityToken);
952        }
953    }
954
955    private Account renameAccountInternal(
956            UserAccounts accounts, Account accountToRename, String newName) {
957        Account resultAccount = null;
958        /*
959         * Cancel existing notifications. Let authenticators
960         * re-post notifications as required. But we don't know if
961         * the authenticators have bound their notifications to
962         * now stale account name data.
963         *
964         * With a rename api, we might not need to do this anymore but it
965         * shouldn't hurt.
966         */
967        cancelNotification(
968                getSigninRequiredNotificationId(accounts, accountToRename),
969                 new UserHandle(accounts.userId));
970        synchronized(accounts.credentialsPermissionNotificationIds) {
971            for (Pair<Pair<Account, String>, Integer> pair:
972                    accounts.credentialsPermissionNotificationIds.keySet()) {
973                if (accountToRename.equals(pair.first.first)) {
974                    int id = accounts.credentialsPermissionNotificationIds.get(pair);
975                    cancelNotification(id, new UserHandle(accounts.userId));
976                }
977            }
978        }
979        synchronized (accounts.cacheLock) {
980            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
981            db.beginTransaction();
982            boolean isSuccessful = false;
983            Account renamedAccount = new Account(newName, accountToRename.type);
984            try {
985                final ContentValues values = new ContentValues();
986                values.put(ACCOUNTS_NAME, newName);
987                values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
988                final long accountId = getAccountIdLocked(db, accountToRename);
989                if (accountId >= 0) {
990                    final String[] argsAccountId = { String.valueOf(accountId) };
991                    db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
992                    db.setTransactionSuccessful();
993                    isSuccessful = true;
994                }
995            } finally {
996                db.endTransaction();
997                if (isSuccessful) {
998                    /*
999                     * Database transaction was successful. Clean up cached
1000                     * data associated with the account in the user profile.
1001                     */
1002                    insertAccountIntoCacheLocked(accounts, renamedAccount);
1003                    /*
1004                     * Extract the data and token caches before removing the
1005                     * old account to preserve the user data associated with
1006                     * the account.
1007                     */
1008                    HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1009                    HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1010                    removeAccountFromCacheLocked(accounts, accountToRename);
1011                    /*
1012                     * Update the cached data associated with the renamed
1013                     * account.
1014                     */
1015                    accounts.userDataCache.put(renamedAccount, tmpData);
1016                    accounts.authTokenCache.put(renamedAccount, tmpTokens);
1017                    accounts.previousNameCache.put(
1018                          renamedAccount,
1019                          new AtomicReference<String>(accountToRename.name));
1020                    resultAccount = renamedAccount;
1021
1022                    if (accounts.userId == UserHandle.USER_OWNER) {
1023                        /*
1024                         * Owner's account was renamed, rename the account for
1025                         * those users with which the account was shared.
1026                         */
1027                        List<UserInfo> users = mUserManager.getUsers(true);
1028                        for (UserInfo user : users) {
1029                            if (!user.isPrimary() && user.isRestricted()) {
1030                                renameSharedAccountAsUser(accountToRename, newName, user.id);
1031                            }
1032                        }
1033                    }
1034                    sendAccountsChangedBroadcast(accounts.userId);
1035                }
1036            }
1037        }
1038        return resultAccount;
1039    }
1040
1041    @Override
1042    public void removeAccount(IAccountManagerResponse response, Account account) {
1043        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1044            Log.v(TAG, "removeAccount: " + account
1045                    + ", response " + response
1046                    + ", caller's uid " + Binder.getCallingUid()
1047                    + ", pid " + Binder.getCallingPid());
1048        }
1049        if (response == null) throw new IllegalArgumentException("response is null");
1050        if (account == null) throw new IllegalArgumentException("account is null");
1051        checkManageAccountsPermission();
1052        UserHandle user = Binder.getCallingUserHandle();
1053        UserAccounts accounts = getUserAccountsForCaller();
1054        int userId = Binder.getCallingUserHandle().getIdentifier();
1055        if (!canUserModifyAccounts(userId)) {
1056            try {
1057                // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
1058                response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1059                        "User cannot modify accounts");
1060            } catch (RemoteException re) {
1061            }
1062            return;
1063        }
1064        if (!canUserModifyAccountsForType(userId, account.type)) {
1065            try {
1066                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1067                        "User cannot modify accounts of this type (policy).");
1068            } catch (RemoteException re) {
1069            }
1070            return;
1071        }
1072
1073        long identityToken = clearCallingIdentity();
1074
1075        cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
1076        synchronized (accounts.credentialsPermissionNotificationIds) {
1077            for (Pair<Pair<Account, String>, Integer> pair:
1078                accounts.credentialsPermissionNotificationIds.keySet()) {
1079                if (account.equals(pair.first.first)) {
1080                    int id = accounts.credentialsPermissionNotificationIds.get(pair);
1081                    cancelNotification(id, user);
1082                }
1083            }
1084        }
1085
1086        try {
1087            new RemoveAccountSession(accounts, response, account).bind();
1088        } finally {
1089            restoreCallingIdentity(identityToken);
1090        }
1091    }
1092
1093    @Override
1094    public void removeAccountAsUser(IAccountManagerResponse response, Account account,
1095            int userId) {
1096        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1097            Log.v(TAG, "removeAccount: " + account
1098                    + ", response " + response
1099                    + ", caller's uid " + Binder.getCallingUid()
1100                    + ", pid " + Binder.getCallingPid()
1101                    + ", for user id " + userId);
1102        }
1103        if (response == null) throw new IllegalArgumentException("response is null");
1104        if (account == null) throw new IllegalArgumentException("account is null");
1105
1106        // Only allow the system process to modify accounts of other users
1107        enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1108                    + " trying to remove account for " + userId);
1109        checkManageAccountsPermission();
1110
1111        UserAccounts accounts = getUserAccounts(userId);
1112        if (!canUserModifyAccounts(userId)) {
1113            try {
1114                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1115                        "User cannot modify accounts");
1116            } catch (RemoteException re) {
1117            }
1118            return;
1119        }
1120        if (!canUserModifyAccountsForType(userId, account.type)) {
1121            try {
1122                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1123                        "User cannot modify accounts of this type (policy).");
1124            } catch (RemoteException re) {
1125            }
1126            return;
1127        }
1128
1129        UserHandle user = new UserHandle(userId);
1130        long identityToken = clearCallingIdentity();
1131
1132        cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
1133        synchronized(accounts.credentialsPermissionNotificationIds) {
1134            for (Pair<Pair<Account, String>, Integer> pair:
1135                accounts.credentialsPermissionNotificationIds.keySet()) {
1136                if (account.equals(pair.first.first)) {
1137                    int id = accounts.credentialsPermissionNotificationIds.get(pair);
1138                    cancelNotification(id, user);
1139                }
1140            }
1141        }
1142
1143        try {
1144            new RemoveAccountSession(accounts, response, account).bind();
1145        } finally {
1146            restoreCallingIdentity(identityToken);
1147        }
1148    }
1149
1150    private class RemoveAccountSession extends Session {
1151        final Account mAccount;
1152        public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
1153                Account account) {
1154            super(accounts, response, account.type, false /* expectActivityLaunch */,
1155                    true /* stripAuthTokenFromResult */);
1156            mAccount = account;
1157        }
1158
1159        @Override
1160        protected String toDebugString(long now) {
1161            return super.toDebugString(now) + ", removeAccount"
1162                    + ", account " + mAccount;
1163        }
1164
1165        @Override
1166        public void run() throws RemoteException {
1167            mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1168        }
1169
1170        @Override
1171        public void onResult(Bundle result) {
1172            if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1173                    && !result.containsKey(AccountManager.KEY_INTENT)) {
1174                final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1175                if (removalAllowed) {
1176                    removeAccountInternal(mAccounts, mAccount);
1177                }
1178                IAccountManagerResponse response = getResponseAndClose();
1179                if (response != null) {
1180                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
1181                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1182                                + response);
1183                    }
1184                    Bundle result2 = new Bundle();
1185                    result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
1186                    try {
1187                        response.onResult(result2);
1188                    } catch (RemoteException e) {
1189                        // ignore
1190                    }
1191                }
1192            }
1193            super.onResult(result);
1194        }
1195    }
1196
1197    /* For testing */
1198    protected void removeAccountInternal(Account account) {
1199        removeAccountInternal(getUserAccountsForCaller(), account);
1200    }
1201
1202    private void removeAccountInternal(UserAccounts accounts, Account account) {
1203        synchronized (accounts.cacheLock) {
1204            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1205            db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1206                    new String[]{account.name, account.type});
1207            removeAccountFromCacheLocked(accounts, account);
1208            sendAccountsChangedBroadcast(accounts.userId);
1209        }
1210        if (accounts.userId == UserHandle.USER_OWNER) {
1211            // Owner's account was removed, remove from any users that are sharing
1212            // this account.
1213            long id = Binder.clearCallingIdentity();
1214            try {
1215                List<UserInfo> users = mUserManager.getUsers(true);
1216                for (UserInfo user : users) {
1217                    if (!user.isPrimary() && user.isRestricted()) {
1218                        removeSharedAccountAsUser(account, user.id);
1219                    }
1220                }
1221            } finally {
1222                Binder.restoreCallingIdentity(id);
1223            }
1224        }
1225    }
1226
1227    @Override
1228    public void invalidateAuthToken(String accountType, String authToken) {
1229        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1230            Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1231                    + ", caller's uid " + Binder.getCallingUid()
1232                    + ", pid " + Binder.getCallingPid());
1233        }
1234        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1235        if (authToken == null) throw new IllegalArgumentException("authToken is null");
1236        checkManageAccountsOrUseCredentialsPermissions();
1237        UserAccounts accounts = getUserAccountsForCaller();
1238        long identityToken = clearCallingIdentity();
1239        try {
1240            synchronized (accounts.cacheLock) {
1241                final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1242                db.beginTransaction();
1243                try {
1244                    invalidateAuthTokenLocked(accounts, db, accountType, authToken);
1245                    db.setTransactionSuccessful();
1246                } finally {
1247                    db.endTransaction();
1248                }
1249            }
1250        } finally {
1251            restoreCallingIdentity(identityToken);
1252        }
1253    }
1254
1255    private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1256            String accountType, String authToken) {
1257        if (authToken == null || accountType == null) {
1258            return;
1259        }
1260        Cursor cursor = db.rawQuery(
1261                "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1262                        + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1263                        + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1264                        + " FROM " + TABLE_ACCOUNTS
1265                        + " JOIN " + TABLE_AUTHTOKENS
1266                        + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1267                        + " = " + AUTHTOKENS_ACCOUNTS_ID
1268                        + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1269                        + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1270                new String[]{authToken, accountType});
1271        try {
1272            while (cursor.moveToNext()) {
1273                long authTokenId = cursor.getLong(0);
1274                String accountName = cursor.getString(1);
1275                String authTokenType = cursor.getString(2);
1276                db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
1277                writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
1278                        authTokenType, null);
1279            }
1280        } finally {
1281            cursor.close();
1282        }
1283    }
1284
1285    private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1286            String authToken) {
1287        if (account == null || type == null) {
1288            return false;
1289        }
1290        cancelNotification(getSigninRequiredNotificationId(accounts, account),
1291                new UserHandle(accounts.userId));
1292        synchronized (accounts.cacheLock) {
1293            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1294            db.beginTransaction();
1295            try {
1296                long accountId = getAccountIdLocked(db, account);
1297                if (accountId < 0) {
1298                    return false;
1299                }
1300                db.delete(TABLE_AUTHTOKENS,
1301                        AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1302                        new String[]{type});
1303                ContentValues values = new ContentValues();
1304                values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1305                values.put(AUTHTOKENS_TYPE, type);
1306                values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1307                if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1308                    db.setTransactionSuccessful();
1309                    writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
1310                    return true;
1311                }
1312                return false;
1313            } finally {
1314                db.endTransaction();
1315            }
1316        }
1317    }
1318
1319    @Override
1320    public String peekAuthToken(Account account, String authTokenType) {
1321        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1322            Log.v(TAG, "peekAuthToken: " + account
1323                    + ", authTokenType " + authTokenType
1324                    + ", caller's uid " + Binder.getCallingUid()
1325                    + ", pid " + Binder.getCallingPid());
1326        }
1327        if (account == null) throw new IllegalArgumentException("account is null");
1328        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1329        checkAuthenticateAccountsPermission(account);
1330        UserAccounts accounts = getUserAccountsForCaller();
1331        long identityToken = clearCallingIdentity();
1332        try {
1333            return readAuthTokenInternal(accounts, account, authTokenType);
1334        } finally {
1335            restoreCallingIdentity(identityToken);
1336        }
1337    }
1338
1339    @Override
1340    public void setAuthToken(Account account, String authTokenType, String authToken) {
1341        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1342            Log.v(TAG, "setAuthToken: " + account
1343                    + ", authTokenType " + authTokenType
1344                    + ", caller's uid " + Binder.getCallingUid()
1345                    + ", pid " + Binder.getCallingPid());
1346        }
1347        if (account == null) throw new IllegalArgumentException("account is null");
1348        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1349        checkAuthenticateAccountsPermission(account);
1350        UserAccounts accounts = getUserAccountsForCaller();
1351        long identityToken = clearCallingIdentity();
1352        try {
1353            saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
1354        } finally {
1355            restoreCallingIdentity(identityToken);
1356        }
1357    }
1358
1359    @Override
1360    public void setPassword(Account account, String password) {
1361        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1362            Log.v(TAG, "setAuthToken: " + account
1363                    + ", caller's uid " + Binder.getCallingUid()
1364                    + ", pid " + Binder.getCallingPid());
1365        }
1366        if (account == null) throw new IllegalArgumentException("account is null");
1367        checkAuthenticateAccountsPermission(account);
1368        UserAccounts accounts = getUserAccountsForCaller();
1369        long identityToken = clearCallingIdentity();
1370        try {
1371            setPasswordInternal(accounts, account, password);
1372        } finally {
1373            restoreCallingIdentity(identityToken);
1374        }
1375    }
1376
1377    private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
1378        if (account == null) {
1379            return;
1380        }
1381        synchronized (accounts.cacheLock) {
1382            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1383            db.beginTransaction();
1384            try {
1385                final ContentValues values = new ContentValues();
1386                values.put(ACCOUNTS_PASSWORD, password);
1387                final long accountId = getAccountIdLocked(db, account);
1388                if (accountId >= 0) {
1389                    final String[] argsAccountId = {String.valueOf(accountId)};
1390                    db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1391                    db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
1392                    accounts.authTokenCache.remove(account);
1393                    db.setTransactionSuccessful();
1394                }
1395            } finally {
1396                db.endTransaction();
1397            }
1398            sendAccountsChangedBroadcast(accounts.userId);
1399        }
1400    }
1401
1402    private void sendAccountsChangedBroadcast(int userId) {
1403        Log.i(TAG, "the accounts changed, sending broadcast of "
1404                + ACCOUNTS_CHANGED_INTENT.getAction());
1405        mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
1406    }
1407
1408    @Override
1409    public void clearPassword(Account account) {
1410        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1411            Log.v(TAG, "clearPassword: " + account
1412                    + ", caller's uid " + Binder.getCallingUid()
1413                    + ", pid " + Binder.getCallingPid());
1414        }
1415        if (account == null) throw new IllegalArgumentException("account is null");
1416        checkManageAccountsPermission();
1417        UserAccounts accounts = getUserAccountsForCaller();
1418        long identityToken = clearCallingIdentity();
1419        try {
1420            setPasswordInternal(accounts, account, null);
1421        } finally {
1422            restoreCallingIdentity(identityToken);
1423        }
1424    }
1425
1426    @Override
1427    public void setUserData(Account account, String key, String value) {
1428        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1429            Log.v(TAG, "setUserData: " + account
1430                    + ", key " + key
1431                    + ", caller's uid " + Binder.getCallingUid()
1432                    + ", pid " + Binder.getCallingPid());
1433        }
1434        if (key == null) throw new IllegalArgumentException("key is null");
1435        if (account == null) throw new IllegalArgumentException("account is null");
1436        checkAuthenticateAccountsPermission(account);
1437        UserAccounts accounts = getUserAccountsForCaller();
1438        long identityToken = clearCallingIdentity();
1439        try {
1440            setUserdataInternal(accounts, account, key, value);
1441        } finally {
1442            restoreCallingIdentity(identityToken);
1443        }
1444    }
1445
1446    private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1447            String value) {
1448        if (account == null || key == null) {
1449            return;
1450        }
1451        synchronized (accounts.cacheLock) {
1452            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1453            db.beginTransaction();
1454            try {
1455                long accountId = getAccountIdLocked(db, account);
1456                if (accountId < 0) {
1457                    return;
1458                }
1459                long extrasId = getExtrasIdLocked(db, accountId, key);
1460                if (extrasId < 0 ) {
1461                    extrasId = insertExtraLocked(db, accountId, key, value);
1462                    if (extrasId < 0) {
1463                        return;
1464                    }
1465                } else {
1466                    ContentValues values = new ContentValues();
1467                    values.put(EXTRAS_VALUE, value);
1468                    if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1469                        return;
1470                    }
1471
1472                }
1473                writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1474                db.setTransactionSuccessful();
1475            } finally {
1476                db.endTransaction();
1477            }
1478        }
1479    }
1480
1481    private void onResult(IAccountManagerResponse response, Bundle result) {
1482        if (result == null) {
1483            Log.e(TAG, "the result is unexpectedly null", new Exception());
1484        }
1485        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1486            Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1487                    + response);
1488        }
1489        try {
1490            response.onResult(result);
1491        } catch (RemoteException e) {
1492            // if the caller is dead then there is no one to care about remote
1493            // exceptions
1494            if (Log.isLoggable(TAG, Log.VERBOSE)) {
1495                Log.v(TAG, "failure while notifying response", e);
1496            }
1497        }
1498    }
1499
1500    @Override
1501    public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1502                                  final String authTokenType)
1503            throws RemoteException {
1504        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1505        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1506
1507        final int callingUid = getCallingUid();
1508        clearCallingIdentity();
1509        if (callingUid != Process.SYSTEM_UID) {
1510            throw new SecurityException("can only call from system");
1511        }
1512        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
1513        long identityToken = clearCallingIdentity();
1514        try {
1515            new Session(accounts, response, accountType, false,
1516                    false /* stripAuthTokenFromResult */) {
1517                @Override
1518                protected String toDebugString(long now) {
1519                    return super.toDebugString(now) + ", getAuthTokenLabel"
1520                            + ", " + accountType
1521                            + ", authTokenType " + authTokenType;
1522                }
1523
1524                @Override
1525                public void run() throws RemoteException {
1526                    mAuthenticator.getAuthTokenLabel(this, authTokenType);
1527                }
1528
1529                @Override
1530                public void onResult(Bundle result) {
1531                    if (result != null) {
1532                        String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1533                        Bundle bundle = new Bundle();
1534                        bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1535                        super.onResult(bundle);
1536                        return;
1537                    } else {
1538                        super.onResult(result);
1539                    }
1540                }
1541            }.bind();
1542        } finally {
1543            restoreCallingIdentity(identityToken);
1544        }
1545    }
1546
1547    @Override
1548    public void getAuthToken(IAccountManagerResponse response, final Account account,
1549            final String authTokenType, final boolean notifyOnAuthFailure,
1550            final boolean expectActivityLaunch, Bundle loginOptionsIn) {
1551        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1552            Log.v(TAG, "getAuthToken: " + account
1553                    + ", response " + response
1554                    + ", authTokenType " + authTokenType
1555                    + ", notifyOnAuthFailure " + notifyOnAuthFailure
1556                    + ", expectActivityLaunch " + expectActivityLaunch
1557                    + ", caller's uid " + Binder.getCallingUid()
1558                    + ", pid " + Binder.getCallingPid());
1559        }
1560        if (response == null) throw new IllegalArgumentException("response is null");
1561        try {
1562            if (account == null) {
1563                Slog.w(TAG, "getAuthToken called with null account");
1564                response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1565                return;
1566            }
1567            if (authTokenType == null) {
1568                Slog.w(TAG, "getAuthToken called with null authTokenType");
1569                response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1570                return;
1571            }
1572        } catch (RemoteException e) {
1573            Slog.w(TAG, "Failed to report error back to the client." + e);
1574            return;
1575        }
1576
1577        checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
1578        final UserAccounts accounts = getUserAccountsForCaller();
1579        final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1580        authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1581                AuthenticatorDescription.newKey(account.type), accounts.userId);
1582        final boolean customTokens =
1583            authenticatorInfo != null && authenticatorInfo.type.customTokens;
1584
1585        // skip the check if customTokens
1586        final int callerUid = Binder.getCallingUid();
1587        final boolean permissionGranted = customTokens ||
1588            permissionIsGranted(account, authTokenType, callerUid);
1589
1590        final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1591            loginOptionsIn;
1592        // let authenticator know the identity of the caller
1593        loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1594        loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1595        if (notifyOnAuthFailure) {
1596            loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
1597        }
1598
1599        long identityToken = clearCallingIdentity();
1600        try {
1601            // if the caller has permission, do the peek. otherwise go the more expensive
1602            // route of starting a Session
1603            if (!customTokens && permissionGranted) {
1604                String authToken = readAuthTokenInternal(accounts, account, authTokenType);
1605                if (authToken != null) {
1606                    Bundle result = new Bundle();
1607                    result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1608                    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1609                    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1610                    onResult(response, result);
1611                    return;
1612                }
1613            }
1614
1615            new Session(accounts, response, account.type, expectActivityLaunch,
1616                    false /* stripAuthTokenFromResult */) {
1617                @Override
1618                protected String toDebugString(long now) {
1619                    if (loginOptions != null) loginOptions.keySet();
1620                    return super.toDebugString(now) + ", getAuthToken"
1621                            + ", " + account
1622                            + ", authTokenType " + authTokenType
1623                            + ", loginOptions " + loginOptions
1624                            + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1625                }
1626
1627                @Override
1628                public void run() throws RemoteException {
1629                    // If the caller doesn't have permission then create and return the
1630                    // "grant permission" intent instead of the "getAuthToken" intent.
1631                    if (!permissionGranted) {
1632                        mAuthenticator.getAuthTokenLabel(this, authTokenType);
1633                    } else {
1634                        mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1635                    }
1636                }
1637
1638                @Override
1639                public void onResult(Bundle result) {
1640                    if (result != null) {
1641                        if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
1642                            Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1643                                    new AccountAuthenticatorResponse(this),
1644                                    authTokenType,
1645                                    result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
1646                            Bundle bundle = new Bundle();
1647                            bundle.putParcelable(AccountManager.KEY_INTENT, intent);
1648                            onResult(bundle);
1649                            return;
1650                        }
1651                        String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
1652                        if (authToken != null) {
1653                            String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1654                            String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
1655                            if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
1656                                onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
1657                                        "the type and name should not be empty");
1658                                return;
1659                            }
1660                            if (!customTokens) {
1661                                saveAuthTokenToDatabase(mAccounts, new Account(name, type),
1662                                        authTokenType, authToken);
1663                            }
1664                        }
1665
1666                        Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
1667                        if (intent != null && notifyOnAuthFailure && !customTokens) {
1668                            doNotification(mAccounts,
1669                                    account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
1670                                    intent, accounts.userId);
1671                        }
1672                    }
1673                    super.onResult(result);
1674                }
1675            }.bind();
1676        } finally {
1677            restoreCallingIdentity(identityToken);
1678        }
1679    }
1680
1681    private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1682            int userId) {
1683        int uid = intent.getIntExtra(
1684                GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1685        String authTokenType = intent.getStringExtra(
1686                GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1687        String authTokenLabel = intent.getStringExtra(
1688                GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1689
1690        Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1691                0 /* when */);
1692        final String titleAndSubtitle =
1693                mContext.getString(R.string.permission_request_notification_with_subtitle,
1694                account.name);
1695        final int index = titleAndSubtitle.indexOf('\n');
1696        String title = titleAndSubtitle;
1697        String subtitle = "";
1698        if (index > 0) {
1699            title = titleAndSubtitle.substring(0, index);
1700            subtitle = titleAndSubtitle.substring(index + 1);
1701        }
1702        UserHandle user = new UserHandle(userId);
1703        n.setLatestEventInfo(mContext, title, subtitle,
1704                PendingIntent.getActivityAsUser(mContext, 0, intent,
1705                        PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1706        installNotification(getCredentialPermissionNotificationId(
1707                account, authTokenType, uid), n, user);
1708    }
1709
1710    private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1711            AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
1712
1713        Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
1714        // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
1715        // Since it was set in Eclair+ we can't change it without breaking apps using
1716        // the intent from a non-Activity context.
1717        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1718        intent.addCategory(
1719                String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
1720
1721        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
1722        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1723        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
1724        intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
1725
1726        return intent;
1727    }
1728
1729    private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1730            int uid) {
1731        Integer id;
1732        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
1733        synchronized (accounts.credentialsPermissionNotificationIds) {
1734            final Pair<Pair<Account, String>, Integer> key =
1735                    new Pair<Pair<Account, String>, Integer>(
1736                            new Pair<Account, String>(account, authTokenType), uid);
1737            id = accounts.credentialsPermissionNotificationIds.get(key);
1738            if (id == null) {
1739                id = mNotificationIds.incrementAndGet();
1740                accounts.credentialsPermissionNotificationIds.put(key, id);
1741            }
1742        }
1743        return id;
1744    }
1745
1746    private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
1747        Integer id;
1748        synchronized (accounts.signinRequiredNotificationIds) {
1749            id = accounts.signinRequiredNotificationIds.get(account);
1750            if (id == null) {
1751                id = mNotificationIds.incrementAndGet();
1752                accounts.signinRequiredNotificationIds.put(account, id);
1753            }
1754        }
1755        return id;
1756    }
1757
1758    @Override
1759    public void addAccount(final IAccountManagerResponse response, final String accountType,
1760            final String authTokenType, final String[] requiredFeatures,
1761            final boolean expectActivityLaunch, final Bundle optionsIn) {
1762        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1763            Log.v(TAG, "addAccount: accountType " + accountType
1764                    + ", response " + response
1765                    + ", authTokenType " + authTokenType
1766                    + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1767                    + ", expectActivityLaunch " + expectActivityLaunch
1768                    + ", caller's uid " + Binder.getCallingUid()
1769                    + ", pid " + Binder.getCallingPid());
1770        }
1771        if (response == null) throw new IllegalArgumentException("response is null");
1772        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1773        checkManageAccountsPermission();
1774
1775        // Is user disallowed from modifying accounts?
1776        int userId = Binder.getCallingUserHandle().getIdentifier();
1777        if (!canUserModifyAccounts(userId)) {
1778            try {
1779                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1780                        "User is not allowed to add an account!");
1781            } catch (RemoteException re) {
1782            }
1783            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1784            return;
1785        }
1786        if (!canUserModifyAccountsForType(userId, accountType)) {
1787            try {
1788                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1789                        "User cannot modify accounts of this type (policy).");
1790            } catch (RemoteException re) {
1791            }
1792            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1793            return;
1794        }
1795
1796        UserAccounts accounts = getUserAccountsForCaller();
1797        final int pid = Binder.getCallingPid();
1798        final int uid = Binder.getCallingUid();
1799        final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1800        options.putInt(AccountManager.KEY_CALLER_UID, uid);
1801        options.putInt(AccountManager.KEY_CALLER_PID, pid);
1802
1803        long identityToken = clearCallingIdentity();
1804        try {
1805            new Session(accounts, response, accountType, expectActivityLaunch,
1806                    true /* stripAuthTokenFromResult */) {
1807                @Override
1808                public void run() throws RemoteException {
1809                    mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1810                            options);
1811                }
1812
1813                @Override
1814                protected String toDebugString(long now) {
1815                    return super.toDebugString(now) + ", addAccount"
1816                            + ", accountType " + accountType
1817                            + ", requiredFeatures "
1818                            + (requiredFeatures != null
1819                              ? TextUtils.join(",", requiredFeatures)
1820                              : null);
1821                }
1822            }.bind();
1823        } finally {
1824            restoreCallingIdentity(identityToken);
1825        }
1826    }
1827
1828    @Override
1829    public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
1830            final String authTokenType, final String[] requiredFeatures,
1831            final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
1832        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1833            Log.v(TAG, "addAccount: accountType " + accountType
1834                    + ", response " + response
1835                    + ", authTokenType " + authTokenType
1836                    + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1837                    + ", expectActivityLaunch " + expectActivityLaunch
1838                    + ", caller's uid " + Binder.getCallingUid()
1839                    + ", pid " + Binder.getCallingPid()
1840                    + ", for user id " + userId);
1841        }
1842        if (response == null) throw new IllegalArgumentException("response is null");
1843        if (accountType == null) throw new IllegalArgumentException("accountType is null");
1844        checkManageAccountsPermission();
1845
1846        // Only allow the system process to add accounts of other users
1847        enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1848                    + " trying to add account for " + userId);
1849
1850        // Is user disallowed from modifying accounts?
1851        if (!canUserModifyAccounts(userId)) {
1852            try {
1853                response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1854                        "User is not allowed to add an account!");
1855            } catch (RemoteException re) {
1856            }
1857            showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1858            return;
1859        }
1860        if (!canUserModifyAccountsForType(userId, accountType)) {
1861            try {
1862                response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1863                        "User cannot modify accounts of this type (policy).");
1864            } catch (RemoteException re) {
1865            }
1866            showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1867            return;
1868        }
1869
1870        UserAccounts accounts = getUserAccounts(userId);
1871        final int pid = Binder.getCallingPid();
1872        final int uid = Binder.getCallingUid();
1873        final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1874        options.putInt(AccountManager.KEY_CALLER_UID, uid);
1875        options.putInt(AccountManager.KEY_CALLER_PID, pid);
1876
1877        long identityToken = clearCallingIdentity();
1878        try {
1879            new Session(accounts, response, accountType, expectActivityLaunch,
1880                    true /* stripAuthTokenFromResult */) {
1881                @Override
1882                public void run() throws RemoteException {
1883                    mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1884                            options);
1885                }
1886
1887                @Override
1888                protected String toDebugString(long now) {
1889                    return super.toDebugString(now) + ", addAccount"
1890                            + ", accountType " + accountType
1891                            + ", requiredFeatures "
1892                            + (requiredFeatures != null
1893                              ? TextUtils.join(",", requiredFeatures)
1894                              : null);
1895                }
1896            }.bind();
1897        } finally {
1898            restoreCallingIdentity(identityToken);
1899        }
1900    }
1901
1902    private void showCantAddAccount(int errorCode) {
1903        Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1904        cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
1905        cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1906        long identityToken = clearCallingIdentity();
1907        try {
1908            mContext.startActivity(cantAddAccount);
1909        } finally {
1910            restoreCallingIdentity(identityToken);
1911        }
1912    }
1913
1914    @Override
1915    public void confirmCredentialsAsUser(IAccountManagerResponse response,
1916            final Account account, final Bundle options, final boolean expectActivityLaunch,
1917            int userId) {
1918        // Only allow the system process to read accounts of other users
1919        enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1920                    + " trying to confirm account credentials for " + userId);
1921
1922        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1923            Log.v(TAG, "confirmCredentials: " + account
1924                    + ", response " + response
1925                    + ", expectActivityLaunch " + expectActivityLaunch
1926                    + ", caller's uid " + Binder.getCallingUid()
1927                    + ", pid " + Binder.getCallingPid());
1928        }
1929        if (response == null) throw new IllegalArgumentException("response is null");
1930        if (account == null) throw new IllegalArgumentException("account is null");
1931        checkManageAccountsPermission();
1932        UserAccounts accounts = getUserAccounts(userId);
1933        long identityToken = clearCallingIdentity();
1934        try {
1935            new Session(accounts, response, account.type, expectActivityLaunch,
1936                    true /* stripAuthTokenFromResult */) {
1937                @Override
1938                public void run() throws RemoteException {
1939                    mAuthenticator.confirmCredentials(this, account, options);
1940                }
1941                @Override
1942                protected String toDebugString(long now) {
1943                    return super.toDebugString(now) + ", confirmCredentials"
1944                            + ", " + account;
1945                }
1946            }.bind();
1947        } finally {
1948            restoreCallingIdentity(identityToken);
1949        }
1950    }
1951
1952    @Override
1953    public void updateCredentials(IAccountManagerResponse response, final Account account,
1954            final String authTokenType, final boolean expectActivityLaunch,
1955            final Bundle loginOptions) {
1956        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1957            Log.v(TAG, "updateCredentials: " + account
1958                    + ", response " + response
1959                    + ", authTokenType " + authTokenType
1960                    + ", expectActivityLaunch " + expectActivityLaunch
1961                    + ", caller's uid " + Binder.getCallingUid()
1962                    + ", pid " + Binder.getCallingPid());
1963        }
1964        if (response == null) throw new IllegalArgumentException("response is null");
1965        if (account == null) throw new IllegalArgumentException("account is null");
1966        if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1967        checkManageAccountsPermission();
1968        UserAccounts accounts = getUserAccountsForCaller();
1969        long identityToken = clearCallingIdentity();
1970        try {
1971            new Session(accounts, response, account.type, expectActivityLaunch,
1972                    true /* stripAuthTokenFromResult */) {
1973                @Override
1974                public void run() throws RemoteException {
1975                    mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1976                }
1977                @Override
1978                protected String toDebugString(long now) {
1979                    if (loginOptions != null) loginOptions.keySet();
1980                    return super.toDebugString(now) + ", updateCredentials"
1981                            + ", " + account
1982                            + ", authTokenType " + authTokenType
1983                            + ", loginOptions " + loginOptions;
1984                }
1985            }.bind();
1986        } finally {
1987            restoreCallingIdentity(identityToken);
1988        }
1989    }
1990
1991    @Override
1992    public void editProperties(IAccountManagerResponse response, final String accountType,
1993            final boolean expectActivityLaunch) {
1994        if (Log.isLoggable(TAG, Log.VERBOSE)) {
1995            Log.v(TAG, "editProperties: accountType " + accountType
1996                    + ", response " + response
1997                    + ", expectActivityLaunch " + expectActivityLaunch
1998                    + ", caller's uid " + Binder.getCallingUid()
1999                    + ", pid " + Binder.getCallingPid());
2000        }
2001        if (response == null) throw new IllegalArgumentException("response is null");
2002        if (accountType == null) throw new IllegalArgumentException("accountType is null");
2003        checkManageAccountsPermission();
2004        UserAccounts accounts = getUserAccountsForCaller();
2005        long identityToken = clearCallingIdentity();
2006        try {
2007            new Session(accounts, response, accountType, expectActivityLaunch,
2008                    true /* stripAuthTokenFromResult */) {
2009                @Override
2010                public void run() throws RemoteException {
2011                    mAuthenticator.editProperties(this, mAccountType);
2012                }
2013                @Override
2014                protected String toDebugString(long now) {
2015                    return super.toDebugString(now) + ", editProperties"
2016                            + ", accountType " + accountType;
2017                }
2018            }.bind();
2019        } finally {
2020            restoreCallingIdentity(identityToken);
2021        }
2022    }
2023
2024    private class GetAccountsByTypeAndFeatureSession extends Session {
2025        private final String[] mFeatures;
2026        private volatile Account[] mAccountsOfType = null;
2027        private volatile ArrayList<Account> mAccountsWithFeatures = null;
2028        private volatile int mCurrentAccount = 0;
2029        private final int mCallingUid;
2030
2031        public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
2032                IAccountManagerResponse response, String type, String[] features, int callingUid) {
2033            super(accounts, response, type, false /* expectActivityLaunch */,
2034                    true /* stripAuthTokenFromResult */);
2035            mCallingUid = callingUid;
2036            mFeatures = features;
2037        }
2038
2039        @Override
2040        public void run() throws RemoteException {
2041            synchronized (mAccounts.cacheLock) {
2042                mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2043                        null);
2044            }
2045            // check whether each account matches the requested features
2046            mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2047            mCurrentAccount = 0;
2048
2049            checkAccount();
2050        }
2051
2052        public void checkAccount() {
2053            if (mCurrentAccount >= mAccountsOfType.length) {
2054                sendResult();
2055                return;
2056            }
2057
2058            final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2059            if (accountAuthenticator == null) {
2060                // It is possible that the authenticator has died, which is indicated by
2061                // mAuthenticator being set to null. If this happens then just abort.
2062                // There is no need to send back a result or error in this case since
2063                // that already happened when mAuthenticator was cleared.
2064                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2065                    Log.v(TAG, "checkAccount: aborting session since we are no longer"
2066                            + " connected to the authenticator, " + toDebugString());
2067                }
2068                return;
2069            }
2070            try {
2071                accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
2072            } catch (RemoteException e) {
2073                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
2074            }
2075        }
2076
2077        @Override
2078        public void onResult(Bundle result) {
2079            mNumResults++;
2080            if (result == null) {
2081                onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
2082                return;
2083            }
2084            if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
2085                mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2086            }
2087            mCurrentAccount++;
2088            checkAccount();
2089        }
2090
2091        public void sendResult() {
2092            IAccountManagerResponse response = getResponseAndClose();
2093            if (response != null) {
2094                try {
2095                    Account[] accounts = new Account[mAccountsWithFeatures.size()];
2096                    for (int i = 0; i < accounts.length; i++) {
2097                        accounts[i] = mAccountsWithFeatures.get(i);
2098                    }
2099                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2100                        Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2101                                + response);
2102                    }
2103                    Bundle result = new Bundle();
2104                    result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2105                    response.onResult(result);
2106                } catch (RemoteException e) {
2107                    // if the caller is dead then there is no one to care about remote exceptions
2108                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2109                        Log.v(TAG, "failure while notifying response", e);
2110                    }
2111                }
2112            }
2113        }
2114
2115
2116        @Override
2117        protected String toDebugString(long now) {
2118            return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2119                    + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2120        }
2121    }
2122
2123    /**
2124     * Returns the accounts for a specific user
2125     * @hide
2126     */
2127    public Account[] getAccounts(int userId) {
2128        checkReadAccountsPermission();
2129        UserAccounts accounts = getUserAccounts(userId);
2130        int callingUid = Binder.getCallingUid();
2131        long identityToken = clearCallingIdentity();
2132        try {
2133            synchronized (accounts.cacheLock) {
2134                return getAccountsFromCacheLocked(accounts, null, callingUid, null);
2135            }
2136        } finally {
2137            restoreCallingIdentity(identityToken);
2138        }
2139    }
2140
2141    /**
2142     * Returns accounts for all running users.
2143     *
2144     * @hide
2145     */
2146    public AccountAndUser[] getRunningAccounts() {
2147        final int[] runningUserIds;
2148        try {
2149            runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2150        } catch (RemoteException e) {
2151            // Running in system_server; should never happen
2152            throw new RuntimeException(e);
2153        }
2154        return getAccounts(runningUserIds);
2155    }
2156
2157    /** {@hide} */
2158    public AccountAndUser[] getAllAccounts() {
2159        final List<UserInfo> users = getUserManager().getUsers();
2160        final int[] userIds = new int[users.size()];
2161        for (int i = 0; i < userIds.length; i++) {
2162            userIds[i] = users.get(i).id;
2163        }
2164        return getAccounts(userIds);
2165    }
2166
2167    private AccountAndUser[] getAccounts(int[] userIds) {
2168        final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
2169        for (int userId : userIds) {
2170            UserAccounts userAccounts = getUserAccounts(userId);
2171            if (userAccounts == null) continue;
2172            synchronized (userAccounts.cacheLock) {
2173                Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2174                        Binder.getCallingUid(), null);
2175                for (int a = 0; a < accounts.length; a++) {
2176                    runningAccounts.add(new AccountAndUser(accounts[a], userId));
2177                }
2178            }
2179        }
2180
2181        AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2182        return runningAccounts.toArray(accountsArray);
2183    }
2184
2185    @Override
2186    public Account[] getAccountsAsUser(String type, int userId) {
2187        return getAccountsAsUser(type, userId, null, -1);
2188    }
2189
2190    private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2191            int packageUid) {
2192        int callingUid = Binder.getCallingUid();
2193        // Only allow the system process to read accounts of other users
2194        if (userId != UserHandle.getCallingUserId()
2195                && callingUid != Process.myUid()
2196                && mContext.checkCallingOrSelfPermission(
2197                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2198                    != PackageManager.PERMISSION_GRANTED) {
2199            throw new SecurityException("User " + UserHandle.getCallingUserId()
2200                    + " trying to get account for " + userId);
2201        }
2202
2203        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2204            Log.v(TAG, "getAccounts: accountType " + type
2205                    + ", caller's uid " + Binder.getCallingUid()
2206                    + ", pid " + Binder.getCallingPid());
2207        }
2208        // If the original calling app was using the framework account chooser activity, we'll
2209        // be passed in the original caller's uid here, which is what should be used for filtering.
2210        if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2211            callingUid = packageUid;
2212        }
2213        checkReadAccountsPermission();
2214        UserAccounts accounts = getUserAccounts(userId);
2215        long identityToken = clearCallingIdentity();
2216        try {
2217            synchronized (accounts.cacheLock) {
2218                return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
2219            }
2220        } finally {
2221            restoreCallingIdentity(identityToken);
2222        }
2223    }
2224
2225    @Override
2226    public boolean addSharedAccountAsUser(Account account, int userId) {
2227        userId = handleIncomingUser(userId);
2228        SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
2229        ContentValues values = new ContentValues();
2230        values.put(ACCOUNTS_NAME, account.name);
2231        values.put(ACCOUNTS_TYPE, account.type);
2232        db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2233                new String[] {account.name, account.type});
2234        long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2235        if (accountId < 0) {
2236            Log.w(TAG, "insertAccountIntoDatabase: " + account
2237                    + ", skipping the DB insert failed");
2238            return false;
2239        }
2240        return true;
2241    }
2242
2243    @Override
2244    public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2245        userId = handleIncomingUser(userId);
2246        UserAccounts accounts = getUserAccounts(userId);
2247        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2248        final ContentValues values = new ContentValues();
2249        values.put(ACCOUNTS_NAME, newName);
2250        values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2251        int r = db.update(
2252                TABLE_SHARED_ACCOUNTS,
2253                values,
2254                ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2255                new String[] { account.name, account.type });
2256        if (r > 0) {
2257            // Recursively rename the account.
2258            renameAccountInternal(accounts, account, newName);
2259        }
2260        return r > 0;
2261    }
2262
2263    @Override
2264    public boolean removeSharedAccountAsUser(Account account, int userId) {
2265        userId = handleIncomingUser(userId);
2266        UserAccounts accounts = getUserAccounts(userId);
2267        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2268        int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2269                new String[] {account.name, account.type});
2270        if (r > 0) {
2271            removeAccountInternal(accounts, account);
2272        }
2273        return r > 0;
2274    }
2275
2276    @Override
2277    public Account[] getSharedAccountsAsUser(int userId) {
2278        userId = handleIncomingUser(userId);
2279        UserAccounts accounts = getUserAccounts(userId);
2280        ArrayList<Account> accountList = new ArrayList<Account>();
2281        Cursor cursor = null;
2282        try {
2283            cursor = accounts.openHelper.getReadableDatabase()
2284                    .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2285                    null, null, null, null, null);
2286            if (cursor != null && cursor.moveToFirst()) {
2287                int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2288                int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2289                do {
2290                    accountList.add(new Account(cursor.getString(nameIndex),
2291                            cursor.getString(typeIndex)));
2292                } while (cursor.moveToNext());
2293            }
2294        } finally {
2295            if (cursor != null) {
2296                cursor.close();
2297            }
2298        }
2299        Account[] accountArray = new Account[accountList.size()];
2300        accountList.toArray(accountArray);
2301        return accountArray;
2302    }
2303
2304    @Override
2305    public Account[] getAccounts(String type) {
2306        return getAccountsAsUser(type, UserHandle.getCallingUserId());
2307    }
2308
2309    @Override
2310    public Account[] getAccountsForPackage(String packageName, int uid) {
2311        int callingUid = Binder.getCallingUid();
2312        if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2313            throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2314                    + callingUid + " with uid=" + uid);
2315        }
2316        return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2317    }
2318
2319    @Override
2320    public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2321        checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2322        int packageUid = -1;
2323        try {
2324            packageUid = AppGlobals.getPackageManager().getPackageUid(
2325                    packageName, UserHandle.getCallingUserId());
2326        } catch (RemoteException re) {
2327            Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2328            return new Account[0];
2329        }
2330        return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2331    }
2332
2333    @Override
2334    public void getAccountsByFeatures(IAccountManagerResponse response,
2335            String type, String[] features) {
2336        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2337            Log.v(TAG, "getAccounts: accountType " + type
2338                    + ", response " + response
2339                    + ", features " + stringArrayToString(features)
2340                    + ", caller's uid " + Binder.getCallingUid()
2341                    + ", pid " + Binder.getCallingPid());
2342        }
2343        if (response == null) throw new IllegalArgumentException("response is null");
2344        if (type == null) throw new IllegalArgumentException("accountType is null");
2345        checkReadAccountsPermission();
2346        UserAccounts userAccounts = getUserAccountsForCaller();
2347        int callingUid = Binder.getCallingUid();
2348        long identityToken = clearCallingIdentity();
2349        try {
2350            if (features == null || features.length == 0) {
2351                Account[] accounts;
2352                synchronized (userAccounts.cacheLock) {
2353                    accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
2354                }
2355                Bundle result = new Bundle();
2356                result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2357                onResult(response, result);
2358                return;
2359            }
2360            new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2361                    callingUid).bind();
2362        } finally {
2363            restoreCallingIdentity(identityToken);
2364        }
2365    }
2366
2367    private long getAccountIdLocked(SQLiteDatabase db, Account account) {
2368        Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
2369                "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2370        try {
2371            if (cursor.moveToNext()) {
2372                return cursor.getLong(0);
2373            }
2374            return -1;
2375        } finally {
2376            cursor.close();
2377        }
2378    }
2379
2380    private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
2381        Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2382                EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2383                new String[]{key}, null, null, null);
2384        try {
2385            if (cursor.moveToNext()) {
2386                return cursor.getLong(0);
2387            }
2388            return -1;
2389        } finally {
2390            cursor.close();
2391        }
2392    }
2393
2394    private abstract class Session extends IAccountAuthenticatorResponse.Stub
2395            implements IBinder.DeathRecipient, ServiceConnection {
2396        IAccountManagerResponse mResponse;
2397        final String mAccountType;
2398        final boolean mExpectActivityLaunch;
2399        final long mCreationTime;
2400
2401        public int mNumResults = 0;
2402        private int mNumRequestContinued = 0;
2403        private int mNumErrors = 0;
2404
2405        IAccountAuthenticator mAuthenticator = null;
2406
2407        private final boolean mStripAuthTokenFromResult;
2408        protected final UserAccounts mAccounts;
2409
2410        public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2411                boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
2412            super();
2413            //if (response == null) throw new IllegalArgumentException("response is null");
2414            if (accountType == null) throw new IllegalArgumentException("accountType is null");
2415            mAccounts = accounts;
2416            mStripAuthTokenFromResult = stripAuthTokenFromResult;
2417            mResponse = response;
2418            mAccountType = accountType;
2419            mExpectActivityLaunch = expectActivityLaunch;
2420            mCreationTime = SystemClock.elapsedRealtime();
2421            synchronized (mSessions) {
2422                mSessions.put(toString(), this);
2423            }
2424            if (response != null) {
2425                try {
2426                    response.asBinder().linkToDeath(this, 0 /* flags */);
2427                } catch (RemoteException e) {
2428                    mResponse = null;
2429                    binderDied();
2430                }
2431            }
2432        }
2433
2434        IAccountManagerResponse getResponseAndClose() {
2435            if (mResponse == null) {
2436                // this session has already been closed
2437                return null;
2438            }
2439            IAccountManagerResponse response = mResponse;
2440            close(); // this clears mResponse so we need to save the response before this call
2441            return response;
2442        }
2443
2444        private void close() {
2445            synchronized (mSessions) {
2446                if (mSessions.remove(toString()) == null) {
2447                    // the session was already closed, so bail out now
2448                    return;
2449                }
2450            }
2451            if (mResponse != null) {
2452                // stop listening for response deaths
2453                mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2454
2455                // clear this so that we don't accidentally send any further results
2456                mResponse = null;
2457            }
2458            cancelTimeout();
2459            unbind();
2460        }
2461
2462        @Override
2463        public void binderDied() {
2464            mResponse = null;
2465            close();
2466        }
2467
2468        protected String toDebugString() {
2469            return toDebugString(SystemClock.elapsedRealtime());
2470        }
2471
2472        protected String toDebugString(long now) {
2473            return "Session: expectLaunch " + mExpectActivityLaunch
2474                    + ", connected " + (mAuthenticator != null)
2475                    + ", stats (" + mNumResults + "/" + mNumRequestContinued
2476                    + "/" + mNumErrors + ")"
2477                    + ", lifetime " + ((now - mCreationTime) / 1000.0);
2478        }
2479
2480        void bind() {
2481            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2482                Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2483            }
2484            if (!bindToAuthenticator(mAccountType)) {
2485                Log.d(TAG, "bind attempt failed for " + toDebugString());
2486                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
2487            }
2488        }
2489
2490        private void unbind() {
2491            if (mAuthenticator != null) {
2492                mAuthenticator = null;
2493                mContext.unbindService(this);
2494            }
2495        }
2496
2497        public void scheduleTimeout() {
2498            mMessageHandler.sendMessageDelayed(
2499                    mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2500        }
2501
2502        public void cancelTimeout() {
2503            mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2504        }
2505
2506        @Override
2507        public void onServiceConnected(ComponentName name, IBinder service) {
2508            mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
2509            try {
2510                run();
2511            } catch (RemoteException e) {
2512                onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2513                        "remote exception");
2514            }
2515        }
2516
2517        @Override
2518        public void onServiceDisconnected(ComponentName name) {
2519            mAuthenticator = null;
2520            IAccountManagerResponse response = getResponseAndClose();
2521            if (response != null) {
2522                try {
2523                    response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2524                            "disconnected");
2525                } catch (RemoteException e) {
2526                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2527                        Log.v(TAG, "Session.onServiceDisconnected: "
2528                                + "caught RemoteException while responding", e);
2529                    }
2530                }
2531            }
2532        }
2533
2534        public abstract void run() throws RemoteException;
2535
2536        public void onTimedOut() {
2537            IAccountManagerResponse response = getResponseAndClose();
2538            if (response != null) {
2539                try {
2540                    response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2541                            "timeout");
2542                } catch (RemoteException e) {
2543                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2544                        Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2545                                e);
2546                    }
2547                }
2548            }
2549        }
2550
2551        @Override
2552        public void onResult(Bundle result) {
2553            mNumResults++;
2554            Intent intent = null;
2555            if (result != null
2556                    && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2557                /*
2558                 * The Authenticator API allows third party authenticators to
2559                 * supply arbitrary intents to other apps that they can run,
2560                 * this can be very bad when those apps are in the system like
2561                 * the System Settings.
2562                 */
2563                int authenticatorUid = Binder.getCallingUid();
2564                long bid = Binder.clearCallingIdentity();
2565                try {
2566                    PackageManager pm = mContext.getPackageManager();
2567                    ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2568                    int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2569                    if (PackageManager.SIGNATURE_MATCH !=
2570                            pm.checkSignatures(authenticatorUid, targetUid)) {
2571                        throw new SecurityException(
2572                                "Activity to be started with KEY_INTENT must " +
2573                               "share Authenticator's signatures");
2574                    }
2575                } finally {
2576                    Binder.restoreCallingIdentity(bid);
2577                }
2578            }
2579            if (result != null
2580                    && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2581                String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2582                String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2583                if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2584                    Account account = new Account(accountName, accountType);
2585                    cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2586                            new UserHandle(mAccounts.userId));
2587                }
2588            }
2589            IAccountManagerResponse response;
2590            if (mExpectActivityLaunch && result != null
2591                    && result.containsKey(AccountManager.KEY_INTENT)) {
2592                response = mResponse;
2593            } else {
2594                response = getResponseAndClose();
2595            }
2596            if (response != null) {
2597                try {
2598                    if (result == null) {
2599                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2600                            Log.v(TAG, getClass().getSimpleName()
2601                                    + " calling onError() on response " + response);
2602                        }
2603                        response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2604                                "null bundle returned");
2605                    } else {
2606                        if (mStripAuthTokenFromResult) {
2607                            result.remove(AccountManager.KEY_AUTHTOKEN);
2608                        }
2609                        if (Log.isLoggable(TAG, Log.VERBOSE)) {
2610                            Log.v(TAG, getClass().getSimpleName()
2611                                    + " calling onResult() on response " + response);
2612                        }
2613                        if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2614                                (intent == null)) {
2615                            // All AccountManager error codes are greater than 0
2616                            response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2617                                    result.getString(AccountManager.KEY_ERROR_MESSAGE));
2618                        } else {
2619                            response.onResult(result);
2620                        }
2621                    }
2622                } catch (RemoteException e) {
2623                    // if the caller is dead then there is no one to care about remote exceptions
2624                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2625                        Log.v(TAG, "failure while notifying response", e);
2626                    }
2627                }
2628            }
2629        }
2630
2631        @Override
2632        public void onRequestContinued() {
2633            mNumRequestContinued++;
2634        }
2635
2636        @Override
2637        public void onError(int errorCode, String errorMessage) {
2638            mNumErrors++;
2639            IAccountManagerResponse response = getResponseAndClose();
2640            if (response != null) {
2641                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2642                    Log.v(TAG, getClass().getSimpleName()
2643                            + " calling onError() on response " + response);
2644                }
2645                try {
2646                    response.onError(errorCode, errorMessage);
2647                } catch (RemoteException e) {
2648                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
2649                        Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2650                    }
2651                }
2652            } else {
2653                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2654                    Log.v(TAG, "Session.onError: already closed");
2655                }
2656            }
2657        }
2658
2659        /**
2660         * find the component name for the authenticator and initiate a bind
2661         * if no authenticator or the bind fails then return false, otherwise return true
2662         */
2663        private boolean bindToAuthenticator(String authenticatorType) {
2664            final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2665            authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2666                    AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
2667            if (authenticatorInfo == null) {
2668                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2669                    Log.v(TAG, "there is no authenticator for " + authenticatorType
2670                            + ", bailing out");
2671                }
2672                return false;
2673            }
2674
2675            Intent intent = new Intent();
2676            intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2677            intent.setComponent(authenticatorInfo.componentName);
2678            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2679                Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2680            }
2681            if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2682                    new UserHandle(mAccounts.userId))) {
2683                if (Log.isLoggable(TAG, Log.VERBOSE)) {
2684                    Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2685                }
2686                return false;
2687            }
2688
2689
2690            return true;
2691        }
2692    }
2693
2694    private class MessageHandler extends Handler {
2695        MessageHandler(Looper looper) {
2696            super(looper);
2697        }
2698
2699        @Override
2700        public void handleMessage(Message msg) {
2701            switch (msg.what) {
2702                case MESSAGE_TIMED_OUT:
2703                    Session session = (Session)msg.obj;
2704                    session.onTimedOut();
2705                    break;
2706
2707                case MESSAGE_COPY_SHARED_ACCOUNT:
2708                    copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2709                    break;
2710
2711                default:
2712                    throw new IllegalStateException("unhandled message: " + msg.what);
2713            }
2714        }
2715    }
2716
2717    private static String getDatabaseName(int userId) {
2718        File systemDir = Environment.getSystemSecureDirectory();
2719        File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
2720        if (userId == 0) {
2721            // Migrate old file, if it exists, to the new location.
2722            // Make sure the new file doesn't already exist. A dummy file could have been
2723            // accidentally created in the old location, causing the new one to become corrupted
2724            // as well.
2725            File oldFile = new File(systemDir, DATABASE_NAME);
2726            if (oldFile.exists() && !databaseFile.exists()) {
2727                // Check for use directory; create if it doesn't exist, else renameTo will fail
2728                File userDir = Environment.getUserSystemDirectory(userId);
2729                if (!userDir.exists()) {
2730                    if (!userDir.mkdirs()) {
2731                        throw new IllegalStateException("User dir cannot be created: " + userDir);
2732                    }
2733                }
2734                if (!oldFile.renameTo(databaseFile)) {
2735                    throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2736                }
2737            }
2738        }
2739        return databaseFile.getPath();
2740    }
2741
2742    static class DatabaseHelper extends SQLiteOpenHelper {
2743
2744        public DatabaseHelper(Context context, int userId) {
2745            super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
2746        }
2747
2748        /**
2749         * This call needs to be made while the mCacheLock is held. The way to
2750         * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2751         * @param db The database.
2752         */
2753        @Override
2754        public void onCreate(SQLiteDatabase db) {
2755            db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2756                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2757                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
2758                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2759                    + ACCOUNTS_PASSWORD + " TEXT, "
2760                    + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
2761                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2762
2763            db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " (  "
2764                    + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,  "
2765                    + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2766                    + AUTHTOKENS_TYPE + " TEXT NOT NULL,  "
2767                    + AUTHTOKENS_AUTHTOKEN + " TEXT,  "
2768                    + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2769
2770            createGrantsTable(db);
2771
2772            db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2773                    + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2774                    + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2775                    + EXTRAS_KEY + " TEXT NOT NULL, "
2776                    + EXTRAS_VALUE + " TEXT, "
2777                    + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2778
2779            db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2780                    + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2781                    + META_VALUE + " TEXT)");
2782
2783            createSharedAccountsTable(db);
2784
2785            createAccountsDeletionTrigger(db);
2786        }
2787
2788        private void createSharedAccountsTable(SQLiteDatabase db) {
2789            db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2790                    + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2791                    + ACCOUNTS_NAME + " TEXT NOT NULL, "
2792                    + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2793                    + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2794        }
2795
2796        private void addOldAccountNameColumn(SQLiteDatabase db) {
2797            db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
2798        }
2799
2800        private void createAccountsDeletionTrigger(SQLiteDatabase db) {
2801            db.execSQL(""
2802                    + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2803                    + " BEGIN"
2804                    + "   DELETE FROM " + TABLE_AUTHTOKENS
2805                    + "     WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2806                    + "   DELETE FROM " + TABLE_EXTRAS
2807                    + "     WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2808                    + "   DELETE FROM " + TABLE_GRANTS
2809                    + "     WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2810                    + " END");
2811        }
2812
2813        private void createGrantsTable(SQLiteDatabase db) {
2814            db.execSQL("CREATE TABLE " + TABLE_GRANTS + " (  "
2815                    + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2816                    + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL,  "
2817                    + GRANTS_GRANTEE_UID + " INTEGER NOT NULL,  "
2818                    + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2819                    +   "," + GRANTS_GRANTEE_UID + "))");
2820        }
2821
2822        @Override
2823        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
2824            Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
2825
2826            if (oldVersion == 1) {
2827                // no longer need to do anything since the work is done
2828                // when upgrading from version 2
2829                oldVersion++;
2830            }
2831
2832            if (oldVersion == 2) {
2833                createGrantsTable(db);
2834                db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2835                createAccountsDeletionTrigger(db);
2836                oldVersion++;
2837            }
2838
2839            if (oldVersion == 3) {
2840                db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2841                        " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2842                oldVersion++;
2843            }
2844
2845            if (oldVersion == 4) {
2846                createSharedAccountsTable(db);
2847                oldVersion++;
2848            }
2849
2850            if (oldVersion == 5) {
2851                addOldAccountNameColumn(db);
2852                oldVersion++;
2853            }
2854
2855            if (oldVersion != newVersion) {
2856                Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2857            }
2858        }
2859
2860        @Override
2861        public void onOpen(SQLiteDatabase db) {
2862            if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2863        }
2864    }
2865
2866    public IBinder onBind(Intent intent) {
2867        return asBinder();
2868    }
2869
2870    /**
2871     * Searches array of arguments for the specified string
2872     * @param args array of argument strings
2873     * @param value value to search for
2874     * @return true if the value is contained in the array
2875     */
2876    private static boolean scanArgs(String[] args, String value) {
2877        if (args != null) {
2878            for (String arg : args) {
2879                if (value.equals(arg)) {
2880                    return true;
2881                }
2882            }
2883        }
2884        return false;
2885    }
2886
2887    @Override
2888    protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
2889        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2890                != PackageManager.PERMISSION_GRANTED) {
2891            fout.println("Permission Denial: can't dump AccountsManager from from pid="
2892                    + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2893                    + " without permission " + android.Manifest.permission.DUMP);
2894            return;
2895        }
2896        final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
2897        final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, "  ");
2898
2899        final List<UserInfo> users = getUserManager().getUsers();
2900        for (UserInfo user : users) {
2901            ipw.println("User " + user + ":");
2902            ipw.increaseIndent();
2903            dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2904            ipw.println();
2905            ipw.decreaseIndent();
2906        }
2907    }
2908
2909    private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2910            String[] args, boolean isCheckinRequest) {
2911        synchronized (userAccounts.cacheLock) {
2912            final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
2913
2914            if (isCheckinRequest) {
2915                // This is a checkin request. *Only* upload the account types and the count of each.
2916                Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2917                        null, null, ACCOUNTS_TYPE, null, null);
2918                try {
2919                    while (cursor.moveToNext()) {
2920                        // print type,count
2921                        fout.println(cursor.getString(0) + "," + cursor.getString(1));
2922                    }
2923                } finally {
2924                    if (cursor != null) {
2925                        cursor.close();
2926                    }
2927                }
2928            } else {
2929                Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
2930                        Process.myUid(), null);
2931                fout.println("Accounts: " + accounts.length);
2932                for (Account account : accounts) {
2933                    fout.println("  " + account);
2934                }
2935
2936                fout.println();
2937                synchronized (mSessions) {
2938                    final long now = SystemClock.elapsedRealtime();
2939                    fout.println("Active Sessions: " + mSessions.size());
2940                    for (Session session : mSessions.values()) {
2941                        fout.println("  " + session.toDebugString(now));
2942                    }
2943                }
2944
2945                fout.println();
2946                mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
2947            }
2948        }
2949    }
2950
2951    private void doNotification(UserAccounts accounts, Account account, CharSequence message,
2952            Intent intent, int userId) {
2953        long identityToken = clearCallingIdentity();
2954        try {
2955            if (Log.isLoggable(TAG, Log.VERBOSE)) {
2956                Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2957            }
2958
2959            if (intent.getComponent() != null &&
2960                    GrantCredentialsPermissionActivity.class.getName().equals(
2961                            intent.getComponent().getClassName())) {
2962                createNoCredentialsPermissionNotification(account, intent, userId);
2963            } else {
2964                final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
2965                intent.addCategory(String.valueOf(notificationId));
2966                Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2967                        0 /* when */);
2968                UserHandle user = new UserHandle(userId);
2969                final String notificationTitleFormat =
2970                        mContext.getText(R.string.notification_title).toString();
2971                n.setLatestEventInfo(mContext,
2972                        String.format(notificationTitleFormat, account.name),
2973                        message, PendingIntent.getActivityAsUser(
2974                        mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
2975                        null, user));
2976                installNotification(notificationId, n, user);
2977            }
2978        } finally {
2979            restoreCallingIdentity(identityToken);
2980        }
2981    }
2982
2983    protected void installNotification(final int notificationId, final Notification n,
2984            UserHandle user) {
2985        ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
2986                .notifyAsUser(null, notificationId, n, user);
2987    }
2988
2989    protected void cancelNotification(int id, UserHandle user) {
2990        long identityToken = clearCallingIdentity();
2991        try {
2992            ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
2993                .cancelAsUser(null, id, user);
2994        } finally {
2995            restoreCallingIdentity(identityToken);
2996        }
2997    }
2998
2999    /** Succeeds if any of the specified permissions are granted. */
3000    private void checkBinderPermission(String... permissions) {
3001        final int uid = Binder.getCallingUid();
3002
3003        for (String perm : permissions) {
3004            if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3005                if (Log.isLoggable(TAG, Log.VERBOSE)) {
3006                    Log.v(TAG, "  caller uid " + uid + " has " + perm);
3007                }
3008                return;
3009            }
3010        }
3011
3012        String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
3013        Log.w(TAG, "  " + msg);
3014        throw new SecurityException(msg);
3015    }
3016
3017    private int handleIncomingUser(int userId) {
3018        try {
3019            return ActivityManagerNative.getDefault().handleIncomingUser(
3020                    Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3021        } catch (RemoteException re) {
3022            // Shouldn't happen, local.
3023        }
3024        return userId;
3025    }
3026
3027    private boolean isPrivileged(int callingUid) {
3028        final int callingUserId = UserHandle.getUserId(callingUid);
3029
3030        final PackageManager userPackageManager;
3031        try {
3032            userPackageManager = mContext.createPackageContextAsUser(
3033                    "android", 0, new UserHandle(callingUserId)).getPackageManager();
3034        } catch (NameNotFoundException e) {
3035            return false;
3036        }
3037
3038        String[] packages = userPackageManager.getPackagesForUid(callingUid);
3039        for (String name : packages) {
3040            try {
3041                PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
3042                if (packageInfo != null
3043                        && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
3044                    return true;
3045                }
3046            } catch (PackageManager.NameNotFoundException e) {
3047                return false;
3048            }
3049        }
3050        return false;
3051    }
3052
3053    private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
3054        final boolean isPrivileged = isPrivileged(callerUid);
3055        final boolean fromAuthenticator = account != null
3056                && hasAuthenticatorUid(account.type, callerUid);
3057        final boolean hasExplicitGrants = account != null
3058                && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
3059        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3060            Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
3061                    + callerUid + ", " + account
3062                    + ": is authenticator? " + fromAuthenticator
3063                    + ", has explicit permission? " + hasExplicitGrants);
3064        }
3065        return fromAuthenticator || hasExplicitGrants || isPrivileged;
3066    }
3067
3068    private boolean hasAuthenticatorUid(String accountType, int callingUid) {
3069        final int callingUserId = UserHandle.getUserId(callingUid);
3070        for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
3071                mAuthenticatorCache.getAllServices(callingUserId)) {
3072            if (serviceInfo.type.type.equals(accountType)) {
3073                return (serviceInfo.uid == callingUid) ||
3074                        (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
3075                                == PackageManager.SIGNATURE_MATCH);
3076            }
3077        }
3078        return false;
3079    }
3080
3081    private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3082            int callerUid) {
3083        if (callerUid == Process.SYSTEM_UID) {
3084            return true;
3085        }
3086        UserAccounts accounts = getUserAccountsForCaller();
3087        synchronized (accounts.cacheLock) {
3088            final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3089            String[] args = { String.valueOf(callerUid), authTokenType,
3090                    account.name, account.type};
3091            final boolean permissionGranted =
3092                    DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3093            if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3094                // TODO: Skip this check when running automated tests. Replace this
3095                // with a more general solution.
3096                Log.d(TAG, "no credentials permission for usage of " + account + ", "
3097                        + authTokenType + " by uid " + callerUid
3098                        + " but ignoring since device is in test harness.");
3099                return true;
3100            }
3101            return permissionGranted;
3102        }
3103    }
3104
3105    private void checkCallingUidAgainstAuthenticator(Account account) {
3106        final int uid = Binder.getCallingUid();
3107        if (account == null || !hasAuthenticatorUid(account.type, uid)) {
3108            String msg = "caller uid " + uid + " is different than the authenticator's uid";
3109            Log.w(TAG, msg);
3110            throw new SecurityException(msg);
3111        }
3112        if (Log.isLoggable(TAG, Log.VERBOSE)) {
3113            Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
3114        }
3115    }
3116
3117    private void checkAuthenticateAccountsPermission(Account account) {
3118        checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3119        checkCallingUidAgainstAuthenticator(account);
3120    }
3121
3122    private void checkReadAccountsPermission() {
3123        checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3124    }
3125
3126    private void checkManageAccountsPermission() {
3127        checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3128    }
3129
3130    private void checkManageAccountsOrUseCredentialsPermissions() {
3131        checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3132                Manifest.permission.USE_CREDENTIALS);
3133    }
3134
3135    private boolean canUserModifyAccounts(int userId) {
3136        if (getUserManager().getUserRestrictions(new UserHandle(userId))
3137                .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3138            return false;
3139        }
3140        return true;
3141    }
3142
3143    private boolean canUserModifyAccountsForType(int userId, String accountType) {
3144        DevicePolicyManager dpm = (DevicePolicyManager) mContext
3145                .getSystemService(Context.DEVICE_POLICY_SERVICE);
3146        String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
3147        if (typesArray == null) {
3148            return true;
3149        }
3150        for (String forbiddenType : typesArray) {
3151            if (forbiddenType.equals(accountType)) {
3152                return false;
3153            }
3154        }
3155        return true;
3156    }
3157
3158    @Override
3159    public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3160            throws RemoteException {
3161        final int callingUid = getCallingUid();
3162
3163        if (callingUid != Process.SYSTEM_UID) {
3164            throw new SecurityException();
3165        }
3166
3167        if (value) {
3168            grantAppPermission(account, authTokenType, uid);
3169        } else {
3170            revokeAppPermission(account, authTokenType, uid);
3171        }
3172    }
3173
3174    /**
3175     * Allow callers with the given uid permission to get credentials for account/authTokenType.
3176     * <p>
3177     * Although this is public it can only be accessed via the AccountManagerService object
3178     * which is in the system. This means we don't need to protect it with permissions.
3179     * @hide
3180     */
3181    private void grantAppPermission(Account account, String authTokenType, int uid) {
3182        if (account == null || authTokenType == null) {
3183            Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
3184            return;
3185        }
3186        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
3187        synchronized (accounts.cacheLock) {
3188            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3189            db.beginTransaction();
3190            try {
3191                long accountId = getAccountIdLocked(db, account);
3192                if (accountId >= 0) {
3193                    ContentValues values = new ContentValues();
3194                    values.put(GRANTS_ACCOUNTS_ID, accountId);
3195                    values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3196                    values.put(GRANTS_GRANTEE_UID, uid);
3197                    db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3198                    db.setTransactionSuccessful();
3199                }
3200            } finally {
3201                db.endTransaction();
3202            }
3203            cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3204                    new UserHandle(accounts.userId));
3205        }
3206    }
3207
3208    /**
3209     * Don't allow callers with the given uid permission to get credentials for
3210     * account/authTokenType.
3211     * <p>
3212     * Although this is public it can only be accessed via the AccountManagerService object
3213     * which is in the system. This means we don't need to protect it with permissions.
3214     * @hide
3215     */
3216    private void revokeAppPermission(Account account, String authTokenType, int uid) {
3217        if (account == null || authTokenType == null) {
3218            Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
3219            return;
3220        }
3221        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
3222        synchronized (accounts.cacheLock) {
3223            final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3224            db.beginTransaction();
3225            try {
3226                long accountId = getAccountIdLocked(db, account);
3227                if (accountId >= 0) {
3228                    db.delete(TABLE_GRANTS,
3229                            GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3230                                    + GRANTS_GRANTEE_UID + "=?",
3231                            new String[]{String.valueOf(accountId), authTokenType,
3232                                    String.valueOf(uid)});
3233                    db.setTransactionSuccessful();
3234                }
3235            } finally {
3236                db.endTransaction();
3237            }
3238            cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3239                    new UserHandle(accounts.userId));
3240        }
3241    }
3242
3243    static final private String stringArrayToString(String[] value) {
3244        return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3245    }
3246
3247    private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3248        final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
3249        if (oldAccountsForType != null) {
3250            ArrayList<Account> newAccountsList = new ArrayList<Account>();
3251            for (Account curAccount : oldAccountsForType) {
3252                if (!curAccount.equals(account)) {
3253                    newAccountsList.add(curAccount);
3254                }
3255            }
3256            if (newAccountsList.isEmpty()) {
3257                accounts.accountCache.remove(account.type);
3258            } else {
3259                Account[] newAccountsForType = new Account[newAccountsList.size()];
3260                newAccountsForType = newAccountsList.toArray(newAccountsForType);
3261                accounts.accountCache.put(account.type, newAccountsForType);
3262            }
3263        }
3264        accounts.userDataCache.remove(account);
3265        accounts.authTokenCache.remove(account);
3266        accounts.previousNameCache.remove(account);
3267    }
3268
3269    /**
3270     * This assumes that the caller has already checked that the account is not already present.
3271     */
3272    private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3273        Account[] accountsForType = accounts.accountCache.get(account.type);
3274        int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3275        Account[] newAccountsForType = new Account[oldLength + 1];
3276        if (accountsForType != null) {
3277            System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
3278        }
3279        newAccountsForType[oldLength] = account;
3280        accounts.accountCache.put(account.type, newAccountsForType);
3281    }
3282
3283    private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
3284            int callingUid, String callingPackage) {
3285        if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
3286                || callingUid == Process.myUid()) {
3287            return unfiltered;
3288        }
3289        UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3290        if (user != null && user.isRestricted()) {
3291            String[] packages = mPackageManager.getPackagesForUid(callingUid);
3292            // If any of the packages is a white listed package, return the full set,
3293            // otherwise return non-shared accounts only.
3294            // This might be a temporary way to specify a whitelist
3295            String whiteList = mContext.getResources().getString(
3296                    com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3297            for (String packageName : packages) {
3298                if (whiteList.contains(";" + packageName + ";")) {
3299                    return unfiltered;
3300                }
3301            }
3302            ArrayList<Account> allowed = new ArrayList<Account>();
3303            Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3304            if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
3305            String requiredAccountType = "";
3306            try {
3307                // If there's an explicit callingPackage specified, check if that package
3308                // opted in to see restricted accounts.
3309                if (callingPackage != null) {
3310                    PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
3311                    if (pi != null && pi.restrictedAccountType != null) {
3312                        requiredAccountType = pi.restrictedAccountType;
3313                    }
3314                } else {
3315                    // Otherwise check if the callingUid has a package that has opted in
3316                    for (String packageName : packages) {
3317                        PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3318                        if (pi != null && pi.restrictedAccountType != null) {
3319                            requiredAccountType = pi.restrictedAccountType;
3320                            break;
3321                        }
3322                    }
3323                }
3324            } catch (NameNotFoundException nnfe) {
3325            }
3326            for (Account account : unfiltered) {
3327                if (account.type.equals(requiredAccountType)) {
3328                    allowed.add(account);
3329                } else {
3330                    boolean found = false;
3331                    for (Account shared : sharedAccounts) {
3332                        if (shared.equals(account)) {
3333                            found = true;
3334                            break;
3335                        }
3336                    }
3337                    if (!found) {
3338                        allowed.add(account);
3339                    }
3340                }
3341            }
3342            Account[] filtered = new Account[allowed.size()];
3343            allowed.toArray(filtered);
3344            return filtered;
3345        } else {
3346            return unfiltered;
3347        }
3348    }
3349
3350    /*
3351     * packageName can be null. If not null, it should be used to filter out restricted accounts
3352     * that the package is not allowed to access.
3353     */
3354    protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
3355            int callingUid, String callingPackage) {
3356        if (accountType != null) {
3357            final Account[] accounts = userAccounts.accountCache.get(accountType);
3358            if (accounts == null) {
3359                return EMPTY_ACCOUNT_ARRAY;
3360            } else {
3361                return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
3362                        callingUid, callingPackage);
3363            }
3364        } else {
3365            int totalLength = 0;
3366            for (Account[] accounts : userAccounts.accountCache.values()) {
3367                totalLength += accounts.length;
3368            }
3369            if (totalLength == 0) {
3370                return EMPTY_ACCOUNT_ARRAY;
3371            }
3372            Account[] accounts = new Account[totalLength];
3373            totalLength = 0;
3374            for (Account[] accountsOfType : userAccounts.accountCache.values()) {
3375                System.arraycopy(accountsOfType, 0, accounts, totalLength,
3376                        accountsOfType.length);
3377                totalLength += accountsOfType.length;
3378            }
3379            return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
3380        }
3381    }
3382
3383    protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3384            Account account, String key, String value) {
3385        HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
3386        if (userDataForAccount == null) {
3387            userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
3388            accounts.userDataCache.put(account, userDataForAccount);
3389        }
3390        if (value == null) {
3391            userDataForAccount.remove(key);
3392        } else {
3393            userDataForAccount.put(key, value);
3394        }
3395    }
3396
3397    protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3398            Account account, String key, String value) {
3399        HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
3400        if (authTokensForAccount == null) {
3401            authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
3402            accounts.authTokenCache.put(account, authTokensForAccount);
3403        }
3404        if (value == null) {
3405            authTokensForAccount.remove(key);
3406        } else {
3407            authTokensForAccount.put(key, value);
3408        }
3409    }
3410
3411    protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3412            String authTokenType) {
3413        synchronized (accounts.cacheLock) {
3414            HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
3415            if (authTokensForAccount == null) {
3416                // need to populate the cache for this account
3417                final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3418                authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
3419                accounts.authTokenCache.put(account, authTokensForAccount);
3420            }
3421            return authTokensForAccount.get(authTokenType);
3422        }
3423    }
3424
3425    protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3426        synchronized (accounts.cacheLock) {
3427            HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
3428            if (userDataForAccount == null) {
3429                // need to populate the cache for this account
3430                final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3431                userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
3432                accounts.userDataCache.put(account, userDataForAccount);
3433            }
3434            return userDataForAccount.get(key);
3435        }
3436    }
3437
3438    protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3439            final SQLiteDatabase db, Account account) {
3440        HashMap<String, String> userDataForAccount = new HashMap<String, String>();
3441        Cursor cursor = db.query(TABLE_EXTRAS,
3442                COLUMNS_EXTRAS_KEY_AND_VALUE,
3443                SELECTION_USERDATA_BY_ACCOUNT,
3444                new String[]{account.name, account.type},
3445                null, null, null);
3446        try {
3447            while (cursor.moveToNext()) {
3448                final String tmpkey = cursor.getString(0);
3449                final String value = cursor.getString(1);
3450                userDataForAccount.put(tmpkey, value);
3451            }
3452        } finally {
3453            cursor.close();
3454        }
3455        return userDataForAccount;
3456    }
3457
3458    protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3459            final SQLiteDatabase db, Account account) {
3460        HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
3461        Cursor cursor = db.query(TABLE_AUTHTOKENS,
3462                COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3463                SELECTION_AUTHTOKENS_BY_ACCOUNT,
3464                new String[]{account.name, account.type},
3465                null, null, null);
3466        try {
3467            while (cursor.moveToNext()) {
3468                final String type = cursor.getString(0);
3469                final String authToken = cursor.getString(1);
3470                authTokensForAccount.put(type, authToken);
3471            }
3472        } finally {
3473            cursor.close();
3474        }
3475        return authTokensForAccount;
3476    }
3477}
3478