blob: 29012127b04e767af3cceb3e9939cc50c957705c [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 Yamasanib82add22013-07-09 11:24:44 -0700825 // If this is not a restricted profile and there is no restrictions pin, clean up
826 // any restrictions files that might have been left behind.
827 if (!userInfo.isRestricted() && salt == 0) {
828 cleanAppRestrictions(id);
829 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700830 return userInfo;
831
832 } catch (IOException ioe) {
833 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800834 } finally {
835 if (fis != null) {
836 try {
837 fis.close();
838 } catch (IOException e) {
839 }
840 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700841 }
842 return null;
843 }
844
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800845 private void readBoolean(XmlPullParser parser, Bundle restrictions,
846 String restrictionKey) {
847 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700848 if (value != null) {
849 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
850 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800851 }
852
853 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
854 throws IOException {
855 if (restrictions.containsKey(restrictionKey)) {
856 xml.attribute(null, restrictionKey,
857 Boolean.toString(restrictions.getBoolean(restrictionKey)));
858 }
859 }
860
Amith Yamasani920ace02012-09-20 22:15:37 -0700861 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
862 String valueString = parser.getAttributeValue(null, attr);
863 if (valueString == null) return defaultValue;
864 try {
865 return Integer.parseInt(valueString);
866 } catch (NumberFormatException nfe) {
867 return defaultValue;
868 }
869 }
870
871 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
872 String valueString = parser.getAttributeValue(null, attr);
873 if (valueString == null) return defaultValue;
874 try {
875 return Long.parseLong(valueString);
876 } catch (NumberFormatException nfe) {
877 return defaultValue;
878 }
879 }
880
Amith Yamasanib82add22013-07-09 11:24:44 -0700881 /**
882 * Removes all the restrictions files (res_<packagename>) for a given user.
883 * Does not do any permissions checking.
884 */
885 private void cleanAppRestrictions(int userId) {
886 synchronized (mPackagesLock) {
887 File dir = Environment.getUserSystemDirectory(userId);
888 String[] files = dir.list();
889 if (files == null) return;
890 for (String fileName : files) {
891 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
892 File resFile = new File(dir, fileName);
893 if (resFile.exists()) {
894 resFile.delete();
895 }
896 }
897 }
898 }
899 }
900
Amith Yamasani258848d2012-08-10 17:06:33 -0700901 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700902 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700903 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700904
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700905 final long ident = Binder.clearCallingIdentity();
906 final UserInfo userInfo;
907 try {
908 synchronized (mInstallLock) {
909 synchronized (mPackagesLock) {
910 if (isUserLimitReachedLocked()) return null;
911 int userId = getNextAvailableIdLocked();
912 userInfo = new UserInfo(userId, name, null, flags);
913 File userPath = new File(mBaseUserPath, Integer.toString(userId));
914 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700915 long now = System.currentTimeMillis();
916 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700917 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700918 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700919 mUsers.put(userId, userInfo);
920 writeUserListLocked();
921 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700922 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700923 userInfo.partial = false;
924 writeUserLocked(userInfo);
925 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500926 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500927 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700928 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700929 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700930 if (userInfo != null) {
931 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
932 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
933 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
934 android.Manifest.permission.MANAGE_USERS);
935 }
936 } finally {
937 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700938 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700939 return userInfo;
940 }
941
Amith Yamasani0b285492011-04-14 17:35:23 -0700942 /**
943 * Removes a user and all data directories created for that user. This method should be called
944 * after the user's processes have been terminated.
945 * @param id the user's id
946 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700947 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700948 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700949 final UserInfo user;
950 synchronized (mPackagesLock) {
951 user = mUsers.get(userHandle);
952 if (userHandle == 0 || user == null) {
953 return false;
954 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800955 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700956 // Set this to a partially created user, so that the user will be purged
957 // on next startup, in case the runtime stops now before stopping and
958 // removing the user completely.
959 user.partial = true;
960 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700961 }
Amith Yamasani16389312012-10-17 21:20:14 -0700962 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700963 int res;
964 try {
965 res = ActivityManagerNative.getDefault().stopUser(userHandle,
966 new IStopUserCallback.Stub() {
967 @Override
968 public void userStopped(int userId) {
969 finishRemoveUser(userId);
970 }
971 @Override
972 public void userStopAborted(int userId) {
973 }
974 });
975 } catch (RemoteException e) {
976 return false;
977 }
978
979 return res == ActivityManager.USER_OP_SUCCESS;
980 }
981
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700982 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700983 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700984 // Let other services shutdown any activity and clean up their state before completely
985 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700986 long ident = Binder.clearCallingIdentity();
987 try {
988 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
989 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700990 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
991 android.Manifest.permission.MANAGE_USERS,
992
993 new BroadcastReceiver() {
994 @Override
995 public void onReceive(Context context, Intent intent) {
996 if (DBG) {
997 Slog.i(LOG_TAG,
998 "USER_REMOVED broadcast sent, cleaning up user data "
999 + userHandle);
1000 }
1001 new Thread() {
1002 public void run() {
1003 synchronized (mInstallLock) {
1004 synchronized (mPackagesLock) {
1005 removeUserStateLocked(userHandle);
1006 }
1007 }
1008 }
1009 }.start();
1010 }
1011 },
1012
1013 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001014 } finally {
1015 Binder.restoreCallingIdentity(ident);
1016 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001017 }
1018
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001019 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001020 // Cleanup package manager settings
1021 mPm.cleanUpUserLILPw(userHandle);
1022
1023 // Remove this user from the list
1024 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001025
1026 // Have user ID linger for several seconds to let external storage VFS
1027 // cache entries expire. This must be greater than the 'entry_valid'
1028 // timeout used by the FUSE daemon.
1029 mHandler.postDelayed(new Runnable() {
1030 @Override
1031 public void run() {
1032 synchronized (mPackagesLock) {
1033 mRemovingUserIds.delete(userHandle);
1034 }
1035 }
1036 }, MINUTE_IN_MILLIS);
1037
Amith Yamasani655d0e22013-06-12 14:19:10 -07001038 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001039 // Remove user file
1040 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
1041 userFile.delete();
1042 // Update the user list
1043 writeUserListLocked();
1044 updateUserIdsLocked();
1045 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1046 }
1047
Amith Yamasani61f57372012-08-31 12:12:28 -07001048 private void removeDirectoryRecursive(File parent) {
1049 if (parent.isDirectory()) {
1050 String[] files = parent.list();
1051 for (String filename : files) {
1052 File child = new File(parent, filename);
1053 removeDirectoryRecursive(child);
1054 }
1055 }
1056 parent.delete();
1057 }
1058
Amith Yamasani2a003292012-08-14 18:25:45 -07001059 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001060 public Bundle getApplicationRestrictions(String packageName) {
1061 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1062 }
1063
1064 @Override
1065 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001066 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001067 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001068 checkManageUsersPermission("Only system can get restrictions for other users/apps");
1069 }
1070 synchronized (mPackagesLock) {
1071 // Read the restrictions from XML
1072 return readApplicationRestrictionsLocked(packageName, userId);
1073 }
1074 }
1075
1076 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001077 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001078 int userId) {
1079 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001080 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001081 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1082 }
1083 synchronized (mPackagesLock) {
1084 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001085 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001086 }
1087 }
1088
Amith Yamasani655d0e22013-06-12 14:19:10 -07001089 @Override
1090 public boolean changeRestrictionsPin(String newPin) {
1091 checkManageUsersPermission("Only system can modify the restrictions pin");
1092 int userId = UserHandle.getCallingUserId();
1093 synchronized (mPackagesLock) {
1094 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1095 if (pinState == null) {
1096 pinState = new RestrictionsPinState();
1097 }
1098 if (newPin == null) {
1099 pinState.salt = 0;
1100 pinState.pinHash = null;
1101 } else {
1102 try {
1103 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1104 } catch (NoSuchAlgorithmException e) {
1105 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1106 }
1107 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1108 pinState.failedAttempts = 0;
1109 }
1110 mRestrictionsPinStates.put(userId, pinState);
1111 writeUserLocked(mUsers.get(userId));
1112 }
1113 return true;
1114 }
1115
1116 @Override
1117 public int checkRestrictionsPin(String pin) {
1118 checkManageUsersPermission("Only system can verify the restrictions pin");
1119 int userId = UserHandle.getCallingUserId();
1120 synchronized (mPackagesLock) {
1121 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1122 // If there's no pin set, return error code
1123 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1124 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1125 } else if (pin == null) {
1126 // If just checking if user can be prompted, return remaining time
1127 int waitTime = getRemainingTimeForPinAttempt(pinState);
1128 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1129 return waitTime;
1130 } else {
1131 int waitTime = getRemainingTimeForPinAttempt(pinState);
1132 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1133 if (waitTime > 0) {
1134 return waitTime;
1135 }
1136 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1137 pinState.failedAttempts = 0;
1138 writeUserLocked(mUsers.get(userId));
1139 return UserManager.PIN_VERIFICATION_SUCCESS;
1140 } else {
1141 pinState.failedAttempts++;
1142 pinState.lastAttemptTime = System.currentTimeMillis();
1143 writeUserLocked(mUsers.get(userId));
1144 return waitTime;
1145 }
1146 }
1147 }
1148 }
1149
1150 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1151 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1152 BACKOFF_TIMES.length - 1);
1153 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1154 BACKOFF_TIMES[backoffIndex] : 0;
1155 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1156 0);
1157 }
1158
1159 @Override
1160 public boolean hasRestrictionsPin() {
1161 int userId = UserHandle.getCallingUserId();
1162 synchronized (mPackagesLock) {
1163 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1164 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1165 return false;
1166 }
1167 }
1168 return true;
1169 }
1170
1171 /*
1172 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1173 * Not the most secure, but it is at least a second level of protection. First level is that
1174 * the file is in a location only readable by the system process.
1175 * @param password the password.
1176 * @param salt the randomly generated salt
1177 * @return the hash of the pattern in a String.
1178 */
1179 private String passwordToHash(String password, long salt) {
1180 if (password == null) {
1181 return null;
1182 }
1183 String algo = null;
1184 String hashed = salt + password;
1185 try {
1186 byte[] saltedPassword = (password + salt).getBytes();
1187 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1188 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1189 hashed = toHex(sha1) + toHex(md5);
1190 } catch (NoSuchAlgorithmException e) {
1191 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1192 }
1193 return hashed;
1194 }
1195
1196 private static String toHex(byte[] ary) {
1197 final String hex = "0123456789ABCDEF";
1198 String ret = "";
1199 for (int i = 0; i < ary.length; i++) {
1200 ret += hex.charAt((ary[i] >> 4) & 0xf);
1201 ret += hex.charAt(ary[i] & 0xf);
1202 }
1203 return ret;
1204 }
1205
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001206 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001207 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001208 try {
1209 return mContext.getPackageManager().getApplicationInfo(packageName,
1210 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1211 } catch (NameNotFoundException nnfe) {
1212 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001213 } finally {
1214 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001215 }
1216 }
1217
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001218 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001219 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001220 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001221 final ArrayList<String> values = new ArrayList<String>();
1222
1223 FileInputStream fis = null;
1224 try {
1225 AtomicFile restrictionsFile =
1226 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1227 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1228 fis = restrictionsFile.openRead();
1229 XmlPullParser parser = Xml.newPullParser();
1230 parser.setInput(fis, null);
1231 int type;
1232 while ((type = parser.next()) != XmlPullParser.START_TAG
1233 && type != XmlPullParser.END_DOCUMENT) {
1234 ;
1235 }
1236
1237 if (type != XmlPullParser.START_TAG) {
1238 Slog.e(LOG_TAG, "Unable to read restrictions file "
1239 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001240 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001241 }
1242
1243 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1244 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1245 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001246 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001247 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1248 if (multiple != null) {
1249 int count = Integer.parseInt(multiple);
1250 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1251 if (type == XmlPullParser.START_TAG
1252 && parser.getName().equals(TAG_VALUE)) {
1253 values.add(parser.nextText().trim());
1254 count--;
1255 }
1256 }
1257 String [] valueStrings = new String[values.size()];
1258 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001259 restrictions.putStringArray(key, valueStrings);
1260 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1261 restrictions.putBoolean(key, Boolean.parseBoolean(
1262 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001263 } else {
1264 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001265 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001266 }
1267 }
1268 }
1269
1270 } catch (IOException ioe) {
1271 } catch (XmlPullParserException pe) {
1272 } finally {
1273 if (fis != null) {
1274 try {
1275 fis.close();
1276 } catch (IOException e) {
1277 }
1278 }
1279 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001280 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001281 }
1282
1283 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001284 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001285 FileOutputStream fos = null;
1286 AtomicFile restrictionsFile = new AtomicFile(
1287 new File(Environment.getUserSystemDirectory(userId),
1288 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1289 try {
1290 fos = restrictionsFile.startWrite();
1291 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1292
1293 // XmlSerializer serializer = XmlUtils.serializerInstance();
1294 final XmlSerializer serializer = new FastXmlSerializer();
1295 serializer.setOutput(bos, "utf-8");
1296 serializer.startDocument(null, true);
1297 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1298
1299 serializer.startTag(null, TAG_RESTRICTIONS);
1300
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001301 for (String key : restrictions.keySet()) {
1302 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001303 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001304 serializer.attribute(null, ATTR_KEY, key);
1305
1306 if (value instanceof Boolean) {
1307 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1308 serializer.text(value.toString());
1309 } else if (value == null || value instanceof String) {
1310 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1311 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001312 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001313 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1314 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001315 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001316 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001317 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001318 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001319 serializer.endTag(null, TAG_VALUE);
1320 }
1321 }
1322 serializer.endTag(null, TAG_ENTRY);
1323 }
1324
1325 serializer.endTag(null, TAG_RESTRICTIONS);
1326
1327 serializer.endDocument();
1328 restrictionsFile.finishWrite(fos);
1329 } catch (Exception e) {
1330 restrictionsFile.failWrite(fos);
1331 Slog.e(LOG_TAG, "Error writing application restrictions list");
1332 }
1333 }
1334
1335 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001336 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001337 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001338 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001339 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001340 }
1341 }
1342
1343 @Override
1344 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001345 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001346 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001347 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001348 }
1349 // Not found
1350 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001351 }
1352 }
1353
Amith Yamasani0b285492011-04-14 17:35:23 -07001354 /**
1355 * Caches the list of user ids in an array, adjusting the array size when necessary.
1356 */
Amith Yamasani13593602012-03-22 16:16:17 -07001357 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001358 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001359 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001360 if (!mUsers.valueAt(i).partial) {
1361 num++;
1362 }
1363 }
Amith Yamasani16389312012-10-17 21:20:14 -07001364 final int[] newUsers = new int[num];
1365 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001366 for (int i = 0; i < mUsers.size(); i++) {
1367 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001368 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001369 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001370 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001371 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001372 }
1373
1374 /**
Amith Yamasani920ace02012-09-20 22:15:37 -07001375 * Make a note of the last started time of a user.
1376 * @param userId the user that was just foregrounded
1377 */
1378 public void userForeground(int userId) {
1379 synchronized (mPackagesLock) {
1380 UserInfo user = mUsers.get(userId);
1381 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001382 if (user == null || user.partial) {
1383 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1384 return;
1385 }
1386 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001387 user.lastLoggedInTime = now;
1388 writeUserLocked(user);
1389 }
1390 }
1391 }
1392
1393 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001394 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001395 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1396 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001397 * @return
1398 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001399 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001400 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001401 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001402 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001403 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001404 break;
1405 }
1406 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001407 }
Amith Yamasani195263742012-08-21 15:40:12 -07001408 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001409 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001410 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001411
1412 @Override
1413 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1414 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1415 != PackageManager.PERMISSION_GRANTED) {
1416 pw.println("Permission Denial: can't dump UserManager from from pid="
1417 + Binder.getCallingPid()
1418 + ", uid=" + Binder.getCallingUid()
1419 + " without permission "
1420 + android.Manifest.permission.DUMP);
1421 return;
1422 }
1423
1424 long now = System.currentTimeMillis();
1425 StringBuilder sb = new StringBuilder();
1426 synchronized (mPackagesLock) {
1427 pw.println("Users:");
1428 for (int i = 0; i < mUsers.size(); i++) {
1429 UserInfo user = mUsers.valueAt(i);
1430 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001431 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001432 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001433 if (user.partial) pw.print(" <partial>");
1434 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001435 pw.print(" Created: ");
1436 if (user.creationTime == 0) {
1437 pw.println("<unknown>");
1438 } else {
1439 sb.setLength(0);
1440 TimeUtils.formatDuration(now - user.creationTime, sb);
1441 sb.append(" ago");
1442 pw.println(sb);
1443 }
1444 pw.print(" Last logged in: ");
1445 if (user.lastLoggedInTime == 0) {
1446 pw.println("<unknown>");
1447 } else {
1448 sb.setLength(0);
1449 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1450 sb.append(" ago");
1451 pw.println(sb);
1452 }
1453 }
1454 }
1455 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001456}