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