UserManagerService.java revision a6db4ab6193626c880970572a0d03db511d403af
1/*
2 * Copyright (C) 2011 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.pm;
18
19import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
20
21import android.app.Activity;
22import android.app.ActivityManager;
23import android.app.ActivityManagerNative;
24import android.app.ActivityThread;
25import android.app.IStopUserCallback;
26import android.content.BroadcastReceiver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.pm.ApplicationInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.content.pm.UserInfo;
33import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
35import android.os.Binder;
36import android.os.Bundle;
37import android.os.Environment;
38import android.os.FileUtils;
39import android.os.Handler;
40import android.os.IUserManager;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.UserHandle;
44import android.os.UserManager;
45import android.util.AtomicFile;
46import android.util.Log;
47import android.util.Slog;
48import android.util.SparseArray;
49import android.util.SparseBooleanArray;
50import android.util.TimeUtils;
51import android.util.Xml;
52
53import com.android.internal.content.PackageMonitor;
54import com.android.internal.util.ArrayUtils;
55import com.android.internal.util.FastXmlSerializer;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
61import java.io.BufferedOutputStream;
62import java.io.File;
63import java.io.FileDescriptor;
64import java.io.FileInputStream;
65import java.io.FileNotFoundException;
66import java.io.FileOutputStream;
67import java.io.IOException;
68import java.io.PrintWriter;
69import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
72import java.util.ArrayList;
73import java.util.List;
74
75public class UserManagerService extends IUserManager.Stub {
76
77    private static final String LOG_TAG = "UserManagerService";
78
79    private static final boolean DBG = false;
80
81    private static final String TAG_NAME = "name";
82    private static final String ATTR_FLAGS = "flags";
83    private static final String ATTR_ICON_PATH = "icon";
84    private static final String ATTR_ID = "id";
85    private static final String ATTR_CREATION_TIME = "created";
86    private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
87    private static final String ATTR_SALT = "salt";
88    private static final String ATTR_PIN_HASH = "pinHash";
89    private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
90    private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
91    private static final String ATTR_SERIAL_NO = "serialNumber";
92    private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
93    private static final String ATTR_PARTIAL = "partial";
94    private static final String ATTR_USER_VERSION = "version";
95    private static final String TAG_USERS = "users";
96    private static final String TAG_USER = "user";
97    private static final String TAG_RESTRICTIONS = "restrictions";
98    private static final String TAG_ENTRY = "entry";
99    private static final String TAG_VALUE = "value";
100    private static final String ATTR_KEY = "key";
101    private static final String ATTR_VALUE_TYPE = "type";
102    private static final String ATTR_MULTIPLE = "m";
103
104    private static final String ATTR_TYPE_STRING_ARRAY = "sa";
105    private static final String ATTR_TYPE_STRING = "s";
106    private static final String ATTR_TYPE_BOOLEAN = "b";
107
108    private static final String USER_INFO_DIR = "system" + File.separator + "users";
109    private static final String USER_LIST_FILENAME = "userlist.xml";
110    private static final String USER_PHOTO_FILENAME = "photo.png";
111
112    private static final String RESTRICTIONS_FILE_PREFIX = "res_";
113    private static final String XML_SUFFIX = ".xml";
114
115    private static final int MIN_USER_ID = 10;
116
117    private static final int USER_VERSION = 4;
118
119    private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
120
121    // Number of attempts before jumping to the next BACKOFF_TIMES slot
122    private static final int BACKOFF_INC_INTERVAL = 5;
123
124    // Amount of time to force the user to wait before entering the PIN again, after failing
125    // BACKOFF_INC_INTERVAL times.
126    private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
127
128    private final Context mContext;
129    private final PackageManagerService mPm;
130    private final Object mInstallLock;
131    private final Object mPackagesLock;
132
133    private final Handler mHandler;
134
135    private final File mUsersDir;
136    private final File mUserListFile;
137    private final File mBaseUserPath;
138
139    private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
140    private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
141
142    class RestrictionsPinState {
143        long salt;
144        String pinHash;
145        int failedAttempts;
146        long lastAttemptTime;
147    }
148
149    private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
150            new SparseArray<RestrictionsPinState>();
151
152    /**
153     * Set of user IDs being actively removed. Removed IDs linger in this set
154     * for several seconds to work around a VFS caching issue.
155     */
156    // @GuardedBy("mPackagesLock")
157    private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
158
159    private int[] mUserIds;
160    private boolean mGuestEnabled;
161    private int mNextSerialNumber;
162    private int mUserVersion = 0;
163
164    private static UserManagerService sInstance;
165
166    public static UserManagerService getInstance() {
167        synchronized (UserManagerService.class) {
168            return sInstance;
169        }
170    }
171
172    /**
173     * Available for testing purposes.
174     */
175    UserManagerService(File dataDir, File baseUserPath) {
176        this(null, null, new Object(), new Object(), dataDir, baseUserPath);
177    }
178
179    /**
180     * Called by package manager to create the service.  This is closely
181     * associated with the package manager, and the given lock is the
182     * package manager's own lock.
183     */
184    UserManagerService(Context context, PackageManagerService pm,
185            Object installLock, Object packagesLock) {
186        this(context, pm, installLock, packagesLock,
187                Environment.getDataDirectory(),
188                new File(Environment.getDataDirectory(), "user"));
189    }
190
191    /**
192     * Available for testing purposes.
193     */
194    private UserManagerService(Context context, PackageManagerService pm,
195            Object installLock, Object packagesLock,
196            File dataDir, File baseUserPath) {
197        mContext = context;
198        mPm = pm;
199        mInstallLock = installLock;
200        mPackagesLock = packagesLock;
201        mHandler = new Handler();
202        synchronized (mInstallLock) {
203            synchronized (mPackagesLock) {
204                mUsersDir = new File(dataDir, USER_INFO_DIR);
205                mUsersDir.mkdirs();
206                // Make zeroth user directory, for services to migrate their files to that location
207                File userZeroDir = new File(mUsersDir, "0");
208                userZeroDir.mkdirs();
209                mBaseUserPath = baseUserPath;
210                FileUtils.setPermissions(mUsersDir.toString(),
211                        FileUtils.S_IRWXU|FileUtils.S_IRWXG
212                        |FileUtils.S_IROTH|FileUtils.S_IXOTH,
213                        -1, -1);
214                mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
215                readUserListLocked();
216                // Prune out any partially created/partially removed users.
217                ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
218                for (int i = 0; i < mUsers.size(); i++) {
219                    UserInfo ui = mUsers.valueAt(i);
220                    if (ui.partial && i != 0) {
221                        partials.add(ui);
222                    }
223                }
224                for (int i = 0; i < partials.size(); i++) {
225                    UserInfo ui = partials.get(i);
226                    Slog.w(LOG_TAG, "Removing partially created user #" + i
227                            + " (name=" + ui.name + ")");
228                    removeUserStateLocked(ui.id);
229                }
230                sInstance = this;
231            }
232        }
233    }
234
235    void systemReady() {
236        mUserPackageMonitor.register(mContext, null, UserHandle.ALL, false);
237        userForeground(UserHandle.USER_OWNER);
238    }
239
240    @Override
241    public List<UserInfo> getUsers(boolean excludeDying) {
242        checkManageUsersPermission("query users");
243        synchronized (mPackagesLock) {
244            ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
245            for (int i = 0; i < mUsers.size(); i++) {
246                UserInfo ui = mUsers.valueAt(i);
247                if (ui.partial) {
248                    continue;
249                }
250                if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
251                    users.add(ui);
252                }
253            }
254            return users;
255        }
256    }
257
258    @Override
259    public UserInfo getUserInfo(int userId) {
260        checkManageUsersPermission("query user");
261        synchronized (mPackagesLock) {
262            return getUserInfoLocked(userId);
263        }
264    }
265
266    @Override
267    public boolean isRestricted() {
268        synchronized (mPackagesLock) {
269            return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
270        }
271    }
272
273    /*
274     * Should be locked on mUsers before calling this.
275     */
276    private UserInfo getUserInfoLocked(int userId) {
277        UserInfo ui = mUsers.get(userId);
278        // If it is partial and not in the process of being removed, return as unknown user.
279        if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
280            Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
281            return null;
282        }
283        return ui;
284    }
285
286    public boolean exists(int userId) {
287        synchronized (mPackagesLock) {
288            return ArrayUtils.contains(mUserIds, userId);
289        }
290    }
291
292    @Override
293    public void setUserName(int userId, String name) {
294        checkManageUsersPermission("rename users");
295        boolean changed = false;
296        synchronized (mPackagesLock) {
297            UserInfo info = mUsers.get(userId);
298            if (info == null || info.partial) {
299                Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
300                return;
301            }
302            if (name != null && !name.equals(info.name)) {
303                info.name = name;
304                writeUserLocked(info);
305                changed = true;
306            }
307        }
308        if (changed) {
309            sendUserInfoChangedBroadcast(userId);
310        }
311    }
312
313    @Override
314    public void setUserIcon(int userId, Bitmap bitmap) {
315        checkManageUsersPermission("update users");
316        synchronized (mPackagesLock) {
317            UserInfo info = mUsers.get(userId);
318            if (info == null || info.partial) {
319                Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
320                return;
321            }
322            writeBitmapLocked(info, bitmap);
323            writeUserLocked(info);
324        }
325        sendUserInfoChangedBroadcast(userId);
326    }
327
328    private void sendUserInfoChangedBroadcast(int userId) {
329        Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
330        changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
331        changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
332        mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
333    }
334
335    @Override
336    public Bitmap getUserIcon(int userId) {
337        checkManageUsersPermission("read users");
338        synchronized (mPackagesLock) {
339            UserInfo info = mUsers.get(userId);
340            if (info == null || info.partial) {
341                Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
342                return null;
343            }
344            if (info.iconPath == null) {
345                return null;
346            }
347            return BitmapFactory.decodeFile(info.iconPath);
348        }
349    }
350
351    @Override
352    public void setGuestEnabled(boolean enable) {
353        checkManageUsersPermission("enable guest users");
354        synchronized (mPackagesLock) {
355            if (mGuestEnabled != enable) {
356                mGuestEnabled = enable;
357                // Erase any guest user that currently exists
358                for (int i = 0; i < mUsers.size(); i++) {
359                    UserInfo user = mUsers.valueAt(i);
360                    if (!user.partial && user.isGuest()) {
361                        if (!enable) {
362                            removeUser(user.id);
363                        }
364                        return;
365                    }
366                }
367                // No guest was found
368                if (enable) {
369                    createUser("Guest", UserInfo.FLAG_GUEST);
370                }
371            }
372        }
373    }
374
375    @Override
376    public boolean isGuestEnabled() {
377        synchronized (mPackagesLock) {
378            return mGuestEnabled;
379        }
380    }
381
382    @Override
383    public void wipeUser(int userHandle) {
384        checkManageUsersPermission("wipe user");
385        // TODO:
386    }
387
388    public void makeInitialized(int userId) {
389        checkManageUsersPermission("makeInitialized");
390        synchronized (mPackagesLock) {
391            UserInfo info = mUsers.get(userId);
392            if (info == null || info.partial) {
393                Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
394            }
395            if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
396                info.flags |= UserInfo.FLAG_INITIALIZED;
397                writeUserLocked(info);
398            }
399        }
400    }
401
402    @Override
403    public Bundle getUserRestrictions(int userId) {
404        // checkManageUsersPermission("getUserRestrictions");
405
406        synchronized (mPackagesLock) {
407            Bundle restrictions = mUserRestrictions.get(userId);
408            return restrictions != null ? restrictions : Bundle.EMPTY;
409        }
410    }
411
412    @Override
413    public void setUserRestrictions(Bundle restrictions, int userId) {
414        checkManageUsersPermission("setUserRestrictions");
415        if (restrictions == null) return;
416
417        synchronized (mPackagesLock) {
418            mUserRestrictions.get(userId).clear();
419            mUserRestrictions.get(userId).putAll(restrictions);
420            writeUserLocked(mUsers.get(userId));
421        }
422    }
423
424    /**
425     * Check if we've hit the limit of how many users can be created.
426     */
427    private boolean isUserLimitReachedLocked() {
428        int nUsers = mUsers.size();
429        return nUsers >= UserManager.getMaxSupportedUsers();
430    }
431
432    /**
433     * Enforces that only the system UID or root's UID or apps that have the
434     * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
435     * permission can make certain calls to the UserManager.
436     *
437     * @param message used as message if SecurityException is thrown
438     * @throws SecurityException if the caller is not system or root
439     */
440    private static final void checkManageUsersPermission(String message) {
441        final int uid = Binder.getCallingUid();
442        if (uid != Process.SYSTEM_UID && uid != 0
443                && ActivityManager.checkComponentPermission(
444                        android.Manifest.permission.MANAGE_USERS,
445                        uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
446            throw new SecurityException("You need MANAGE_USERS permission to: " + message);
447        }
448    }
449
450    private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
451        try {
452            File dir = new File(mUsersDir, Integer.toString(info.id));
453            File file = new File(dir, USER_PHOTO_FILENAME);
454            if (!dir.exists()) {
455                dir.mkdir();
456                FileUtils.setPermissions(
457                        dir.getPath(),
458                        FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
459                        -1, -1);
460            }
461            FileOutputStream os;
462            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
463                info.iconPath = file.getAbsolutePath();
464            }
465            try {
466                os.close();
467            } catch (IOException ioe) {
468                // What the ... !
469            }
470        } catch (FileNotFoundException e) {
471            Slog.w(LOG_TAG, "Error setting photo for user ", e);
472        }
473    }
474
475    /**
476     * Returns an array of user ids. This array is cached here for quick access, so do not modify or
477     * cache it elsewhere.
478     * @return the array of user ids.
479     */
480    public int[] getUserIds() {
481        synchronized (mPackagesLock) {
482            return mUserIds;
483        }
484    }
485
486    int[] getUserIdsLPr() {
487        return mUserIds;
488    }
489
490    private void readUserListLocked() {
491        mGuestEnabled = false;
492        if (!mUserListFile.exists()) {
493            fallbackToSingleUserLocked();
494            return;
495        }
496        FileInputStream fis = null;
497        AtomicFile userListFile = new AtomicFile(mUserListFile);
498        try {
499            fis = userListFile.openRead();
500            XmlPullParser parser = Xml.newPullParser();
501            parser.setInput(fis, null);
502            int type;
503            while ((type = parser.next()) != XmlPullParser.START_TAG
504                    && type != XmlPullParser.END_DOCUMENT) {
505                ;
506            }
507
508            if (type != XmlPullParser.START_TAG) {
509                Slog.e(LOG_TAG, "Unable to read user list");
510                fallbackToSingleUserLocked();
511                return;
512            }
513
514            mNextSerialNumber = -1;
515            if (parser.getName().equals(TAG_USERS)) {
516                String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
517                if (lastSerialNumber != null) {
518                    mNextSerialNumber = Integer.parseInt(lastSerialNumber);
519                }
520                String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
521                if (versionNumber != null) {
522                    mUserVersion = Integer.parseInt(versionNumber);
523                }
524            }
525
526            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
527                if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
528                    String id = parser.getAttributeValue(null, ATTR_ID);
529                    UserInfo user = readUserLocked(Integer.parseInt(id));
530
531                    if (user != null) {
532                        mUsers.put(user.id, user);
533                        if (user.isGuest()) {
534                            mGuestEnabled = true;
535                        }
536                        if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
537                            mNextSerialNumber = user.id + 1;
538                        }
539                    }
540                }
541            }
542            updateUserIdsLocked();
543            upgradeIfNecessaryLocked();
544        } catch (IOException ioe) {
545            fallbackToSingleUserLocked();
546        } catch (XmlPullParserException pe) {
547            fallbackToSingleUserLocked();
548        } finally {
549            if (fis != null) {
550                try {
551                    fis.close();
552                } catch (IOException e) {
553                }
554            }
555        }
556    }
557
558    /**
559     * Upgrade steps between versions, either for fixing bugs or changing the data format.
560     */
561    private void upgradeIfNecessaryLocked() {
562        int userVersion = mUserVersion;
563        if (userVersion < 1) {
564            // Assign a proper name for the owner, if not initialized correctly before
565            UserInfo user = mUsers.get(UserHandle.USER_OWNER);
566            if ("Primary".equals(user.name)) {
567                user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
568                writeUserLocked(user);
569            }
570            userVersion = 1;
571        }
572
573        if (userVersion < 2) {
574            // Owner should be marked as initialized
575            UserInfo user = mUsers.get(UserHandle.USER_OWNER);
576            if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
577                user.flags |= UserInfo.FLAG_INITIALIZED;
578                writeUserLocked(user);
579            }
580            userVersion = 2;
581        }
582
583
584        if (userVersion < 4) {
585            userVersion = 4;
586        }
587
588        if (userVersion < USER_VERSION) {
589            Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
590                    + USER_VERSION);
591        } else {
592            mUserVersion = userVersion;
593            writeUserListLocked();
594        }
595    }
596
597    private void fallbackToSingleUserLocked() {
598        // Create the primary user
599        UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
600                mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
601                UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
602        mUsers.put(0, primary);
603        mNextSerialNumber = MIN_USER_ID;
604        mUserVersion = USER_VERSION;
605
606        Bundle restrictions = new Bundle();
607        mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
608
609        updateUserIdsLocked();
610
611        writeUserListLocked();
612        writeUserLocked(primary);
613    }
614
615    /*
616     * Writes the user file in this format:
617     *
618     * <user flags="20039023" id="0">
619     *   <name>Primary</name>
620     * </user>
621     */
622    private void writeUserLocked(UserInfo userInfo) {
623        FileOutputStream fos = null;
624        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
625        try {
626            fos = userFile.startWrite();
627            final BufferedOutputStream bos = new BufferedOutputStream(fos);
628
629            // XmlSerializer serializer = XmlUtils.serializerInstance();
630            final XmlSerializer serializer = new FastXmlSerializer();
631            serializer.setOutput(bos, "utf-8");
632            serializer.startDocument(null, true);
633            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
634
635            serializer.startTag(null, TAG_USER);
636            serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
637            serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
638            serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
639            serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
640            serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
641                    Long.toString(userInfo.lastLoggedInTime));
642            RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
643            if (pinState != null) {
644                if (pinState.salt != 0) {
645                    serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
646                }
647                if (pinState.pinHash != null) {
648                    serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
649                }
650                if (pinState.failedAttempts != 0) {
651                    serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
652                            Integer.toString(pinState.failedAttempts));
653                    serializer.attribute(null, ATTR_LAST_RETRY_MS,
654                            Long.toString(pinState.lastAttemptTime));
655                }
656            }
657            if (userInfo.iconPath != null) {
658                serializer.attribute(null,  ATTR_ICON_PATH, userInfo.iconPath);
659            }
660            if (userInfo.partial) {
661                serializer.attribute(null, ATTR_PARTIAL, "true");
662            }
663
664            serializer.startTag(null, TAG_NAME);
665            serializer.text(userInfo.name);
666            serializer.endTag(null, TAG_NAME);
667
668            Bundle restrictions = mUserRestrictions.get(userInfo.id);
669            if (restrictions != null) {
670                serializer.startTag(null, TAG_RESTRICTIONS);
671                writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
672                writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
673                writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
674                writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
675                writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
676                writeBoolean(serializer, restrictions,
677                        UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
678                writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
679                writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
680                writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
681                writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
682                serializer.endTag(null, TAG_RESTRICTIONS);
683            }
684            serializer.endTag(null, TAG_USER);
685
686            serializer.endDocument();
687            userFile.finishWrite(fos);
688        } catch (Exception ioe) {
689            Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
690            userFile.failWrite(fos);
691        }
692    }
693
694    /*
695     * Writes the user list file in this format:
696     *
697     * <users nextSerialNumber="3">
698     *   <user id="0"></user>
699     *   <user id="2"></user>
700     * </users>
701     */
702    private void writeUserListLocked() {
703        FileOutputStream fos = null;
704        AtomicFile userListFile = new AtomicFile(mUserListFile);
705        try {
706            fos = userListFile.startWrite();
707            final BufferedOutputStream bos = new BufferedOutputStream(fos);
708
709            // XmlSerializer serializer = XmlUtils.serializerInstance();
710            final XmlSerializer serializer = new FastXmlSerializer();
711            serializer.setOutput(bos, "utf-8");
712            serializer.startDocument(null, true);
713            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
714
715            serializer.startTag(null, TAG_USERS);
716            serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
717            serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
718
719            for (int i = 0; i < mUsers.size(); i++) {
720                UserInfo user = mUsers.valueAt(i);
721                serializer.startTag(null, TAG_USER);
722                serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
723                serializer.endTag(null, TAG_USER);
724            }
725
726            serializer.endTag(null, TAG_USERS);
727
728            serializer.endDocument();
729            userListFile.finishWrite(fos);
730        } catch (Exception e) {
731            userListFile.failWrite(fos);
732            Slog.e(LOG_TAG, "Error writing user list");
733        }
734    }
735
736    private UserInfo readUserLocked(int id) {
737        int flags = 0;
738        int serialNumber = id;
739        String name = null;
740        String iconPath = null;
741        long creationTime = 0L;
742        long lastLoggedInTime = 0L;
743        long salt = 0L;
744        String pinHash = null;
745        int failedAttempts = 0;
746        long lastAttemptTime = 0L;
747        boolean partial = false;
748        Bundle restrictions = new Bundle();
749
750        FileInputStream fis = null;
751        try {
752            AtomicFile userFile =
753                    new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
754            fis = userFile.openRead();
755            XmlPullParser parser = Xml.newPullParser();
756            parser.setInput(fis, null);
757            int type;
758            while ((type = parser.next()) != XmlPullParser.START_TAG
759                    && type != XmlPullParser.END_DOCUMENT) {
760                ;
761            }
762
763            if (type != XmlPullParser.START_TAG) {
764                Slog.e(LOG_TAG, "Unable to read user " + id);
765                return null;
766            }
767
768            if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
769                int storedId = readIntAttribute(parser, ATTR_ID, -1);
770                if (storedId != id) {
771                    Slog.e(LOG_TAG, "User id does not match the file name");
772                    return null;
773                }
774                serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
775                flags = readIntAttribute(parser, ATTR_FLAGS, 0);
776                iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
777                creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
778                lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
779                salt = readLongAttribute(parser, ATTR_SALT, 0L);
780                pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
781                failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
782                lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
783                String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
784                if ("true".equals(valueString)) {
785                    partial = true;
786                }
787
788                int outerDepth = parser.getDepth();
789                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
790                       && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
791                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
792                        continue;
793                    }
794                    String tag = parser.getName();
795                    if (TAG_NAME.equals(tag)) {
796                        type = parser.next();
797                        if (type == XmlPullParser.TEXT) {
798                            name = parser.getText();
799                        }
800                    } else if (TAG_RESTRICTIONS.equals(tag)) {
801                        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
802                        readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
803                        readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
804                        readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
805                        readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
806                        readBoolean(parser, restrictions,
807                                UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
808                        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
809                        readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
810                        readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
811                        readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
812                    }
813                }
814            }
815
816            UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
817            userInfo.serialNumber = serialNumber;
818            userInfo.creationTime = creationTime;
819            userInfo.lastLoggedInTime = lastLoggedInTime;
820            userInfo.partial = partial;
821            mUserRestrictions.append(id, restrictions);
822            if (salt != 0L) {
823                RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
824                if (pinState == null) {
825                    pinState = new RestrictionsPinState();
826                    mRestrictionsPinStates.put(id, pinState);
827                }
828                pinState.salt = salt;
829                pinState.pinHash = pinHash;
830                pinState.failedAttempts = failedAttempts;
831                pinState.lastAttemptTime = lastAttemptTime;
832            }
833            return userInfo;
834
835        } catch (IOException ioe) {
836        } catch (XmlPullParserException pe) {
837        } finally {
838            if (fis != null) {
839                try {
840                    fis.close();
841                } catch (IOException e) {
842                }
843            }
844        }
845        return null;
846    }
847
848    private void readBoolean(XmlPullParser parser, Bundle restrictions,
849            String restrictionKey) {
850        String value = parser.getAttributeValue(null, restrictionKey);
851        if (value != null) {
852            restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
853        }
854    }
855
856    private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
857            throws IOException {
858        if (restrictions.containsKey(restrictionKey)) {
859            xml.attribute(null, restrictionKey,
860                    Boolean.toString(restrictions.getBoolean(restrictionKey)));
861        }
862    }
863
864    private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
865        String valueString = parser.getAttributeValue(null, attr);
866        if (valueString == null) return defaultValue;
867        try {
868            return Integer.parseInt(valueString);
869        } catch (NumberFormatException nfe) {
870            return defaultValue;
871        }
872    }
873
874    private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
875        String valueString = parser.getAttributeValue(null, attr);
876        if (valueString == null) return defaultValue;
877        try {
878            return Long.parseLong(valueString);
879        } catch (NumberFormatException nfe) {
880            return defaultValue;
881        }
882    }
883
884    private boolean isPackageInstalled(String pkg, int userId) {
885        final ApplicationInfo info = mPm.getApplicationInfo(pkg,
886                PackageManager.GET_UNINSTALLED_PACKAGES,
887                userId);
888        if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
889            return false;
890        }
891        return true;
892    }
893
894    /**
895     * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
896     * else removes only those packages that have been uninstalled.
897     * Does not do any permissions checking.
898     */
899    private void cleanAppRestrictions(int userId, boolean all) {
900        synchronized (mPackagesLock) {
901            File dir = Environment.getUserSystemDirectory(userId);
902            String[] files = dir.list();
903            if (files == null) return;
904            for (String fileName : files) {
905                if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
906                    File resFile = new File(dir, fileName);
907                    if (resFile.exists()) {
908                        if (all) {
909                            resFile.delete();
910                        } else {
911                            String pkg = restrictionsFileNameToPackage(fileName);
912                            if (!isPackageInstalled(pkg, userId)) {
913                                resFile.delete();
914                            }
915                        }
916                    }
917                }
918            }
919        }
920    }
921
922    /**
923     * Removes the app restrictions file for a specific package and user id, if it exists.
924     */
925    private void cleanAppRestrictionsForPackage(String pkg, int userId) {
926        synchronized (mPackagesLock) {
927            File dir = Environment.getUserSystemDirectory(userId);
928            File resFile = new File(dir, packageToRestrictionsFileName(pkg));
929            if (resFile.exists()) {
930                resFile.delete();
931            }
932        }
933    }
934
935    @Override
936    public UserInfo createUser(String name, int flags) {
937        checkManageUsersPermission("Only the system can create users");
938
939        final long ident = Binder.clearCallingIdentity();
940        final UserInfo userInfo;
941        try {
942            synchronized (mInstallLock) {
943                synchronized (mPackagesLock) {
944                    if (isUserLimitReachedLocked()) return null;
945                    int userId = getNextAvailableIdLocked();
946                    userInfo = new UserInfo(userId, name, null, flags);
947                    File userPath = new File(mBaseUserPath, Integer.toString(userId));
948                    userInfo.serialNumber = mNextSerialNumber++;
949                    long now = System.currentTimeMillis();
950                    userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
951                    userInfo.partial = true;
952                    Environment.getUserSystemDirectory(userInfo.id).mkdirs();
953                    mUsers.put(userId, userInfo);
954                    writeUserListLocked();
955                    writeUserLocked(userInfo);
956                    mPm.createNewUserLILPw(userId, userPath);
957                    userInfo.partial = false;
958                    writeUserLocked(userInfo);
959                    updateUserIdsLocked();
960                    Bundle restrictions = new Bundle();
961                    mUserRestrictions.append(userId, restrictions);
962                }
963            }
964            if (userInfo != null) {
965                Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
966                addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
967                mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
968                        android.Manifest.permission.MANAGE_USERS);
969            }
970        } finally {
971            Binder.restoreCallingIdentity(ident);
972        }
973        return userInfo;
974    }
975
976    /**
977     * Removes a user and all data directories created for that user. This method should be called
978     * after the user's processes have been terminated.
979     * @param id the user's id
980     */
981    public boolean removeUser(int userHandle) {
982        checkManageUsersPermission("Only the system can remove users");
983        final UserInfo user;
984        synchronized (mPackagesLock) {
985            user = mUsers.get(userHandle);
986            if (userHandle == 0 || user == null) {
987                return false;
988            }
989            mRemovingUserIds.put(userHandle, true);
990            // Set this to a partially created user, so that the user will be purged
991            // on next startup, in case the runtime stops now before stopping and
992            // removing the user completely.
993            user.partial = true;
994            writeUserLocked(user);
995        }
996        if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
997        int res;
998        try {
999            res = ActivityManagerNative.getDefault().stopUser(userHandle,
1000                    new IStopUserCallback.Stub() {
1001                        @Override
1002                        public void userStopped(int userId) {
1003                            finishRemoveUser(userId);
1004                        }
1005                        @Override
1006                        public void userStopAborted(int userId) {
1007                        }
1008            });
1009        } catch (RemoteException e) {
1010            return false;
1011        }
1012
1013        return res == ActivityManager.USER_OP_SUCCESS;
1014    }
1015
1016    void finishRemoveUser(final int userHandle) {
1017        if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
1018        // Let other services shutdown any activity and clean up their state before completely
1019        // wiping the user's system directory and removing from the user list
1020        long ident = Binder.clearCallingIdentity();
1021        try {
1022            Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1023            addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
1024            mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1025                    android.Manifest.permission.MANAGE_USERS,
1026
1027                    new BroadcastReceiver() {
1028                        @Override
1029                        public void onReceive(Context context, Intent intent) {
1030                            if (DBG) {
1031                                Slog.i(LOG_TAG,
1032                                        "USER_REMOVED broadcast sent, cleaning up user data "
1033                                        + userHandle);
1034                            }
1035                            new Thread() {
1036                                public void run() {
1037                                    synchronized (mInstallLock) {
1038                                        synchronized (mPackagesLock) {
1039                                            removeUserStateLocked(userHandle);
1040                                        }
1041                                    }
1042                                }
1043                            }.start();
1044                        }
1045                    },
1046
1047                    null, Activity.RESULT_OK, null, null);
1048        } finally {
1049            Binder.restoreCallingIdentity(ident);
1050        }
1051    }
1052
1053    private void removeUserStateLocked(final int userHandle) {
1054        // Cleanup package manager settings
1055        mPm.cleanUpUserLILPw(userHandle);
1056
1057        // Remove this user from the list
1058        mUsers.remove(userHandle);
1059
1060        // Have user ID linger for several seconds to let external storage VFS
1061        // cache entries expire. This must be greater than the 'entry_valid'
1062        // timeout used by the FUSE daemon.
1063        mHandler.postDelayed(new Runnable() {
1064            @Override
1065            public void run() {
1066                synchronized (mPackagesLock) {
1067                    mRemovingUserIds.delete(userHandle);
1068                }
1069            }
1070        }, MINUTE_IN_MILLIS);
1071
1072        mRestrictionsPinStates.remove(userHandle);
1073        // Remove user file
1074        AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
1075        userFile.delete();
1076        // Update the user list
1077        writeUserListLocked();
1078        updateUserIdsLocked();
1079        removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1080    }
1081
1082    private void removeDirectoryRecursive(File parent) {
1083        if (parent.isDirectory()) {
1084            String[] files = parent.list();
1085            for (String filename : files) {
1086                File child = new File(parent, filename);
1087                removeDirectoryRecursive(child);
1088            }
1089        }
1090        parent.delete();
1091    }
1092
1093    @Override
1094    public Bundle getApplicationRestrictions(String packageName) {
1095        return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1096    }
1097
1098    @Override
1099    public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
1100        if (UserHandle.getCallingUserId() != userId
1101                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1102            checkManageUsersPermission("Only system can get restrictions for other users/apps");
1103        }
1104        synchronized (mPackagesLock) {
1105            // Read the restrictions from XML
1106            return readApplicationRestrictionsLocked(packageName, userId);
1107        }
1108    }
1109
1110    @Override
1111    public void setApplicationRestrictions(String packageName, Bundle restrictions,
1112            int userId) {
1113        if (UserHandle.getCallingUserId() != userId
1114                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
1115            checkManageUsersPermission("Only system can set restrictions for other users/apps");
1116        }
1117        synchronized (mPackagesLock) {
1118            // Write the restrictions to XML
1119            writeApplicationRestrictionsLocked(packageName, restrictions, userId);
1120        }
1121    }
1122
1123    @Override
1124    public boolean setRestrictionsChallenge(String newPin) {
1125        checkManageUsersPermission("Only system can modify the restrictions pin");
1126        int userId = UserHandle.getCallingUserId();
1127        synchronized (mPackagesLock) {
1128            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1129            if (pinState == null) {
1130                pinState = new RestrictionsPinState();
1131            }
1132            if (newPin == null) {
1133                pinState.salt = 0;
1134                pinState.pinHash = null;
1135            } else {
1136                try {
1137                    pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1138                } catch (NoSuchAlgorithmException e) {
1139                    pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1140                }
1141                pinState.pinHash = passwordToHash(newPin, pinState.salt);
1142                pinState.failedAttempts = 0;
1143            }
1144            mRestrictionsPinStates.put(userId, pinState);
1145            writeUserLocked(mUsers.get(userId));
1146        }
1147        return true;
1148    }
1149
1150    @Override
1151    public int checkRestrictionsChallenge(String pin) {
1152        checkManageUsersPermission("Only system can verify the restrictions pin");
1153        int userId = UserHandle.getCallingUserId();
1154        synchronized (mPackagesLock) {
1155            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1156            // If there's no pin set, return error code
1157            if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1158                return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1159            } else if (pin == null) {
1160                // If just checking if user can be prompted, return remaining time
1161                int waitTime = getRemainingTimeForPinAttempt(pinState);
1162                Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1163                return waitTime;
1164            } else {
1165                int waitTime = getRemainingTimeForPinAttempt(pinState);
1166                Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1167                if (waitTime > 0) {
1168                    return waitTime;
1169                }
1170                if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1171                    pinState.failedAttempts = 0;
1172                    writeUserLocked(mUsers.get(userId));
1173                    return UserManager.PIN_VERIFICATION_SUCCESS;
1174                } else {
1175                    pinState.failedAttempts++;
1176                    pinState.lastAttemptTime = System.currentTimeMillis();
1177                    writeUserLocked(mUsers.get(userId));
1178                    return waitTime;
1179                }
1180            }
1181        }
1182    }
1183
1184    private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1185        int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1186                BACKOFF_TIMES.length - 1);
1187        int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1188                BACKOFF_TIMES[backoffIndex] : 0;
1189        return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1190                0);
1191    }
1192
1193    @Override
1194    public boolean hasRestrictionsChallenge() {
1195        int userId = UserHandle.getCallingUserId();
1196        synchronized (mPackagesLock) {
1197            return hasRestrictionsPinLocked(userId);
1198        }
1199    }
1200
1201    private boolean hasRestrictionsPinLocked(int userId) {
1202        RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1203        if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1204            return false;
1205        }
1206        return true;
1207    }
1208
1209    @Override
1210    public void removeRestrictions() {
1211        checkManageUsersPermission("Only system can remove restrictions");
1212        final int userHandle = UserHandle.getCallingUserId();
1213        removeRestrictionsForUser(userHandle, true);
1214    }
1215
1216    private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
1217        synchronized (mPackagesLock) {
1218            // Remove all user restrictions
1219            setUserRestrictions(new Bundle(), userHandle);
1220            // Remove restrictions pin
1221            setRestrictionsChallenge(null);
1222            // Remove any app restrictions
1223            cleanAppRestrictions(userHandle, true);
1224        }
1225        if (unblockApps) {
1226            unblockAllAppsForUser(userHandle);
1227        }
1228    }
1229
1230    private void unblockAllAppsForUser(final int userHandle) {
1231        mHandler.post(new Runnable() {
1232            @Override
1233            public void run() {
1234                List<ApplicationInfo> apps =
1235                        mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1236                                userHandle).getList();
1237                final long ident = Binder.clearCallingIdentity();
1238                try {
1239                    for (ApplicationInfo appInfo : apps) {
1240                        if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1241                                && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1242                            mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1243                                    userHandle);
1244                        }
1245                    }
1246                } finally {
1247                    Binder.restoreCallingIdentity(ident);
1248                }
1249            }
1250        });
1251    }
1252
1253    /*
1254     * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1255     * Not the most secure, but it is at least a second level of protection. First level is that
1256     * the file is in a location only readable by the system process.
1257     * @param password the password.
1258     * @param salt the randomly generated salt
1259     * @return the hash of the pattern in a String.
1260     */
1261    private String passwordToHash(String password, long salt) {
1262        if (password == null) {
1263            return null;
1264        }
1265        String algo = null;
1266        String hashed = salt + password;
1267        try {
1268            byte[] saltedPassword = (password + salt).getBytes();
1269            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1270            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1271            hashed = toHex(sha1) + toHex(md5);
1272        } catch (NoSuchAlgorithmException e) {
1273            Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1274        }
1275        return hashed;
1276    }
1277
1278    private static String toHex(byte[] ary) {
1279        final String hex = "0123456789ABCDEF";
1280        String ret = "";
1281        for (int i = 0; i < ary.length; i++) {
1282            ret += hex.charAt((ary[i] >> 4) & 0xf);
1283            ret += hex.charAt(ary[i] & 0xf);
1284        }
1285        return ret;
1286    }
1287
1288    private int getUidForPackage(String packageName) {
1289        long ident = Binder.clearCallingIdentity();
1290        try {
1291            return mContext.getPackageManager().getApplicationInfo(packageName,
1292                    PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1293        } catch (NameNotFoundException nnfe) {
1294            return -1;
1295        } finally {
1296            Binder.restoreCallingIdentity(ident);
1297        }
1298    }
1299
1300    private Bundle readApplicationRestrictionsLocked(String packageName,
1301            int userId) {
1302        final Bundle restrictions = new Bundle();
1303        final ArrayList<String> values = new ArrayList<String>();
1304
1305        FileInputStream fis = null;
1306        try {
1307            AtomicFile restrictionsFile =
1308                    new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1309                            packageToRestrictionsFileName(packageName)));
1310            fis = restrictionsFile.openRead();
1311            XmlPullParser parser = Xml.newPullParser();
1312            parser.setInput(fis, null);
1313            int type;
1314            while ((type = parser.next()) != XmlPullParser.START_TAG
1315                    && type != XmlPullParser.END_DOCUMENT) {
1316                ;
1317            }
1318
1319            if (type != XmlPullParser.START_TAG) {
1320                Slog.e(LOG_TAG, "Unable to read restrictions file "
1321                        + restrictionsFile.getBaseFile());
1322                return restrictions;
1323            }
1324
1325            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1326                if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1327                    String key = parser.getAttributeValue(null, ATTR_KEY);
1328                    String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
1329                    String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1330                    if (multiple != null) {
1331                        int count = Integer.parseInt(multiple);
1332                        while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1333                            if (type == XmlPullParser.START_TAG
1334                                    && parser.getName().equals(TAG_VALUE)) {
1335                                values.add(parser.nextText().trim());
1336                                count--;
1337                            }
1338                        }
1339                        String [] valueStrings = new String[values.size()];
1340                        values.toArray(valueStrings);
1341                        restrictions.putStringArray(key, valueStrings);
1342                    } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1343                        restrictions.putBoolean(key, Boolean.parseBoolean(
1344                                parser.nextText().trim()));
1345                    } else {
1346                        String value = parser.nextText().trim();
1347                        restrictions.putString(key, value);
1348                    }
1349                }
1350            }
1351
1352        } catch (IOException ioe) {
1353        } catch (XmlPullParserException pe) {
1354        } finally {
1355            if (fis != null) {
1356                try {
1357                    fis.close();
1358                } catch (IOException e) {
1359                }
1360            }
1361        }
1362        return restrictions;
1363    }
1364
1365    private void writeApplicationRestrictionsLocked(String packageName,
1366            Bundle restrictions, int userId) {
1367        FileOutputStream fos = null;
1368        AtomicFile restrictionsFile = new AtomicFile(
1369                new File(Environment.getUserSystemDirectory(userId),
1370                        packageToRestrictionsFileName(packageName)));
1371        try {
1372            fos = restrictionsFile.startWrite();
1373            final BufferedOutputStream bos = new BufferedOutputStream(fos);
1374
1375            // XmlSerializer serializer = XmlUtils.serializerInstance();
1376            final XmlSerializer serializer = new FastXmlSerializer();
1377            serializer.setOutput(bos, "utf-8");
1378            serializer.startDocument(null, true);
1379            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1380
1381            serializer.startTag(null, TAG_RESTRICTIONS);
1382
1383            for (String key : restrictions.keySet()) {
1384                Object value = restrictions.get(key);
1385                serializer.startTag(null, TAG_ENTRY);
1386                serializer.attribute(null, ATTR_KEY, key);
1387
1388                if (value instanceof Boolean) {
1389                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1390                    serializer.text(value.toString());
1391                } else if (value == null || value instanceof String) {
1392                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1393                    serializer.text(value != null ? (String) value : "");
1394                } else {
1395                    serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1396                    String[] values = (String[]) value;
1397                    serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1398                    for (String choice : values) {
1399                        serializer.startTag(null, TAG_VALUE);
1400                        serializer.text(choice != null ? choice : "");
1401                        serializer.endTag(null, TAG_VALUE);
1402                    }
1403                }
1404                serializer.endTag(null, TAG_ENTRY);
1405            }
1406
1407            serializer.endTag(null, TAG_RESTRICTIONS);
1408
1409            serializer.endDocument();
1410            restrictionsFile.finishWrite(fos);
1411        } catch (Exception e) {
1412            restrictionsFile.failWrite(fos);
1413            Slog.e(LOG_TAG, "Error writing application restrictions list");
1414        }
1415    }
1416
1417    @Override
1418    public int getUserSerialNumber(int userHandle) {
1419        synchronized (mPackagesLock) {
1420            if (!exists(userHandle)) return -1;
1421            return getUserInfoLocked(userHandle).serialNumber;
1422        }
1423    }
1424
1425    @Override
1426    public int getUserHandle(int userSerialNumber) {
1427        synchronized (mPackagesLock) {
1428            for (int userId : mUserIds) {
1429                if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
1430            }
1431            // Not found
1432            return -1;
1433        }
1434    }
1435
1436    /**
1437     * Caches the list of user ids in an array, adjusting the array size when necessary.
1438     */
1439    private void updateUserIdsLocked() {
1440        int num = 0;
1441        for (int i = 0; i < mUsers.size(); i++) {
1442            if (!mUsers.valueAt(i).partial) {
1443                num++;
1444            }
1445        }
1446        final int[] newUsers = new int[num];
1447        int n = 0;
1448        for (int i = 0; i < mUsers.size(); i++) {
1449            if (!mUsers.valueAt(i).partial) {
1450                newUsers[n++] = mUsers.keyAt(i);
1451            }
1452        }
1453        mUserIds = newUsers;
1454    }
1455
1456    /**
1457     * Make a note of the last started time of a user and do some cleanup.
1458     * @param userId the user that was just foregrounded
1459     */
1460    public void userForeground(int userId) {
1461        synchronized (mPackagesLock) {
1462            UserInfo user = mUsers.get(userId);
1463            long now = System.currentTimeMillis();
1464            if (user == null || user.partial) {
1465                Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1466                return;
1467            }
1468            if (now > EPOCH_PLUS_30_YEARS) {
1469                user.lastLoggedInTime = now;
1470                writeUserLocked(user);
1471            }
1472            // If this is not a restricted profile and there is no restrictions pin, clean up
1473            // all restrictions files that might have been left behind, else clean up just the
1474            // ones with uninstalled packages
1475            RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1476            final long salt = pinState == null ? 0 : pinState.salt;
1477            cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
1478        }
1479    }
1480
1481    /**
1482     * Returns the next available user id, filling in any holes in the ids.
1483     * TODO: May not be a good idea to recycle ids, in case it results in confusion
1484     * for data and battery stats collection, or unexpected cross-talk.
1485     * @return
1486     */
1487    private int getNextAvailableIdLocked() {
1488        synchronized (mPackagesLock) {
1489            int i = MIN_USER_ID;
1490            while (i < Integer.MAX_VALUE) {
1491                if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
1492                    break;
1493                }
1494                i++;
1495            }
1496            return i;
1497        }
1498    }
1499
1500    private String packageToRestrictionsFileName(String packageName) {
1501        return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1502    }
1503
1504    private String restrictionsFileNameToPackage(String fileName) {
1505        return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1506                (int) (fileName.length() - XML_SUFFIX.length()));
1507    }
1508
1509    @Override
1510    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1511        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1512                != PackageManager.PERMISSION_GRANTED) {
1513            pw.println("Permission Denial: can't dump UserManager from from pid="
1514                    + Binder.getCallingPid()
1515                    + ", uid=" + Binder.getCallingUid()
1516                    + " without permission "
1517                    + android.Manifest.permission.DUMP);
1518            return;
1519        }
1520
1521        long now = System.currentTimeMillis();
1522        StringBuilder sb = new StringBuilder();
1523        synchronized (mPackagesLock) {
1524            pw.println("Users:");
1525            for (int i = 0; i < mUsers.size(); i++) {
1526                UserInfo user = mUsers.valueAt(i);
1527                if (user == null) continue;
1528                pw.print("  "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
1529                if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
1530                if (user.partial) pw.print(" <partial>");
1531                pw.println();
1532                pw.print("    Created: ");
1533                if (user.creationTime == 0) {
1534                    pw.println("<unknown>");
1535                } else {
1536                    sb.setLength(0);
1537                    TimeUtils.formatDuration(now - user.creationTime, sb);
1538                    sb.append(" ago");
1539                    pw.println(sb);
1540                }
1541                pw.print("    Last logged in: ");
1542                if (user.lastLoggedInTime == 0) {
1543                    pw.println("<unknown>");
1544                } else {
1545                    sb.setLength(0);
1546                    TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1547                    sb.append(" ago");
1548                    pw.println(sb);
1549                }
1550            }
1551        }
1552    }
1553
1554    private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1555        @Override
1556        public void onPackageRemoved(String pkg, int uid) {
1557            final int userId = this.getChangingUserId();
1558            // Package could be disappearing because it is being blocked, so also check if
1559            // it has been uninstalled.
1560            final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1561            if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1562                cleanAppRestrictionsForPackage(pkg, userId);
1563            }
1564        }
1565    };
1566}
1567