blob: 16c2fe7f77ce5ec5d249c34e321460c75b1301a0 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
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
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080029import android.content.RestrictionEntry;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
35import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Amith Yamasani655d0e22013-06-12 14:19:10 -070044import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070047import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070048import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.util.Slog;
50import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.util.SparseBooleanArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070052import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070053import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.util.Xml;
55
Amith Yamasani1a7472e2013-07-02 11:17:30 -070056import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import com.android.internal.util.ArrayUtils;
58import com.android.internal.util.FastXmlSerializer;
59
60import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
62import org.xmlpull.v1.XmlSerializer;
63
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.BufferedOutputStream;
65import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070068import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069import java.io.FileOutputStream;
70import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070071import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070072import java.security.MessageDigest;
73import java.security.NoSuchAlgorithmException;
74import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.util.ArrayList;
76import java.util.List;
77
Amith Yamasani258848d2012-08-10 17:06:33 -070078public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani2a003292012-08-14 18:25:45 -070080 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070081
Amith Yamasani16389312012-10-17 21:20:14 -070082 private static final boolean DBG = false;
83
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070086 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070088 private static final String ATTR_CREATION_TIME = "created";
89 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070090 private static final String ATTR_SALT = "salt";
91 private static final String ATTR_PIN_HASH = "pinHash";
92 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
93 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070094 private static final String ATTR_SERIAL_NO = "serialNumber";
95 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070096 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070097 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
116
Amith Yamasani634cf312012-10-04 17:34:21 -0700117 private static final int MIN_USER_ID = 10;
118
Amith Yamasanibc9625052012-11-15 14:39:18 -0800119 private static final int USER_VERSION = 2;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120
Amith Yamasani920ace02012-09-20 22:15:37 -0700121 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
122
Amith Yamasani655d0e22013-06-12 14:19:10 -0700123 // Number of attempts before jumping to the next BACKOFF_TIMES slot
124 private static final int BACKOFF_INC_INTERVAL = 5;
125
126 // Amount of time to force the user to wait before entering the PIN again, after failing
127 // BACKOFF_INC_INTERVAL times.
128 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
129
Dianne Hackborn4428e172012-08-24 17:43:05 -0700130 private final Context mContext;
131 private final PackageManagerService mPm;
132 private final Object mInstallLock;
133 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800135 private final Handler mHandler;
136
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private final File mUsersDir;
138 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final File mBaseUserPath;
140
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800141 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800142 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143
Amith Yamasani655d0e22013-06-12 14:19:10 -0700144 class RestrictionsPinState {
145 long salt;
146 String pinHash;
147 int failedAttempts;
148 long lastAttemptTime;
149 }
150
151 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
152 new SparseArray<RestrictionsPinState>();
153
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800154 /**
155 * Set of user IDs being actively removed. Removed IDs linger in this set
156 * for several seconds to work around a VFS caching issue.
157 */
158 // @GuardedBy("mPackagesLock")
159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700162 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700163 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700165
Amith Yamasani258848d2012-08-10 17:06:33 -0700166 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700167
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168 public static UserManagerService getInstance() {
169 synchronized (UserManagerService.class) {
170 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173
174 /**
175 * Available for testing purposes.
176 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179 }
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 /**
182 * Called by package manager to create the service. This is closely
183 * associated with the package manager, and the given lock is the
184 * package manager's own lock.
185 */
186 UserManagerService(Context context, PackageManagerService pm,
187 Object installLock, Object packagesLock) {
188 this(context, pm, installLock, packagesLock,
189 Environment.getDataDirectory(),
190 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191 }
192
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 /**
194 * Available for testing purposes.
195 */
196 private UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock,
198 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700199 mContext = context;
200 mPm = pm;
201 mInstallLock = installLock;
202 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800203 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700204 synchronized (mInstallLock) {
205 synchronized (mPackagesLock) {
206 mUsersDir = new File(dataDir, USER_INFO_DIR);
207 mUsersDir.mkdirs();
208 // Make zeroth user directory, for services to migrate their files to that location
209 File userZeroDir = new File(mUsersDir, "0");
210 userZeroDir.mkdirs();
211 mBaseUserPath = baseUserPath;
212 FileUtils.setPermissions(mUsersDir.toString(),
213 FileUtils.S_IRWXU|FileUtils.S_IRWXG
214 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
215 -1, -1);
216 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
217 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700218 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
220 for (int i = 0; i < mUsers.size(); i++) {
221 UserInfo ui = mUsers.valueAt(i);
222 if (ui.partial && i != 0) {
223 partials.add(ui);
224 }
225 }
226 for (int i = 0; i < partials.size(); i++) {
227 UserInfo ui = partials.get(i);
228 Slog.w(LOG_TAG, "Removing partially created user #" + i
229 + " (name=" + ui.name + ")");
230 removeUserStateLocked(ui.id);
231 }
232 sInstance = this;
233 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700235
236 }
237
238 void systemReady() {
239 mUserPackageMonitor.register(ActivityThread.systemMain().getSystemContext(),
240 null, UserHandle.ALL, false);
241 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700242 }
243
244 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700245 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700246 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700248 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
249 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 UserInfo ui = mUsers.valueAt(i);
251 if (ui.partial) {
252 continue;
253 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800254 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700256 }
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700259 }
Amith Yamasani13593602012-03-22 16:16:17 -0700260 }
261
Amith Yamasani258848d2012-08-10 17:06:33 -0700262 @Override
263 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700264 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700265 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700266 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
268 }
269
Amith Yamasani71e6c692013-03-24 17:39:28 -0700270 @Override
271 public boolean isRestricted() {
272 synchronized (mPackagesLock) {
273 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
274 }
275 }
276
Amith Yamasani195263742012-08-21 15:40:12 -0700277 /*
278 * Should be locked on mUsers before calling this.
279 */
280 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700282 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800283 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700284 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
285 return null;
286 }
287 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700288 }
289
Amith Yamasani13593602012-03-22 16:16:17 -0700290 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700291 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700292 return ArrayUtils.contains(mUserIds, userId);
293 }
294 }
295
Amith Yamasani258848d2012-08-10 17:06:33 -0700296 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700297 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700298 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700299 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700300 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700301 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700302 if (info == null || info.partial) {
303 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
304 return;
305 }
Amith Yamasani13593602012-03-22 16:16:17 -0700306 if (name != null && !name.equals(info.name)) {
307 info.name = name;
308 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700309 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700310 }
311 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700312 if (changed) {
313 sendUserInfoChangedBroadcast(userId);
314 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700315 }
316
Amith Yamasani258848d2012-08-10 17:06:33 -0700317 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700318 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700319 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700320 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700321 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700322 if (info == null || info.partial) {
323 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
324 return;
325 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700326 writeBitmapLocked(info, bitmap);
327 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700328 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700329 sendUserInfoChangedBroadcast(userId);
330 }
331
332 private void sendUserInfoChangedBroadcast(int userId) {
333 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
334 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
335 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700336 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700337 }
338
Amith Yamasani258848d2012-08-10 17:06:33 -0700339 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700340 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700341 checkManageUsersPermission("read users");
342 synchronized (mPackagesLock) {
343 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700344 if (info == null || info.partial) {
345 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
346 return null;
347 }
348 if (info.iconPath == null) {
349 return null;
350 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700351 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700352 }
353 }
354
355 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700356 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700357 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700358 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700359 if (mGuestEnabled != enable) {
360 mGuestEnabled = enable;
361 // Erase any guest user that currently exists
362 for (int i = 0; i < mUsers.size(); i++) {
363 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700365 if (!enable) {
366 removeUser(user.id);
367 }
368 return;
369 }
370 }
371 // No guest was found
372 if (enable) {
373 createUser("Guest", UserInfo.FLAG_GUEST);
374 }
375 }
376 }
377 }
378
379 @Override
380 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700382 return mGuestEnabled;
383 }
384 }
385
386 @Override
387 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700388 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 // TODO:
390 }
391
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700392 public void makeInitialized(int userId) {
393 checkManageUsersPermission("makeInitialized");
394 synchronized (mPackagesLock) {
395 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700396 if (info == null || info.partial) {
397 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
398 }
399 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700400 info.flags |= UserInfo.FLAG_INITIALIZED;
401 writeUserLocked(info);
402 }
403 }
404 }
405
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800406 @Override
407 public Bundle getUserRestrictions(int userId) {
408 // checkManageUsersPermission("getUserRestrictions");
409
410 synchronized (mPackagesLock) {
411 Bundle restrictions = mUserRestrictions.get(userId);
412 return restrictions != null ? restrictions : Bundle.EMPTY;
413 }
414 }
415
416 @Override
417 public void setUserRestrictions(Bundle restrictions, int userId) {
418 checkManageUsersPermission("setUserRestrictions");
419
420 synchronized (mPackagesLock) {
421 mUserRestrictions.get(userId).putAll(restrictions);
422 writeUserLocked(mUsers.get(userId));
423 }
424 }
425
Amith Yamasani258848d2012-08-10 17:06:33 -0700426 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700427 * Check if we've hit the limit of how many users can be created.
428 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700429 private boolean isUserLimitReachedLocked() {
430 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700431 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700432 }
433
434 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700435 * 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.
Amith Yamasani258848d2012-08-10 17:06:33 -0700438 *
439 * @param message used as message if SecurityException is thrown
440 * @throws SecurityException if the caller is not system or root
441 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700442 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700444 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);
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 }
450 }
451
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700452 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700453 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 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700463 FileOutputStream os;
464 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700465 info.iconPath = file.getAbsolutePath();
466 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700467 try {
468 os.close();
469 } catch (IOException ioe) {
470 // What the ... !
471 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700472 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700473 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700474 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700475 }
476
Amith Yamasani0b285492011-04-14 17:35:23 -0700477 /**
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 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700482 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700483 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700484 return mUserIds;
485 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700486 }
487
Dianne Hackborn4428e172012-08-24 17:43:05 -0700488 int[] getUserIdsLPr() {
489 return mUserIds;
490 }
491
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700492 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700493 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700494 readUserListLocked();
495 }
496 }
497
498 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700499 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700501 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700502 return;
503 }
504 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700505 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700506 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700507 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700508 XmlPullParser parser = Xml.newPullParser();
509 parser.setInput(fis, null);
510 int type;
511 while ((type = parser.next()) != XmlPullParser.START_TAG
512 && type != XmlPullParser.END_DOCUMENT) {
513 ;
514 }
515
516 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700517 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700518 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700519 return;
520 }
521
Amith Yamasani2a003292012-08-14 18:25:45 -0700522 mNextSerialNumber = -1;
523 if (parser.getName().equals(TAG_USERS)) {
524 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
525 if (lastSerialNumber != null) {
526 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
527 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700528 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
529 if (versionNumber != null) {
530 mUserVersion = Integer.parseInt(versionNumber);
531 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700532 }
533
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700534 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
535 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
536 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800537 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700538
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700539 if (user != null) {
540 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700541 if (user.isGuest()) {
542 mGuestEnabled = true;
543 }
544 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
545 mNextSerialNumber = user.id + 1;
546 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700547 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700548 }
549 }
Amith Yamasani13593602012-03-22 16:16:17 -0700550 updateUserIdsLocked();
Amith Yamasani6f34b412012-10-22 18:19:27 -0700551 upgradeIfNecessary();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700552 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700553 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700554 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700555 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800556 } finally {
557 if (fis != null) {
558 try {
559 fis.close();
560 } catch (IOException e) {
561 }
562 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700563 }
564 }
565
Amith Yamasani6f34b412012-10-22 18:19:27 -0700566 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800567 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700568 */
569 private void upgradeIfNecessary() {
570 int userVersion = mUserVersion;
571 if (userVersion < 1) {
572 // Assign a proper name for the owner, if not initialized correctly before
573 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
574 if ("Primary".equals(user.name)) {
575 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
576 writeUserLocked(user);
577 }
578 userVersion = 1;
579 }
580
Amith Yamasanibc9625052012-11-15 14:39:18 -0800581 if (userVersion < 2) {
582 // Owner should be marked as initialized
583 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
584 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
585 user.flags |= UserInfo.FLAG_INITIALIZED;
586 writeUserLocked(user);
587 }
588 userVersion = 2;
589 }
590
Amith Yamasani6f34b412012-10-22 18:19:27 -0700591 if (userVersion < USER_VERSION) {
592 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
593 + USER_VERSION);
594 } else {
595 mUserVersion = userVersion;
596 writeUserListLocked();
597 }
598 }
599
Amith Yamasani13593602012-03-22 16:16:17 -0700600 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700601 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800602 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700603 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700604 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700606 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800607
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500608 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800609 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
610
Amith Yamasani13593602012-03-22 16:16:17 -0700611 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700612
Amith Yamasani13593602012-03-22 16:16:17 -0700613 writeUserListLocked();
614 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700615 }
616
617 /*
618 * Writes the user file in this format:
619 *
620 * <user flags="20039023" id="0">
621 * <name>Primary</name>
622 * </user>
623 */
Amith Yamasani13593602012-03-22 16:16:17 -0700624 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700625 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700626 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700627 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700628 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700629 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));
Amith Yamasani2a003292012-08-14 18:25:45 -0700639 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700641 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
642 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
643 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700644 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 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700659 if (userInfo.iconPath != null) {
660 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
661 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700662 if (userInfo.partial) {
663 serializer.attribute(null, ATTR_PARTIAL, "true");
664 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665
666 serializer.startTag(null, TAG_NAME);
667 serializer.text(userInfo.name);
668 serializer.endTag(null, TAG_NAME);
669
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800670 Bundle restrictions = mUserRestrictions.get(userInfo.id);
671 if (restrictions != null) {
672 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700673 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);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400678 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);
Emily Bernierb223f732013-04-11 15:46:36 -0400682 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
683 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800684 serializer.endTag(null, TAG_RESTRICTIONS);
685 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700686 serializer.endTag(null, TAG_USER);
687
688 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700689 userFile.finishWrite(fos);
690 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700691 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700692 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 }
694 }
695
696 /*
697 * Writes the user list file in this format:
698 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700699 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700700 * <user id="0"></user>
701 * <user id="2"></user>
702 * </users>
703 */
Amith Yamasani13593602012-03-22 16:16:17 -0700704 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700705 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700706 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700707 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700708 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700709 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);
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700719 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720
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);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 }
727
728 serializer.endTag(null, TAG_USERS);
729
730 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700731 userListFile.finishWrite(fos);
732 } catch (Exception e) {
733 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700734 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700735 }
736 }
737
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800738 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700739 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700742 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700743 long creationTime = 0L;
744 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700745 long salt = 0L;
746 String pinHash = null;
747 int failedAttempts = 0;
748 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700749 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800750 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700751
752 FileInputStream fis = null;
753 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700754 AtomicFile userFile =
755 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
756 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 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) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700766 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 return null;
768 }
769
770 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700771 int storedId = readIntAttribute(parser, ATTR_ID, -1);
772 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700773 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 return null;
775 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700776 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
777 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700778 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700779 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
780 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700781 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);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700785 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
786 if ("true".equals(valueString)) {
787 partial = true;
788 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700789
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800790 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)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700803 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);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400808 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);
Emily Bernierb223f732013-04-11 15:46:36 -0400812 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
813 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700814 }
815 }
816 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700818 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700819 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700820 userInfo.creationTime = creationTime;
821 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700822 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800823 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700824 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 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700835 return userInfo;
836
837 } catch (IOException ioe) {
838 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800839 } finally {
840 if (fis != null) {
841 try {
842 fis.close();
843 } catch (IOException e) {
844 }
845 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700846 }
847 return null;
848 }
849
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800850 private void readBoolean(XmlPullParser parser, Bundle restrictions,
851 String restrictionKey) {
852 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700853 if (value != null) {
854 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
855 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800856 }
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
Amith Yamasani920ace02012-09-20 22:15:37 -0700866 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
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700886 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
Amith Yamasanib82add22013-07-09 11:24:44 -0700896 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700897 * 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.
Amith Yamasanib82add22013-07-09 11:24:44 -0700899 * Does not do any permissions checking.
900 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700901 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700902 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()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700910 if (all) {
911 resFile.delete();
912 } else {
913 String pkg = fileName.substring(RESTRICTIONS_FILE_PREFIX.length());
914 if (!isPackageInstalled(pkg, userId)) {
915 resFile.delete();
916 }
917 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700918 }
919 }
920 }
921 }
922 }
923
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700924 /**
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, RESTRICTIONS_FILE_PREFIX + pkg);
931 if (resFile.exists()) {
932 resFile.delete();
933 }
934 }
935 }
936
Amith Yamasani258848d2012-08-10 17:06:33 -0700937 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700938 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700939 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700940
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700941 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++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700951 long now = System.currentTimeMillis();
952 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700953 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700954 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700955 mUsers.put(userId, userInfo);
956 writeUserListLocked();
957 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700958 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700959 userInfo.partial = false;
960 writeUserLocked(userInfo);
961 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500962 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500963 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700964 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700965 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700966 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);
Amith Yamasani258848d2012-08-10 17:06:33 -0700974 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700975 return userInfo;
976 }
977
Amith Yamasani0b285492011-04-14 17:35:23 -0700978 /**
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 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700983 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700985 final UserInfo user;
986 synchronized (mPackagesLock) {
987 user = mUsers.get(userHandle);
988 if (userHandle == 0 || user == null) {
989 return false;
990 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800991 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700992 // 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);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700997 }
Amith Yamasani16389312012-10-17 21:20:14 -0700998 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700999 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
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001018 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001019 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001020 // 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
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001022 long ident = Binder.clearCallingIdentity();
1023 try {
1024 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1025 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001026 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);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001050 } finally {
1051 Binder.restoreCallingIdentity(ident);
1052 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001053 }
1054
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001055 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001056 // Cleanup package manager settings
1057 mPm.cleanUpUserLILPw(userHandle);
1058
1059 // Remove this user from the list
1060 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001061
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
Amith Yamasani655d0e22013-06-12 14:19:10 -07001074 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001075 // Remove user file
1076 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
1077 userFile.delete();
1078 // Update the user list
1079 writeUserListLocked();
1080 updateUserIdsLocked();
1081 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1082 }
1083
Amith Yamasani61f57372012-08-31 12:12:28 -07001084 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
Amith Yamasani2a003292012-08-14 18:25:45 -07001095 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001096 public Bundle getApplicationRestrictions(String packageName) {
1097 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1098 }
1099
1100 @Override
1101 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001102 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001103 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001104 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
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001113 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001114 int userId) {
1115 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001116 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001117 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1118 }
1119 synchronized (mPackagesLock) {
1120 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001121 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001122 }
1123 }
1124
Amith Yamasani655d0e22013-06-12 14:19:10 -07001125 @Override
1126 public boolean changeRestrictionsPin(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 checkRestrictionsPin(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 hasRestrictionsPin() {
1197 int userId = UserHandle.getCallingUserId();
1198 synchronized (mPackagesLock) {
1199 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1200 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1201 return false;
1202 }
1203 }
1204 return true;
1205 }
1206
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001207 @Override
1208 public void removeRestrictions() {
1209 checkManageUsersPermission("Only system can remove restrictions");
1210 final int userHandle = UserHandle.getCallingUserId();
1211 synchronized (mPackagesLock) {
1212 // Remove all user restrictions
1213 setUserRestrictions(new Bundle(), userHandle);
1214 // Remove restrictions pin
1215 changeRestrictionsPin(null);
1216 // Remove any app restrictions
1217 cleanAppRestrictions(userHandle, true);
1218 }
1219 mHandler.post(new Runnable() {
1220 @Override
1221 public void run() {
1222 List<ApplicationInfo> apps =
1223 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1224 userHandle).getList();
1225 final long ident = Binder.clearCallingIdentity();
1226 try {
1227 for (ApplicationInfo appInfo : apps) {
1228 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1229 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1230 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1231 userHandle);
1232 }
1233 }
1234 } finally {
1235 Binder.restoreCallingIdentity(ident);
1236 }
1237 }
1238 });
1239 }
1240
Amith Yamasani655d0e22013-06-12 14:19:10 -07001241 /*
1242 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1243 * Not the most secure, but it is at least a second level of protection. First level is that
1244 * the file is in a location only readable by the system process.
1245 * @param password the password.
1246 * @param salt the randomly generated salt
1247 * @return the hash of the pattern in a String.
1248 */
1249 private String passwordToHash(String password, long salt) {
1250 if (password == null) {
1251 return null;
1252 }
1253 String algo = null;
1254 String hashed = salt + password;
1255 try {
1256 byte[] saltedPassword = (password + salt).getBytes();
1257 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1258 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1259 hashed = toHex(sha1) + toHex(md5);
1260 } catch (NoSuchAlgorithmException e) {
1261 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1262 }
1263 return hashed;
1264 }
1265
1266 private static String toHex(byte[] ary) {
1267 final String hex = "0123456789ABCDEF";
1268 String ret = "";
1269 for (int i = 0; i < ary.length; i++) {
1270 ret += hex.charAt((ary[i] >> 4) & 0xf);
1271 ret += hex.charAt(ary[i] & 0xf);
1272 }
1273 return ret;
1274 }
1275
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001276 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001277 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001278 try {
1279 return mContext.getPackageManager().getApplicationInfo(packageName,
1280 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1281 } catch (NameNotFoundException nnfe) {
1282 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001283 } finally {
1284 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001285 }
1286 }
1287
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001288 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001289 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001290 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001291 final ArrayList<String> values = new ArrayList<String>();
1292
1293 FileInputStream fis = null;
1294 try {
1295 AtomicFile restrictionsFile =
1296 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1297 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1298 fis = restrictionsFile.openRead();
1299 XmlPullParser parser = Xml.newPullParser();
1300 parser.setInput(fis, null);
1301 int type;
1302 while ((type = parser.next()) != XmlPullParser.START_TAG
1303 && type != XmlPullParser.END_DOCUMENT) {
1304 ;
1305 }
1306
1307 if (type != XmlPullParser.START_TAG) {
1308 Slog.e(LOG_TAG, "Unable to read restrictions file "
1309 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001310 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001311 }
1312
1313 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1314 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1315 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001316 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001317 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1318 if (multiple != null) {
1319 int count = Integer.parseInt(multiple);
1320 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1321 if (type == XmlPullParser.START_TAG
1322 && parser.getName().equals(TAG_VALUE)) {
1323 values.add(parser.nextText().trim());
1324 count--;
1325 }
1326 }
1327 String [] valueStrings = new String[values.size()];
1328 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001329 restrictions.putStringArray(key, valueStrings);
1330 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1331 restrictions.putBoolean(key, Boolean.parseBoolean(
1332 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001333 } else {
1334 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001335 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001336 }
1337 }
1338 }
1339
1340 } catch (IOException ioe) {
1341 } catch (XmlPullParserException pe) {
1342 } finally {
1343 if (fis != null) {
1344 try {
1345 fis.close();
1346 } catch (IOException e) {
1347 }
1348 }
1349 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001350 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001351 }
1352
1353 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001354 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001355 FileOutputStream fos = null;
1356 AtomicFile restrictionsFile = new AtomicFile(
1357 new File(Environment.getUserSystemDirectory(userId),
1358 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1359 try {
1360 fos = restrictionsFile.startWrite();
1361 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1362
1363 // XmlSerializer serializer = XmlUtils.serializerInstance();
1364 final XmlSerializer serializer = new FastXmlSerializer();
1365 serializer.setOutput(bos, "utf-8");
1366 serializer.startDocument(null, true);
1367 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1368
1369 serializer.startTag(null, TAG_RESTRICTIONS);
1370
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001371 for (String key : restrictions.keySet()) {
1372 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001373 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001374 serializer.attribute(null, ATTR_KEY, key);
1375
1376 if (value instanceof Boolean) {
1377 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1378 serializer.text(value.toString());
1379 } else if (value == null || value instanceof String) {
1380 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1381 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001382 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001383 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1384 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001385 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001386 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001387 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001388 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001389 serializer.endTag(null, TAG_VALUE);
1390 }
1391 }
1392 serializer.endTag(null, TAG_ENTRY);
1393 }
1394
1395 serializer.endTag(null, TAG_RESTRICTIONS);
1396
1397 serializer.endDocument();
1398 restrictionsFile.finishWrite(fos);
1399 } catch (Exception e) {
1400 restrictionsFile.failWrite(fos);
1401 Slog.e(LOG_TAG, "Error writing application restrictions list");
1402 }
1403 }
1404
1405 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001406 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001407 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001408 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001409 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001410 }
1411 }
1412
1413 @Override
1414 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001415 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001416 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001417 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001418 }
1419 // Not found
1420 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001421 }
1422 }
1423
Amith Yamasani0b285492011-04-14 17:35:23 -07001424 /**
1425 * Caches the list of user ids in an array, adjusting the array size when necessary.
1426 */
Amith Yamasani13593602012-03-22 16:16:17 -07001427 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001428 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001429 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001430 if (!mUsers.valueAt(i).partial) {
1431 num++;
1432 }
1433 }
Amith Yamasani16389312012-10-17 21:20:14 -07001434 final int[] newUsers = new int[num];
1435 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001436 for (int i = 0; i < mUsers.size(); i++) {
1437 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001438 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001439 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001440 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001441 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001442 }
1443
1444 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001445 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001446 * @param userId the user that was just foregrounded
1447 */
1448 public void userForeground(int userId) {
1449 synchronized (mPackagesLock) {
1450 UserInfo user = mUsers.get(userId);
1451 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001452 if (user == null || user.partial) {
1453 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1454 return;
1455 }
1456 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001457 user.lastLoggedInTime = now;
1458 writeUserLocked(user);
1459 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001460 // If this is not a restricted profile and there is no restrictions pin, clean up
1461 // all restrictions files that might have been left behind, else clean up just the
1462 // ones with uninstalled packages
1463 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1464 final long salt = pinState == null ? 0 : pinState.salt;
1465 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001466 }
1467 }
1468
1469 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001470 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001471 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1472 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001473 * @return
1474 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001475 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001476 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001477 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001478 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001479 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001480 break;
1481 }
1482 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001483 }
Amith Yamasani195263742012-08-21 15:40:12 -07001484 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001485 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001486 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001487
1488 @Override
1489 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1490 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1491 != PackageManager.PERMISSION_GRANTED) {
1492 pw.println("Permission Denial: can't dump UserManager from from pid="
1493 + Binder.getCallingPid()
1494 + ", uid=" + Binder.getCallingUid()
1495 + " without permission "
1496 + android.Manifest.permission.DUMP);
1497 return;
1498 }
1499
1500 long now = System.currentTimeMillis();
1501 StringBuilder sb = new StringBuilder();
1502 synchronized (mPackagesLock) {
1503 pw.println("Users:");
1504 for (int i = 0; i < mUsers.size(); i++) {
1505 UserInfo user = mUsers.valueAt(i);
1506 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001507 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001508 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001509 if (user.partial) pw.print(" <partial>");
1510 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001511 pw.print(" Created: ");
1512 if (user.creationTime == 0) {
1513 pw.println("<unknown>");
1514 } else {
1515 sb.setLength(0);
1516 TimeUtils.formatDuration(now - user.creationTime, sb);
1517 sb.append(" ago");
1518 pw.println(sb);
1519 }
1520 pw.print(" Last logged in: ");
1521 if (user.lastLoggedInTime == 0) {
1522 pw.println("<unknown>");
1523 } else {
1524 sb.setLength(0);
1525 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1526 sb.append(" ago");
1527 pw.println(sb);
1528 }
1529 }
1530 }
1531 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001532
1533 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1534 @Override
1535 public void onPackageRemoved(String pkg, int uid) {
1536 final int userId = this.getChangingUserId();
1537 // Package could be disappearing because it is being blocked, so also check if
1538 // it has been uninstalled.
1539 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1540 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1541 cleanAppRestrictionsForPackage(pkg, userId);
1542 }
1543 }
1544 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001545}