blob: d86f2c75c08e4a45b60cbece5b819d12f153350a [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;
24import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.RestrictionEntry;
Amith Yamasani0b285492011-04-14 17:35:23 -070029import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080030import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080035import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070036import android.os.Environment;
37import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080038import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070041import android.os.RemoteException;
Amith Yamasani655d0e22013-06-12 14:19:10 -070042import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070050import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import android.util.Xml;
53
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import 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
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.BufferedOutputStream;
62import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070065import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileOutputStream;
67import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.util.ArrayList;
73import java.util.List;
74
Amith Yamasani258848d2012-08-10 17:06:33 -070075public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076
Amith Yamasani2a003292012-08-14 18:25:45 -070077 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani16389312012-10-17 21:20:14 -070079 private static final boolean DBG = false;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070085 private static final String ATTR_CREATION_TIME = "created";
86 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070087 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";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080097 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080098 private static final String TAG_ENTRY = "entry";
99 private static final String TAG_VALUE = "value";
100 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700101 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 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
Amith Yamasani0b285492011-04-14 17:35:23 -0700108 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
113
Amith Yamasani634cf312012-10-04 17:34:21 -0700114 private static final int MIN_USER_ID = 10;
115
Amith Yamasanibc9625052012-11-15 14:39:18 -0800116 private static final int USER_VERSION = 2;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700117
Amith Yamasani920ace02012-09-20 22:15:37 -0700118 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
119
Amith Yamasani655d0e22013-06-12 14:19:10 -0700120 // Number of attempts before jumping to the next BACKOFF_TIMES slot
121 private static final int BACKOFF_INC_INTERVAL = 5;
122
123 // Amount of time to force the user to wait before entering the PIN again, after failing
124 // BACKOFF_INC_INTERVAL times.
125 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
126
Dianne Hackborn4428e172012-08-24 17:43:05 -0700127 private final Context mContext;
128 private final PackageManagerService mPm;
129 private final Object mInstallLock;
130 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800132 private final Handler mHandler;
133
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private final File mUsersDir;
135 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700136 private final File mBaseUserPath;
137
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800138 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800139 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800140
Amith Yamasani655d0e22013-06-12 14:19:10 -0700141 class RestrictionsPinState {
142 long salt;
143 String pinHash;
144 int failedAttempts;
145 long lastAttemptTime;
146 }
147
148 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
149 new SparseArray<RestrictionsPinState>();
150
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151 /**
152 * Set of user IDs being actively removed. Removed IDs linger in this set
153 * for several seconds to work around a VFS caching issue.
154 */
155 // @GuardedBy("mPackagesLock")
156 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700157
Amith Yamasani0b285492011-04-14 17:35:23 -0700158 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700159 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700160 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700161 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700162
Amith Yamasani258848d2012-08-10 17:06:33 -0700163 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 public static UserManagerService getInstance() {
166 synchronized (UserManagerService.class) {
167 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700168 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700169 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170
171 /**
172 * Available for testing purposes.
173 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176 }
177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 /**
179 * Called by package manager to create the service. This is closely
180 * associated with the package manager, and the given lock is the
181 * package manager's own lock.
182 */
183 UserManagerService(Context context, PackageManagerService pm,
184 Object installLock, Object packagesLock) {
185 this(context, pm, installLock, packagesLock,
186 Environment.getDataDirectory(),
187 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 }
189
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190 /**
191 * Available for testing purposes.
192 */
193 private UserManagerService(Context context, PackageManagerService pm,
194 Object installLock, Object packagesLock,
195 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700196 mContext = context;
197 mPm = pm;
198 mInstallLock = installLock;
199 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800200 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700201 synchronized (mInstallLock) {
202 synchronized (mPackagesLock) {
203 mUsersDir = new File(dataDir, USER_INFO_DIR);
204 mUsersDir.mkdirs();
205 // Make zeroth user directory, for services to migrate their files to that location
206 File userZeroDir = new File(mUsersDir, "0");
207 userZeroDir.mkdirs();
208 mBaseUserPath = baseUserPath;
209 FileUtils.setPermissions(mUsersDir.toString(),
210 FileUtils.S_IRWXU|FileUtils.S_IRWXG
211 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
212 -1, -1);
213 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
214 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700215 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700216 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
217 for (int i = 0; i < mUsers.size(); i++) {
218 UserInfo ui = mUsers.valueAt(i);
219 if (ui.partial && i != 0) {
220 partials.add(ui);
221 }
222 }
223 for (int i = 0; i < partials.size(); i++) {
224 UserInfo ui = partials.get(i);
225 Slog.w(LOG_TAG, "Removing partially created user #" + i
226 + " (name=" + ui.name + ")");
227 removeUserStateLocked(ui.id);
228 }
229 sInstance = this;
230 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700232 }
233
234 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700235 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700236 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700237 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700238 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
239 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700240 UserInfo ui = mUsers.valueAt(i);
241 if (ui.partial) {
242 continue;
243 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800244 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700246 }
Amith Yamasani13593602012-03-22 16:16:17 -0700247 }
248 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700249 }
Amith Yamasani13593602012-03-22 16:16:17 -0700250 }
251
Amith Yamasani258848d2012-08-10 17:06:33 -0700252 @Override
253 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700254 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700255 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700256 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258 }
259
Amith Yamasani71e6c692013-03-24 17:39:28 -0700260 @Override
261 public boolean isRestricted() {
262 synchronized (mPackagesLock) {
263 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
264 }
265 }
266
Amith Yamasani195263742012-08-21 15:40:12 -0700267 /*
268 * Should be locked on mUsers before calling this.
269 */
270 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700271 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700272 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800273 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700274 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
275 return null;
276 }
277 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700278 }
279
Amith Yamasani13593602012-03-22 16:16:17 -0700280 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700281 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700282 return ArrayUtils.contains(mUserIds, userId);
283 }
284 }
285
Amith Yamasani258848d2012-08-10 17:06:33 -0700286 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700287 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700288 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700289 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700290 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700291 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700292 if (info == null || info.partial) {
293 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
294 return;
295 }
Amith Yamasani13593602012-03-22 16:16:17 -0700296 if (name != null && !name.equals(info.name)) {
297 info.name = name;
298 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700299 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700300 }
301 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700302 if (changed) {
303 sendUserInfoChangedBroadcast(userId);
304 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700305 }
306
Amith Yamasani258848d2012-08-10 17:06:33 -0700307 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700308 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700309 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700310 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700311 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700312 if (info == null || info.partial) {
313 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
314 return;
315 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700316 writeBitmapLocked(info, bitmap);
317 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700318 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700319 sendUserInfoChangedBroadcast(userId);
320 }
321
322 private void sendUserInfoChangedBroadcast(int userId) {
323 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
324 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
325 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700326 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700327 }
328
Amith Yamasani258848d2012-08-10 17:06:33 -0700329 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700330 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700331 checkManageUsersPermission("read users");
332 synchronized (mPackagesLock) {
333 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700334 if (info == null || info.partial) {
335 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
336 return null;
337 }
338 if (info.iconPath == null) {
339 return null;
340 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700341 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700342 }
343 }
344
345 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700347 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700348 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700349 if (mGuestEnabled != enable) {
350 mGuestEnabled = enable;
351 // Erase any guest user that currently exists
352 for (int i = 0; i < mUsers.size(); i++) {
353 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700354 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700355 if (!enable) {
356 removeUser(user.id);
357 }
358 return;
359 }
360 }
361 // No guest was found
362 if (enable) {
363 createUser("Guest", UserInfo.FLAG_GUEST);
364 }
365 }
366 }
367 }
368
369 @Override
370 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700371 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700372 return mGuestEnabled;
373 }
374 }
375
376 @Override
377 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700378 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 // TODO:
380 }
381
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700382 public void makeInitialized(int userId) {
383 checkManageUsersPermission("makeInitialized");
384 synchronized (mPackagesLock) {
385 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700386 if (info == null || info.partial) {
387 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
388 }
389 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700390 info.flags |= UserInfo.FLAG_INITIALIZED;
391 writeUserLocked(info);
392 }
393 }
394 }
395
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800396 @Override
397 public Bundle getUserRestrictions(int userId) {
398 // checkManageUsersPermission("getUserRestrictions");
399
400 synchronized (mPackagesLock) {
401 Bundle restrictions = mUserRestrictions.get(userId);
402 return restrictions != null ? restrictions : Bundle.EMPTY;
403 }
404 }
405
406 @Override
407 public void setUserRestrictions(Bundle restrictions, int userId) {
408 checkManageUsersPermission("setUserRestrictions");
409
410 synchronized (mPackagesLock) {
411 mUserRestrictions.get(userId).putAll(restrictions);
412 writeUserLocked(mUsers.get(userId));
413 }
414 }
415
Amith Yamasani258848d2012-08-10 17:06:33 -0700416 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700417 * Check if we've hit the limit of how many users can be created.
418 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700419 private boolean isUserLimitReachedLocked() {
420 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700421 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700422 }
423
424 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700425 * Enforces that only the system UID or root's UID or apps that have the
426 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
427 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700428 *
429 * @param message used as message if SecurityException is thrown
430 * @throws SecurityException if the caller is not system or root
431 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700432 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700433 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700434 if (uid != Process.SYSTEM_UID && uid != 0
435 && ActivityManager.checkComponentPermission(
436 android.Manifest.permission.MANAGE_USERS,
437 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
438 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700439 }
440 }
441
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700442 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700443 try {
444 File dir = new File(mUsersDir, Integer.toString(info.id));
445 File file = new File(dir, USER_PHOTO_FILENAME);
446 if (!dir.exists()) {
447 dir.mkdir();
448 FileUtils.setPermissions(
449 dir.getPath(),
450 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
451 -1, -1);
452 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700453 FileOutputStream os;
454 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700455 info.iconPath = file.getAbsolutePath();
456 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700457 try {
458 os.close();
459 } catch (IOException ioe) {
460 // What the ... !
461 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700462 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700463 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700464 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700465 }
466
Amith Yamasani0b285492011-04-14 17:35:23 -0700467 /**
468 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
469 * cache it elsewhere.
470 * @return the array of user ids.
471 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700472 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700473 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700474 return mUserIds;
475 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700476 }
477
Dianne Hackborn4428e172012-08-24 17:43:05 -0700478 int[] getUserIdsLPr() {
479 return mUserIds;
480 }
481
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700482 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700483 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700484 readUserListLocked();
485 }
486 }
487
488 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700489 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700490 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700491 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700492 return;
493 }
494 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700495 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700496 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700497 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700498 XmlPullParser parser = Xml.newPullParser();
499 parser.setInput(fis, null);
500 int type;
501 while ((type = parser.next()) != XmlPullParser.START_TAG
502 && type != XmlPullParser.END_DOCUMENT) {
503 ;
504 }
505
506 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700507 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700508 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700509 return;
510 }
511
Amith Yamasani2a003292012-08-14 18:25:45 -0700512 mNextSerialNumber = -1;
513 if (parser.getName().equals(TAG_USERS)) {
514 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
515 if (lastSerialNumber != null) {
516 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
517 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700518 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
519 if (versionNumber != null) {
520 mUserVersion = Integer.parseInt(versionNumber);
521 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700522 }
523
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700524 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
525 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
526 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800527 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700528
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700529 if (user != null) {
530 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700531 if (user.isGuest()) {
532 mGuestEnabled = true;
533 }
534 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
535 mNextSerialNumber = user.id + 1;
536 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700537 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700538 }
539 }
Amith Yamasani13593602012-03-22 16:16:17 -0700540 updateUserIdsLocked();
Amith Yamasani6f34b412012-10-22 18:19:27 -0700541 upgradeIfNecessary();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700542 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700543 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700544 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700545 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800546 } finally {
547 if (fis != null) {
548 try {
549 fis.close();
550 } catch (IOException e) {
551 }
552 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700553 }
554 }
555
Amith Yamasani6f34b412012-10-22 18:19:27 -0700556 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800557 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700558 */
559 private void upgradeIfNecessary() {
560 int userVersion = mUserVersion;
561 if (userVersion < 1) {
562 // Assign a proper name for the owner, if not initialized correctly before
563 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
564 if ("Primary".equals(user.name)) {
565 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
566 writeUserLocked(user);
567 }
568 userVersion = 1;
569 }
570
Amith Yamasanibc9625052012-11-15 14:39:18 -0800571 if (userVersion < 2) {
572 // Owner should be marked as initialized
573 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
574 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
575 user.flags |= UserInfo.FLAG_INITIALIZED;
576 writeUserLocked(user);
577 }
578 userVersion = 2;
579 }
580
Amith Yamasani6f34b412012-10-22 18:19:27 -0700581 if (userVersion < USER_VERSION) {
582 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
583 + USER_VERSION);
584 } else {
585 mUserVersion = userVersion;
586 writeUserListLocked();
587 }
588 }
589
Amith Yamasani13593602012-03-22 16:16:17 -0700590 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700591 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800592 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700593 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700594 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700595 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700596 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800597
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500598 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800599 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
600
Amith Yamasani13593602012-03-22 16:16:17 -0700601 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700602
Amith Yamasani13593602012-03-22 16:16:17 -0700603 writeUserListLocked();
604 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 }
606
607 /*
608 * Writes the user file in this format:
609 *
610 * <user flags="20039023" id="0">
611 * <name>Primary</name>
612 * </user>
613 */
Amith Yamasani13593602012-03-22 16:16:17 -0700614 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700615 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700616 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700617 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700618 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700619 final BufferedOutputStream bos = new BufferedOutputStream(fos);
620
621 // XmlSerializer serializer = XmlUtils.serializerInstance();
622 final XmlSerializer serializer = new FastXmlSerializer();
623 serializer.setOutput(bos, "utf-8");
624 serializer.startDocument(null, true);
625 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
626
627 serializer.startTag(null, TAG_USER);
628 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700629 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700630 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700631 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
632 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
633 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700634 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
635 if (pinState != null) {
636 if (pinState.salt != 0) {
637 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
638 }
639 if (pinState.pinHash != null) {
640 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
641 }
642 if (pinState.failedAttempts != 0) {
643 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
644 Integer.toString(pinState.failedAttempts));
645 serializer.attribute(null, ATTR_LAST_RETRY_MS,
646 Long.toString(pinState.lastAttemptTime));
647 }
648 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700649 if (userInfo.iconPath != null) {
650 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
651 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700652 if (userInfo.partial) {
653 serializer.attribute(null, ATTR_PARTIAL, "true");
654 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700655
656 serializer.startTag(null, TAG_NAME);
657 serializer.text(userInfo.name);
658 serializer.endTag(null, TAG_NAME);
659
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800660 Bundle restrictions = mUserRestrictions.get(userInfo.id);
661 if (restrictions != null) {
662 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700663 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
664 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
665 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
666 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
667 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400668 writeBoolean(serializer, restrictions,
669 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
670 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
671 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400672 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
673 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800674 serializer.endTag(null, TAG_RESTRICTIONS);
675 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700676 serializer.endTag(null, TAG_USER);
677
678 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700679 userFile.finishWrite(fos);
680 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700681 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700682 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700683 }
684 }
685
686 /*
687 * Writes the user list file in this format:
688 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700689 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700690 * <user id="0"></user>
691 * <user id="2"></user>
692 * </users>
693 */
Amith Yamasani13593602012-03-22 16:16:17 -0700694 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700695 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700696 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700697 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700698 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700699 final BufferedOutputStream bos = new BufferedOutputStream(fos);
700
701 // XmlSerializer serializer = XmlUtils.serializerInstance();
702 final XmlSerializer serializer = new FastXmlSerializer();
703 serializer.setOutput(bos, "utf-8");
704 serializer.startDocument(null, true);
705 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
706
707 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700708 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700709 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700710
711 for (int i = 0; i < mUsers.size(); i++) {
712 UserInfo user = mUsers.valueAt(i);
713 serializer.startTag(null, TAG_USER);
714 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
715 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700716 }
717
718 serializer.endTag(null, TAG_USERS);
719
720 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700721 userListFile.finishWrite(fos);
722 } catch (Exception e) {
723 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700724 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700725 }
726 }
727
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800728 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700729 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700730 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700731 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700732 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700733 long creationTime = 0L;
734 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700735 long salt = 0L;
736 String pinHash = null;
737 int failedAttempts = 0;
738 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700739 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800740 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741
742 FileInputStream fis = null;
743 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700744 AtomicFile userFile =
745 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
746 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700747 XmlPullParser parser = Xml.newPullParser();
748 parser.setInput(fis, null);
749 int type;
750 while ((type = parser.next()) != XmlPullParser.START_TAG
751 && type != XmlPullParser.END_DOCUMENT) {
752 ;
753 }
754
755 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700756 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 return null;
758 }
759
760 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700761 int storedId = readIntAttribute(parser, ATTR_ID, -1);
762 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700763 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700764 return null;
765 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700766 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
767 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700768 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700769 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
770 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700771 salt = readLongAttribute(parser, ATTR_SALT, 0L);
772 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
773 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
774 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700775 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
776 if ("true".equals(valueString)) {
777 partial = true;
778 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700779
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800780 int outerDepth = parser.getDepth();
781 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
782 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
783 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
784 continue;
785 }
786 String tag = parser.getName();
787 if (TAG_NAME.equals(tag)) {
788 type = parser.next();
789 if (type == XmlPullParser.TEXT) {
790 name = parser.getText();
791 }
792 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700793 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
794 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
795 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
796 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
797 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400798 readBoolean(parser, restrictions,
799 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
800 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
801 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400802 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
803 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700804 }
805 }
806 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700807
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700808 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700809 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700810 userInfo.creationTime = creationTime;
811 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700812 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800813 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700814 if (salt != 0L) {
815 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
816 if (pinState == null) {
817 pinState = new RestrictionsPinState();
818 mRestrictionsPinStates.put(id, pinState);
819 }
820 pinState.salt = salt;
821 pinState.pinHash = pinHash;
822 pinState.failedAttempts = failedAttempts;
823 pinState.lastAttemptTime = lastAttemptTime;
824 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700825 return userInfo;
826
827 } catch (IOException ioe) {
828 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800829 } finally {
830 if (fis != null) {
831 try {
832 fis.close();
833 } catch (IOException e) {
834 }
835 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700836 }
837 return null;
838 }
839
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800840 private void readBoolean(XmlPullParser parser, Bundle restrictions,
841 String restrictionKey) {
842 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700843 if (value != null) {
844 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
845 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800846 }
847
848 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
849 throws IOException {
850 if (restrictions.containsKey(restrictionKey)) {
851 xml.attribute(null, restrictionKey,
852 Boolean.toString(restrictions.getBoolean(restrictionKey)));
853 }
854 }
855
Amith Yamasani920ace02012-09-20 22:15:37 -0700856 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
857 String valueString = parser.getAttributeValue(null, attr);
858 if (valueString == null) return defaultValue;
859 try {
860 return Integer.parseInt(valueString);
861 } catch (NumberFormatException nfe) {
862 return defaultValue;
863 }
864 }
865
866 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
867 String valueString = parser.getAttributeValue(null, attr);
868 if (valueString == null) return defaultValue;
869 try {
870 return Long.parseLong(valueString);
871 } catch (NumberFormatException nfe) {
872 return defaultValue;
873 }
874 }
875
Amith Yamasani258848d2012-08-10 17:06:33 -0700876 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700877 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700878 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700879
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700880 final long ident = Binder.clearCallingIdentity();
881 final UserInfo userInfo;
882 try {
883 synchronized (mInstallLock) {
884 synchronized (mPackagesLock) {
885 if (isUserLimitReachedLocked()) return null;
886 int userId = getNextAvailableIdLocked();
887 userInfo = new UserInfo(userId, name, null, flags);
888 File userPath = new File(mBaseUserPath, Integer.toString(userId));
889 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700890 long now = System.currentTimeMillis();
891 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700892 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700893 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700894 mUsers.put(userId, userInfo);
895 writeUserListLocked();
896 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700897 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700898 userInfo.partial = false;
899 writeUserLocked(userInfo);
900 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500901 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500902 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700903 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700904 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700905 if (userInfo != null) {
906 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
907 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
908 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
909 android.Manifest.permission.MANAGE_USERS);
910 }
911 } finally {
912 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700913 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700914 return userInfo;
915 }
916
Amith Yamasani0b285492011-04-14 17:35:23 -0700917 /**
918 * Removes a user and all data directories created for that user. This method should be called
919 * after the user's processes have been terminated.
920 * @param id the user's id
921 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700922 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700923 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700924 final UserInfo user;
925 synchronized (mPackagesLock) {
926 user = mUsers.get(userHandle);
927 if (userHandle == 0 || user == null) {
928 return false;
929 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800930 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700931 // Set this to a partially created user, so that the user will be purged
932 // on next startup, in case the runtime stops now before stopping and
933 // removing the user completely.
934 user.partial = true;
935 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700936 }
Amith Yamasani16389312012-10-17 21:20:14 -0700937 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700938 int res;
939 try {
940 res = ActivityManagerNative.getDefault().stopUser(userHandle,
941 new IStopUserCallback.Stub() {
942 @Override
943 public void userStopped(int userId) {
944 finishRemoveUser(userId);
945 }
946 @Override
947 public void userStopAborted(int userId) {
948 }
949 });
950 } catch (RemoteException e) {
951 return false;
952 }
953
954 return res == ActivityManager.USER_OP_SUCCESS;
955 }
956
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700957 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700958 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700959 // Let other services shutdown any activity and clean up their state before completely
960 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700961 long ident = Binder.clearCallingIdentity();
962 try {
963 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
964 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700965 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
966 android.Manifest.permission.MANAGE_USERS,
967
968 new BroadcastReceiver() {
969 @Override
970 public void onReceive(Context context, Intent intent) {
971 if (DBG) {
972 Slog.i(LOG_TAG,
973 "USER_REMOVED broadcast sent, cleaning up user data "
974 + userHandle);
975 }
976 new Thread() {
977 public void run() {
978 synchronized (mInstallLock) {
979 synchronized (mPackagesLock) {
980 removeUserStateLocked(userHandle);
981 }
982 }
983 }
984 }.start();
985 }
986 },
987
988 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700989 } finally {
990 Binder.restoreCallingIdentity(ident);
991 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700992 }
993
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800994 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700995 // Cleanup package manager settings
996 mPm.cleanUpUserLILPw(userHandle);
997
998 // Remove this user from the list
999 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001000
1001 // Have user ID linger for several seconds to let external storage VFS
1002 // cache entries expire. This must be greater than the 'entry_valid'
1003 // timeout used by the FUSE daemon.
1004 mHandler.postDelayed(new Runnable() {
1005 @Override
1006 public void run() {
1007 synchronized (mPackagesLock) {
1008 mRemovingUserIds.delete(userHandle);
1009 }
1010 }
1011 }, MINUTE_IN_MILLIS);
1012
Amith Yamasani655d0e22013-06-12 14:19:10 -07001013 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001014 // Remove user file
1015 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
1016 userFile.delete();
1017 // Update the user list
1018 writeUserListLocked();
1019 updateUserIdsLocked();
1020 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1021 }
1022
Amith Yamasani61f57372012-08-31 12:12:28 -07001023 private void removeDirectoryRecursive(File parent) {
1024 if (parent.isDirectory()) {
1025 String[] files = parent.list();
1026 for (String filename : files) {
1027 File child = new File(parent, filename);
1028 removeDirectoryRecursive(child);
1029 }
1030 }
1031 parent.delete();
1032 }
1033
Amith Yamasani2a003292012-08-14 18:25:45 -07001034 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001035 public Bundle getApplicationRestrictions(String packageName) {
1036 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1037 }
1038
1039 @Override
1040 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001041 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001042 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001043 checkManageUsersPermission("Only system can get restrictions for other users/apps");
1044 }
1045 synchronized (mPackagesLock) {
1046 // Read the restrictions from XML
1047 return readApplicationRestrictionsLocked(packageName, userId);
1048 }
1049 }
1050
1051 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001052 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001053 int userId) {
1054 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001055 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001056 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1057 }
1058 synchronized (mPackagesLock) {
1059 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001060 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001061 }
1062 }
1063
Amith Yamasani655d0e22013-06-12 14:19:10 -07001064 @Override
1065 public boolean changeRestrictionsPin(String newPin) {
1066 checkManageUsersPermission("Only system can modify the restrictions pin");
1067 int userId = UserHandle.getCallingUserId();
1068 synchronized (mPackagesLock) {
1069 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1070 if (pinState == null) {
1071 pinState = new RestrictionsPinState();
1072 }
1073 if (newPin == null) {
1074 pinState.salt = 0;
1075 pinState.pinHash = null;
1076 } else {
1077 try {
1078 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1079 } catch (NoSuchAlgorithmException e) {
1080 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1081 }
1082 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1083 pinState.failedAttempts = 0;
1084 }
1085 mRestrictionsPinStates.put(userId, pinState);
1086 writeUserLocked(mUsers.get(userId));
1087 }
1088 return true;
1089 }
1090
1091 @Override
1092 public int checkRestrictionsPin(String pin) {
1093 checkManageUsersPermission("Only system can verify the restrictions pin");
1094 int userId = UserHandle.getCallingUserId();
1095 synchronized (mPackagesLock) {
1096 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1097 // If there's no pin set, return error code
1098 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1099 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1100 } else if (pin == null) {
1101 // If just checking if user can be prompted, return remaining time
1102 int waitTime = getRemainingTimeForPinAttempt(pinState);
1103 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1104 return waitTime;
1105 } else {
1106 int waitTime = getRemainingTimeForPinAttempt(pinState);
1107 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1108 if (waitTime > 0) {
1109 return waitTime;
1110 }
1111 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1112 pinState.failedAttempts = 0;
1113 writeUserLocked(mUsers.get(userId));
1114 return UserManager.PIN_VERIFICATION_SUCCESS;
1115 } else {
1116 pinState.failedAttempts++;
1117 pinState.lastAttemptTime = System.currentTimeMillis();
1118 writeUserLocked(mUsers.get(userId));
1119 return waitTime;
1120 }
1121 }
1122 }
1123 }
1124
1125 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1126 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1127 BACKOFF_TIMES.length - 1);
1128 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1129 BACKOFF_TIMES[backoffIndex] : 0;
1130 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1131 0);
1132 }
1133
1134 @Override
1135 public boolean hasRestrictionsPin() {
1136 int userId = UserHandle.getCallingUserId();
1137 synchronized (mPackagesLock) {
1138 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1139 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1140 return false;
1141 }
1142 }
1143 return true;
1144 }
1145
1146 /*
1147 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1148 * Not the most secure, but it is at least a second level of protection. First level is that
1149 * the file is in a location only readable by the system process.
1150 * @param password the password.
1151 * @param salt the randomly generated salt
1152 * @return the hash of the pattern in a String.
1153 */
1154 private String passwordToHash(String password, long salt) {
1155 if (password == null) {
1156 return null;
1157 }
1158 String algo = null;
1159 String hashed = salt + password;
1160 try {
1161 byte[] saltedPassword = (password + salt).getBytes();
1162 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1163 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1164 hashed = toHex(sha1) + toHex(md5);
1165 } catch (NoSuchAlgorithmException e) {
1166 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1167 }
1168 return hashed;
1169 }
1170
1171 private static String toHex(byte[] ary) {
1172 final String hex = "0123456789ABCDEF";
1173 String ret = "";
1174 for (int i = 0; i < ary.length; i++) {
1175 ret += hex.charAt((ary[i] >> 4) & 0xf);
1176 ret += hex.charAt(ary[i] & 0xf);
1177 }
1178 return ret;
1179 }
1180
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001181 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001182 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001183 try {
1184 return mContext.getPackageManager().getApplicationInfo(packageName,
1185 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1186 } catch (NameNotFoundException nnfe) {
1187 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001188 } finally {
1189 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001190 }
1191 }
1192
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001193 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001194 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001195 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001196 final ArrayList<String> values = new ArrayList<String>();
1197
1198 FileInputStream fis = null;
1199 try {
1200 AtomicFile restrictionsFile =
1201 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1202 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1203 fis = restrictionsFile.openRead();
1204 XmlPullParser parser = Xml.newPullParser();
1205 parser.setInput(fis, null);
1206 int type;
1207 while ((type = parser.next()) != XmlPullParser.START_TAG
1208 && type != XmlPullParser.END_DOCUMENT) {
1209 ;
1210 }
1211
1212 if (type != XmlPullParser.START_TAG) {
1213 Slog.e(LOG_TAG, "Unable to read restrictions file "
1214 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001215 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001216 }
1217
1218 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1219 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1220 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001221 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001222 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1223 if (multiple != null) {
1224 int count = Integer.parseInt(multiple);
1225 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1226 if (type == XmlPullParser.START_TAG
1227 && parser.getName().equals(TAG_VALUE)) {
1228 values.add(parser.nextText().trim());
1229 count--;
1230 }
1231 }
1232 String [] valueStrings = new String[values.size()];
1233 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001234 restrictions.putStringArray(key, valueStrings);
1235 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1236 restrictions.putBoolean(key, Boolean.parseBoolean(
1237 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001238 } else {
1239 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001240 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001241 }
1242 }
1243 }
1244
1245 } catch (IOException ioe) {
1246 } catch (XmlPullParserException pe) {
1247 } finally {
1248 if (fis != null) {
1249 try {
1250 fis.close();
1251 } catch (IOException e) {
1252 }
1253 }
1254 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001255 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001256 }
1257
1258 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001259 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001260 FileOutputStream fos = null;
1261 AtomicFile restrictionsFile = new AtomicFile(
1262 new File(Environment.getUserSystemDirectory(userId),
1263 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1264 try {
1265 fos = restrictionsFile.startWrite();
1266 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1267
1268 // XmlSerializer serializer = XmlUtils.serializerInstance();
1269 final XmlSerializer serializer = new FastXmlSerializer();
1270 serializer.setOutput(bos, "utf-8");
1271 serializer.startDocument(null, true);
1272 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1273
1274 serializer.startTag(null, TAG_RESTRICTIONS);
1275
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001276 for (String key : restrictions.keySet()) {
1277 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001278 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001279 serializer.attribute(null, ATTR_KEY, key);
1280
1281 if (value instanceof Boolean) {
1282 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1283 serializer.text(value.toString());
1284 } else if (value == null || value instanceof String) {
1285 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1286 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001287 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001288 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1289 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001290 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001291 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001292 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001293 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001294 serializer.endTag(null, TAG_VALUE);
1295 }
1296 }
1297 serializer.endTag(null, TAG_ENTRY);
1298 }
1299
1300 serializer.endTag(null, TAG_RESTRICTIONS);
1301
1302 serializer.endDocument();
1303 restrictionsFile.finishWrite(fos);
1304 } catch (Exception e) {
1305 restrictionsFile.failWrite(fos);
1306 Slog.e(LOG_TAG, "Error writing application restrictions list");
1307 }
1308 }
1309
1310 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001311 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001312 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001313 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001314 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001315 }
1316 }
1317
1318 @Override
1319 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001320 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001321 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001322 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001323 }
1324 // Not found
1325 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001326 }
1327 }
1328
Amith Yamasani0b285492011-04-14 17:35:23 -07001329 /**
1330 * Caches the list of user ids in an array, adjusting the array size when necessary.
1331 */
Amith Yamasani13593602012-03-22 16:16:17 -07001332 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001333 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001334 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001335 if (!mUsers.valueAt(i).partial) {
1336 num++;
1337 }
1338 }
Amith Yamasani16389312012-10-17 21:20:14 -07001339 final int[] newUsers = new int[num];
1340 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001341 for (int i = 0; i < mUsers.size(); i++) {
1342 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001343 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001344 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001345 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001346 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001347 }
1348
1349 /**
Amith Yamasani920ace02012-09-20 22:15:37 -07001350 * Make a note of the last started time of a user.
1351 * @param userId the user that was just foregrounded
1352 */
1353 public void userForeground(int userId) {
1354 synchronized (mPackagesLock) {
1355 UserInfo user = mUsers.get(userId);
1356 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001357 if (user == null || user.partial) {
1358 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1359 return;
1360 }
1361 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001362 user.lastLoggedInTime = now;
1363 writeUserLocked(user);
1364 }
1365 }
1366 }
1367
1368 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001369 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001370 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1371 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001372 * @return
1373 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001374 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001375 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001376 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001377 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001378 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001379 break;
1380 }
1381 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001382 }
Amith Yamasani195263742012-08-21 15:40:12 -07001383 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001384 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001385 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001386
1387 @Override
1388 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1389 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1390 != PackageManager.PERMISSION_GRANTED) {
1391 pw.println("Permission Denial: can't dump UserManager from from pid="
1392 + Binder.getCallingPid()
1393 + ", uid=" + Binder.getCallingUid()
1394 + " without permission "
1395 + android.Manifest.permission.DUMP);
1396 return;
1397 }
1398
1399 long now = System.currentTimeMillis();
1400 StringBuilder sb = new StringBuilder();
1401 synchronized (mPackagesLock) {
1402 pw.println("Users:");
1403 for (int i = 0; i < mUsers.size(); i++) {
1404 UserInfo user = mUsers.valueAt(i);
1405 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001406 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001407 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001408 if (user.partial) pw.print(" <partial>");
1409 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001410 pw.print(" Created: ");
1411 if (user.creationTime == 0) {
1412 pw.println("<unknown>");
1413 } else {
1414 sb.setLength(0);
1415 TimeUtils.formatDuration(now - user.creationTime, sb);
1416 sb.append(" ago");
1417 pw.println(sb);
1418 }
1419 pw.print(" Last logged in: ");
1420 if (user.lastLoggedInTime == 0) {
1421 pw.println("<unknown>");
1422 } else {
1423 sb.setLength(0);
1424 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1425 sb.append(" ago");
1426 pw.println(sb);
1427 }
1428 }
1429 }
1430 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001431}