blob: 5760dcd0aecea489df35fe4e6b55a59798cef35b [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 Yamasani0b285492011-04-14 17:35:23 -070028import android.content.pm.PackageManager;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070029import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070030import android.graphics.Bitmap;
31import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070032import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080033import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070034import android.os.Environment;
35import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080036import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070038import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070039import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070040import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070041import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070042import android.util.AtomicFile;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070043import android.util.Slog;
44import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080045import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070046import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Xml;
48
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import com.android.internal.util.ArrayUtils;
50import com.android.internal.util.FastXmlSerializer;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
55
Amith Yamasani4b2e9342011-03-31 12:38:53 -070056import java.io.BufferedOutputStream;
57import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070058import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070060import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.FileOutputStream;
62import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.PrintWriter;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.util.ArrayList;
65import java.util.List;
66
Amith Yamasani258848d2012-08-10 17:06:33 -070067public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070068
Amith Yamasani2a003292012-08-14 18:25:45 -070069 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070070
Amith Yamasani16389312012-10-17 21:20:14 -070071 private static final boolean DBG = false;
72
Amith Yamasani4b2e9342011-03-31 12:38:53 -070073 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070074 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070075 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070077 private static final String ATTR_CREATION_TIME = "created";
78 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070079 private static final String ATTR_SERIAL_NO = "serialNumber";
80 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070081 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070082 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080085 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086
Amith Yamasani0b285492011-04-14 17:35:23 -070087 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070088 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070089 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090
Amith Yamasani634cf312012-10-04 17:34:21 -070091 private static final int MIN_USER_ID = 10;
92
Amith Yamasanibc9625052012-11-15 14:39:18 -080093 private static final int USER_VERSION = 2;
Amith Yamasani6f34b412012-10-22 18:19:27 -070094
Amith Yamasani920ace02012-09-20 22:15:37 -070095 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
96
Dianne Hackborn4428e172012-08-24 17:43:05 -070097 private final Context mContext;
98 private final PackageManagerService mPm;
99 private final Object mInstallLock;
100 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700101
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800102 private final Handler mHandler;
103
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700104 private final File mUsersDir;
105 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700106 private final File mBaseUserPath;
107
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800108 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800109 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800110
111 /**
112 * Set of user IDs being actively removed. Removed IDs linger in this set
113 * for several seconds to work around a VFS caching issue.
114 */
115 // @GuardedBy("mPackagesLock")
116 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700117
Amith Yamasani0b285492011-04-14 17:35:23 -0700118 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700119 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700120 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700121 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700122
Amith Yamasani258848d2012-08-10 17:06:33 -0700123 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700124
Dianne Hackborn4428e172012-08-24 17:43:05 -0700125 public static UserManagerService getInstance() {
126 synchronized (UserManagerService.class) {
127 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700128 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700129 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700130
131 /**
132 * Available for testing purposes.
133 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700134 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700135 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700136 }
137
Dianne Hackborn4428e172012-08-24 17:43:05 -0700138 /**
139 * Called by package manager to create the service. This is closely
140 * associated with the package manager, and the given lock is the
141 * package manager's own lock.
142 */
143 UserManagerService(Context context, PackageManagerService pm,
144 Object installLock, Object packagesLock) {
145 this(context, pm, installLock, packagesLock,
146 Environment.getDataDirectory(),
147 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700148 }
149
Dianne Hackborn4428e172012-08-24 17:43:05 -0700150 /**
151 * Available for testing purposes.
152 */
153 private UserManagerService(Context context, PackageManagerService pm,
154 Object installLock, Object packagesLock,
155 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700156 mContext = context;
157 mPm = pm;
158 mInstallLock = installLock;
159 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800160 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700161 synchronized (mInstallLock) {
162 synchronized (mPackagesLock) {
163 mUsersDir = new File(dataDir, USER_INFO_DIR);
164 mUsersDir.mkdirs();
165 // Make zeroth user directory, for services to migrate their files to that location
166 File userZeroDir = new File(mUsersDir, "0");
167 userZeroDir.mkdirs();
168 mBaseUserPath = baseUserPath;
169 FileUtils.setPermissions(mUsersDir.toString(),
170 FileUtils.S_IRWXU|FileUtils.S_IRWXG
171 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
172 -1, -1);
173 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
174 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700175 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700176 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
177 for (int i = 0; i < mUsers.size(); i++) {
178 UserInfo ui = mUsers.valueAt(i);
179 if (ui.partial && i != 0) {
180 partials.add(ui);
181 }
182 }
183 for (int i = 0; i < partials.size(); i++) {
184 UserInfo ui = partials.get(i);
185 Slog.w(LOG_TAG, "Removing partially created user #" + i
186 + " (name=" + ui.name + ")");
187 removeUserStateLocked(ui.id);
188 }
189 sInstance = this;
190 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700192 }
193
194 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700195 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700196 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700197 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700198 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
199 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700200 UserInfo ui = mUsers.valueAt(i);
201 if (ui.partial) {
202 continue;
203 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800204 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700205 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700206 }
Amith Yamasani13593602012-03-22 16:16:17 -0700207 }
208 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700209 }
Amith Yamasani13593602012-03-22 16:16:17 -0700210 }
211
Amith Yamasani258848d2012-08-10 17:06:33 -0700212 @Override
213 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700214 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700215 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700216 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700217 }
218 }
219
Amith Yamasani195263742012-08-21 15:40:12 -0700220 /*
221 * Should be locked on mUsers before calling this.
222 */
223 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700224 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700225 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800226 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700227 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
228 return null;
229 }
230 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700231 }
232
Amith Yamasani13593602012-03-22 16:16:17 -0700233 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700235 return ArrayUtils.contains(mUserIds, userId);
236 }
237 }
238
Amith Yamasani258848d2012-08-10 17:06:33 -0700239 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700240 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700241 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700242 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700244 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700245 if (info == null || info.partial) {
246 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
247 return;
248 }
Amith Yamasani13593602012-03-22 16:16:17 -0700249 if (name != null && !name.equals(info.name)) {
250 info.name = name;
251 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700253 }
254 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 if (changed) {
256 sendUserInfoChangedBroadcast(userId);
257 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700258 }
259
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700261 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700262 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700264 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700265 if (info == null || info.partial) {
266 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
267 return;
268 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700269 writeBitmapLocked(info, bitmap);
270 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700271 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700272 sendUserInfoChangedBroadcast(userId);
273 }
274
275 private void sendUserInfoChangedBroadcast(int userId) {
276 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
277 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
278 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
279 mContext.sendBroadcastAsUser(changedIntent, new UserHandle(userId));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700280 }
281
Amith Yamasani258848d2012-08-10 17:06:33 -0700282 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700283 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700284 checkManageUsersPermission("read users");
285 synchronized (mPackagesLock) {
286 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700287 if (info == null || info.partial) {
288 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
289 return null;
290 }
291 if (info.iconPath == null) {
292 return null;
293 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700294 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700295 }
296 }
297
298 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700299 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700300 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700301 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700302 if (mGuestEnabled != enable) {
303 mGuestEnabled = enable;
304 // Erase any guest user that currently exists
305 for (int i = 0; i < mUsers.size(); i++) {
306 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700307 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700308 if (!enable) {
309 removeUser(user.id);
310 }
311 return;
312 }
313 }
314 // No guest was found
315 if (enable) {
316 createUser("Guest", UserInfo.FLAG_GUEST);
317 }
318 }
319 }
320 }
321
322 @Override
323 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700324 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700325 return mGuestEnabled;
326 }
327 }
328
329 @Override
330 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700331 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700332 // TODO:
333 }
334
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700335 public void makeInitialized(int userId) {
336 checkManageUsersPermission("makeInitialized");
337 synchronized (mPackagesLock) {
338 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700339 if (info == null || info.partial) {
340 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
341 }
342 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700343 info.flags |= UserInfo.FLAG_INITIALIZED;
344 writeUserLocked(info);
345 }
346 }
347 }
348
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800349 @Override
350 public Bundle getUserRestrictions(int userId) {
351 // checkManageUsersPermission("getUserRestrictions");
352
353 synchronized (mPackagesLock) {
354 Bundle restrictions = mUserRestrictions.get(userId);
355 return restrictions != null ? restrictions : Bundle.EMPTY;
356 }
357 }
358
359 @Override
360 public void setUserRestrictions(Bundle restrictions, int userId) {
361 checkManageUsersPermission("setUserRestrictions");
362
363 synchronized (mPackagesLock) {
364 mUserRestrictions.get(userId).putAll(restrictions);
365 writeUserLocked(mUsers.get(userId));
366 }
367 }
368
Amith Yamasani258848d2012-08-10 17:06:33 -0700369 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700370 * Check if we've hit the limit of how many users can be created.
371 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700372 private boolean isUserLimitReachedLocked() {
373 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700374 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700375 }
376
377 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700378 * Enforces that only the system UID or root's UID or apps that have the
379 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
380 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700381 *
382 * @param message used as message if SecurityException is thrown
383 * @throws SecurityException if the caller is not system or root
384 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700385 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700386 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700387 if (uid != Process.SYSTEM_UID && uid != 0
388 && ActivityManager.checkComponentPermission(
389 android.Manifest.permission.MANAGE_USERS,
390 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
391 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700392 }
393 }
394
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700395 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700396 try {
397 File dir = new File(mUsersDir, Integer.toString(info.id));
398 File file = new File(dir, USER_PHOTO_FILENAME);
399 if (!dir.exists()) {
400 dir.mkdir();
401 FileUtils.setPermissions(
402 dir.getPath(),
403 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
404 -1, -1);
405 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700406 FileOutputStream os;
407 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700408 info.iconPath = file.getAbsolutePath();
409 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700410 try {
411 os.close();
412 } catch (IOException ioe) {
413 // What the ... !
414 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700415 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700416 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700417 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700418 }
419
Amith Yamasani0b285492011-04-14 17:35:23 -0700420 /**
421 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
422 * cache it elsewhere.
423 * @return the array of user ids.
424 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700425 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700426 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700427 return mUserIds;
428 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700429 }
430
Dianne Hackborn4428e172012-08-24 17:43:05 -0700431 int[] getUserIdsLPr() {
432 return mUserIds;
433 }
434
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700435 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700436 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700437 readUserListLocked();
438 }
439 }
440
441 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700442 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700443 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700444 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700445 return;
446 }
447 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700448 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700449 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700450 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700451 XmlPullParser parser = Xml.newPullParser();
452 parser.setInput(fis, null);
453 int type;
454 while ((type = parser.next()) != XmlPullParser.START_TAG
455 && type != XmlPullParser.END_DOCUMENT) {
456 ;
457 }
458
459 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700460 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700461 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700462 return;
463 }
464
Amith Yamasani2a003292012-08-14 18:25:45 -0700465 mNextSerialNumber = -1;
466 if (parser.getName().equals(TAG_USERS)) {
467 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
468 if (lastSerialNumber != null) {
469 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
470 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700471 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
472 if (versionNumber != null) {
473 mUserVersion = Integer.parseInt(versionNumber);
474 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700475 }
476
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700477 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
478 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
479 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800480 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700481
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700482 if (user != null) {
483 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700484 if (user.isGuest()) {
485 mGuestEnabled = true;
486 }
487 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
488 mNextSerialNumber = user.id + 1;
489 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700490 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700491 }
492 }
Amith Yamasani13593602012-03-22 16:16:17 -0700493 updateUserIdsLocked();
Amith Yamasani6f34b412012-10-22 18:19:27 -0700494 upgradeIfNecessary();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700495 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700496 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700497 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700498 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800499 } finally {
500 if (fis != null) {
501 try {
502 fis.close();
503 } catch (IOException e) {
504 }
505 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700506 }
507 }
508
Amith Yamasani6f34b412012-10-22 18:19:27 -0700509 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800510 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700511 */
512 private void upgradeIfNecessary() {
513 int userVersion = mUserVersion;
514 if (userVersion < 1) {
515 // Assign a proper name for the owner, if not initialized correctly before
516 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
517 if ("Primary".equals(user.name)) {
518 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
519 writeUserLocked(user);
520 }
521 userVersion = 1;
522 }
523
Amith Yamasanibc9625052012-11-15 14:39:18 -0800524 if (userVersion < 2) {
525 // Owner should be marked as initialized
526 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
527 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
528 user.flags |= UserInfo.FLAG_INITIALIZED;
529 writeUserLocked(user);
530 }
531 userVersion = 2;
532 }
533
Amith Yamasani6f34b412012-10-22 18:19:27 -0700534 if (userVersion < USER_VERSION) {
535 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
536 + USER_VERSION);
537 } else {
538 mUserVersion = userVersion;
539 writeUserListLocked();
540 }
541 }
542
Amith Yamasani13593602012-03-22 16:16:17 -0700543 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700544 // Create the primary user
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800545 UserInfo primary = new UserInfo(0,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700546 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700547 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700548 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700549 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani13593602012-03-22 16:16:17 -0700550 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700551
Amith Yamasani13593602012-03-22 16:16:17 -0700552 writeUserListLocked();
553 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700554 }
555
556 /*
557 * Writes the user file in this format:
558 *
559 * <user flags="20039023" id="0">
560 * <name>Primary</name>
561 * </user>
562 */
Amith Yamasani13593602012-03-22 16:16:17 -0700563 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700564 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700565 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700566 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700567 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700568 final BufferedOutputStream bos = new BufferedOutputStream(fos);
569
570 // XmlSerializer serializer = XmlUtils.serializerInstance();
571 final XmlSerializer serializer = new FastXmlSerializer();
572 serializer.setOutput(bos, "utf-8");
573 serializer.startDocument(null, true);
574 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
575
576 serializer.startTag(null, TAG_USER);
577 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700578 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700579 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700580 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
581 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
582 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700583 if (userInfo.iconPath != null) {
584 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
585 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700586 if (userInfo.partial) {
587 serializer.attribute(null, ATTR_PARTIAL, "true");
588 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700589
590 serializer.startTag(null, TAG_NAME);
591 serializer.text(userInfo.name);
592 serializer.endTag(null, TAG_NAME);
593
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800594 Bundle restrictions = mUserRestrictions.get(userInfo.id);
595 if (restrictions != null) {
596 serializer.startTag(null, TAG_RESTRICTIONS);
597 writeBoolean(serializer, restrictions, UserManager.ALLOW_CONFIG_WIFI);
598 writeBoolean(serializer, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
599 writeBoolean(serializer, restrictions, UserManager.ALLOW_INSTALL_APPS);
600 writeBoolean(serializer, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
601 serializer.endTag(null, TAG_RESTRICTIONS);
602 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700603 serializer.endTag(null, TAG_USER);
604
605 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700606 userFile.finishWrite(fos);
607 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700608 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700609 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700610 }
611 }
612
613 /*
614 * Writes the user list file in this format:
615 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700616 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700617 * <user id="0"></user>
618 * <user id="2"></user>
619 * </users>
620 */
Amith Yamasani13593602012-03-22 16:16:17 -0700621 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700622 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700623 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700624 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700625 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700626 final BufferedOutputStream bos = new BufferedOutputStream(fos);
627
628 // XmlSerializer serializer = XmlUtils.serializerInstance();
629 final XmlSerializer serializer = new FastXmlSerializer();
630 serializer.setOutput(bos, "utf-8");
631 serializer.startDocument(null, true);
632 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
633
634 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700635 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700636 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700637
638 for (int i = 0; i < mUsers.size(); i++) {
639 UserInfo user = mUsers.valueAt(i);
640 serializer.startTag(null, TAG_USER);
641 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
642 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700643 }
644
645 serializer.endTag(null, TAG_USERS);
646
647 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700648 userListFile.finishWrite(fos);
649 } catch (Exception e) {
650 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700651 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700652 }
653 }
654
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800655 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700656 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700657 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700658 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700659 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700660 long creationTime = 0L;
661 long lastLoggedInTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700662 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800663 Bundle restrictions = new Bundle();
664 initRestrictionsToDefaults(restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665
666 FileInputStream fis = null;
667 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700668 AtomicFile userFile =
669 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
670 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700671 XmlPullParser parser = Xml.newPullParser();
672 parser.setInput(fis, null);
673 int type;
674 while ((type = parser.next()) != XmlPullParser.START_TAG
675 && type != XmlPullParser.END_DOCUMENT) {
676 ;
677 }
678
679 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700680 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700681 return null;
682 }
683
684 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700685 int storedId = readIntAttribute(parser, ATTR_ID, -1);
686 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700687 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700688 return null;
689 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700690 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
691 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700692 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700693 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
694 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700695 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
696 if ("true".equals(valueString)) {
697 partial = true;
698 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700699
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800700 int outerDepth = parser.getDepth();
701 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
702 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
703 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
704 continue;
705 }
706 String tag = parser.getName();
707 if (TAG_NAME.equals(tag)) {
708 type = parser.next();
709 if (type == XmlPullParser.TEXT) {
710 name = parser.getText();
711 }
712 } else if (TAG_RESTRICTIONS.equals(tag)) {
713 readBoolean(parser, restrictions, UserManager.ALLOW_CONFIG_WIFI);
714 readBoolean(parser, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
715 readBoolean(parser, restrictions, UserManager.ALLOW_INSTALL_APPS);
716 readBoolean(parser, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700717 }
718 }
719 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700721 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700722 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700723 userInfo.creationTime = creationTime;
724 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700725 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800726 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700727 return userInfo;
728
729 } catch (IOException ioe) {
730 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800731 } finally {
732 if (fis != null) {
733 try {
734 fis.close();
735 } catch (IOException e) {
736 }
737 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 }
739 return null;
740 }
741
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800742 private void readBoolean(XmlPullParser parser, Bundle restrictions,
743 String restrictionKey) {
744 String value = parser.getAttributeValue(null, restrictionKey);
745 restrictions.putBoolean(restrictionKey, value == null ? true : Boolean.parseBoolean(value));
746 }
747
748 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
749 throws IOException {
750 if (restrictions.containsKey(restrictionKey)) {
751 xml.attribute(null, restrictionKey,
752 Boolean.toString(restrictions.getBoolean(restrictionKey)));
753 }
754 }
755
756 private void initRestrictionsToDefaults(Bundle restrictions) {
757 restrictions.putBoolean(UserManager.ALLOW_CONFIG_WIFI, true);
758 restrictions.putBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS, true);
759 restrictions.putBoolean(UserManager.ALLOW_INSTALL_APPS, true);
760 restrictions.putBoolean(UserManager.ALLOW_UNINSTALL_APPS, true);
761 }
762
Amith Yamasani920ace02012-09-20 22:15:37 -0700763 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
764 String valueString = parser.getAttributeValue(null, attr);
765 if (valueString == null) return defaultValue;
766 try {
767 return Integer.parseInt(valueString);
768 } catch (NumberFormatException nfe) {
769 return defaultValue;
770 }
771 }
772
773 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
774 String valueString = parser.getAttributeValue(null, attr);
775 if (valueString == null) return defaultValue;
776 try {
777 return Long.parseLong(valueString);
778 } catch (NumberFormatException nfe) {
779 return defaultValue;
780 }
781 }
782
Amith Yamasani258848d2012-08-10 17:06:33 -0700783 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700784 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700785 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700786
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700787 final long ident = Binder.clearCallingIdentity();
788 final UserInfo userInfo;
789 try {
790 synchronized (mInstallLock) {
791 synchronized (mPackagesLock) {
792 if (isUserLimitReachedLocked()) return null;
793 int userId = getNextAvailableIdLocked();
794 userInfo = new UserInfo(userId, name, null, flags);
795 File userPath = new File(mBaseUserPath, Integer.toString(userId));
796 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700797 long now = System.currentTimeMillis();
798 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700799 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700800 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700801 mUsers.put(userId, userInfo);
802 writeUserListLocked();
803 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700804 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700805 userInfo.partial = false;
806 writeUserLocked(userInfo);
807 updateUserIdsLocked();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700808 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700809 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700810 if (userInfo != null) {
811 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
812 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
813 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
814 android.Manifest.permission.MANAGE_USERS);
815 }
816 } finally {
817 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700818 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700819 return userInfo;
820 }
821
Amith Yamasani0b285492011-04-14 17:35:23 -0700822 /**
823 * Removes a user and all data directories created for that user. This method should be called
824 * after the user's processes have been terminated.
825 * @param id the user's id
826 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700827 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700828 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700829 final UserInfo user;
830 synchronized (mPackagesLock) {
831 user = mUsers.get(userHandle);
832 if (userHandle == 0 || user == null) {
833 return false;
834 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800835 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700836 // Set this to a partially created user, so that the user will be purged
837 // on next startup, in case the runtime stops now before stopping and
838 // removing the user completely.
839 user.partial = true;
840 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700841 }
Amith Yamasani16389312012-10-17 21:20:14 -0700842 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700843 int res;
844 try {
845 res = ActivityManagerNative.getDefault().stopUser(userHandle,
846 new IStopUserCallback.Stub() {
847 @Override
848 public void userStopped(int userId) {
849 finishRemoveUser(userId);
850 }
851 @Override
852 public void userStopAborted(int userId) {
853 }
854 });
855 } catch (RemoteException e) {
856 return false;
857 }
858
859 return res == ActivityManager.USER_OP_SUCCESS;
860 }
861
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700862 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700863 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700864 // Let other services shutdown any activity and clean up their state before completely
865 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700866 long ident = Binder.clearCallingIdentity();
867 try {
868 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
869 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700870 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
871 android.Manifest.permission.MANAGE_USERS,
872
873 new BroadcastReceiver() {
874 @Override
875 public void onReceive(Context context, Intent intent) {
876 if (DBG) {
877 Slog.i(LOG_TAG,
878 "USER_REMOVED broadcast sent, cleaning up user data "
879 + userHandle);
880 }
881 new Thread() {
882 public void run() {
883 synchronized (mInstallLock) {
884 synchronized (mPackagesLock) {
885 removeUserStateLocked(userHandle);
886 }
887 }
888 }
889 }.start();
890 }
891 },
892
893 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700894 } finally {
895 Binder.restoreCallingIdentity(ident);
896 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700897 }
898
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800899 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700900 // Cleanup package manager settings
901 mPm.cleanUpUserLILPw(userHandle);
902
903 // Remove this user from the list
904 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800905
906 // Have user ID linger for several seconds to let external storage VFS
907 // cache entries expire. This must be greater than the 'entry_valid'
908 // timeout used by the FUSE daemon.
909 mHandler.postDelayed(new Runnable() {
910 @Override
911 public void run() {
912 synchronized (mPackagesLock) {
913 mRemovingUserIds.delete(userHandle);
914 }
915 }
916 }, MINUTE_IN_MILLIS);
917
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700918 // Remove user file
919 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
920 userFile.delete();
921 // Update the user list
922 writeUserListLocked();
923 updateUserIdsLocked();
924 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
925 }
926
Amith Yamasani61f57372012-08-31 12:12:28 -0700927 private void removeDirectoryRecursive(File parent) {
928 if (parent.isDirectory()) {
929 String[] files = parent.list();
930 for (String filename : files) {
931 File child = new File(parent, filename);
932 removeDirectoryRecursive(child);
933 }
934 }
935 parent.delete();
936 }
937
Amith Yamasani2a003292012-08-14 18:25:45 -0700938 @Override
939 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700940 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700941 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -0700942 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -0700943 }
944 }
945
946 @Override
947 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700948 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -0700950 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -0700951 }
952 // Not found
953 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -0700954 }
955 }
956
Amith Yamasani0b285492011-04-14 17:35:23 -0700957 /**
958 * Caches the list of user ids in an array, adjusting the array size when necessary.
959 */
Amith Yamasani13593602012-03-22 16:16:17 -0700960 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700961 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700962 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700963 if (!mUsers.valueAt(i).partial) {
964 num++;
965 }
966 }
Amith Yamasani16389312012-10-17 21:20:14 -0700967 final int[] newUsers = new int[num];
968 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700969 for (int i = 0; i < mUsers.size(); i++) {
970 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -0700971 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700972 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700973 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700974 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -0700975 }
976
977 /**
Amith Yamasani920ace02012-09-20 22:15:37 -0700978 * Make a note of the last started time of a user.
979 * @param userId the user that was just foregrounded
980 */
981 public void userForeground(int userId) {
982 synchronized (mPackagesLock) {
983 UserInfo user = mUsers.get(userId);
984 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700985 if (user == null || user.partial) {
986 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
987 return;
988 }
989 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700990 user.lastLoggedInTime = now;
991 writeUserLocked(user);
992 }
993 }
994 }
995
996 /**
Amith Yamasani0b285492011-04-14 17:35:23 -0700997 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -0700998 * TODO: May not be a good idea to recycle ids, in case it results in confusion
999 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001000 * @return
1001 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001002 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001003 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001004 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001005 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001006 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001007 break;
1008 }
1009 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001010 }
Amith Yamasani195263742012-08-21 15:40:12 -07001011 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001012 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001013 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001014
1015 @Override
1016 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1017 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1018 != PackageManager.PERMISSION_GRANTED) {
1019 pw.println("Permission Denial: can't dump UserManager from from pid="
1020 + Binder.getCallingPid()
1021 + ", uid=" + Binder.getCallingUid()
1022 + " without permission "
1023 + android.Manifest.permission.DUMP);
1024 return;
1025 }
1026
1027 long now = System.currentTimeMillis();
1028 StringBuilder sb = new StringBuilder();
1029 synchronized (mPackagesLock) {
1030 pw.println("Users:");
1031 for (int i = 0; i < mUsers.size(); i++) {
1032 UserInfo user = mUsers.valueAt(i);
1033 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001034 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001035 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001036 if (user.partial) pw.print(" <partial>");
1037 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001038 pw.print(" Created: ");
1039 if (user.creationTime == 0) {
1040 pw.println("<unknown>");
1041 } else {
1042 sb.setLength(0);
1043 TimeUtils.formatDuration(now - user.creationTime, sb);
1044 sb.append(" ago");
1045 pw.println(sb);
1046 }
1047 pw.print(" Last logged in: ");
1048 if (user.lastLoggedInTime == 0) {
1049 pw.println("<unknown>");
1050 } else {
1051 sb.setLength(0);
1052 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1053 sb.append(" ago");
1054 pw.println(sb);
1055 }
1056 }
1057 }
1058 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001059}