blob: 18ccf750cd7a5229b2d01624e3693f89cb565537 [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;
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500550
551 Bundle restrictions = new Bundle();
552 initRestrictionsToDefaults(restrictions);
553 mUserRestrictions.append(0, restrictions);
554
Amith Yamasani13593602012-03-22 16:16:17 -0700555 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700556
Amith Yamasani13593602012-03-22 16:16:17 -0700557 writeUserListLocked();
558 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700559 }
560
561 /*
562 * Writes the user file in this format:
563 *
564 * <user flags="20039023" id="0">
565 * <name>Primary</name>
566 * </user>
567 */
Amith Yamasani13593602012-03-22 16:16:17 -0700568 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700569 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700570 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700572 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700573 final BufferedOutputStream bos = new BufferedOutputStream(fos);
574
575 // XmlSerializer serializer = XmlUtils.serializerInstance();
576 final XmlSerializer serializer = new FastXmlSerializer();
577 serializer.setOutput(bos, "utf-8");
578 serializer.startDocument(null, true);
579 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
580
581 serializer.startTag(null, TAG_USER);
582 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700583 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700584 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700585 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
586 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
587 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700588 if (userInfo.iconPath != null) {
589 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
590 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700591 if (userInfo.partial) {
592 serializer.attribute(null, ATTR_PARTIAL, "true");
593 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700594
595 serializer.startTag(null, TAG_NAME);
596 serializer.text(userInfo.name);
597 serializer.endTag(null, TAG_NAME);
598
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800599 Bundle restrictions = mUserRestrictions.get(userInfo.id);
600 if (restrictions != null) {
601 serializer.startTag(null, TAG_RESTRICTIONS);
602 writeBoolean(serializer, restrictions, UserManager.ALLOW_CONFIG_WIFI);
603 writeBoolean(serializer, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
604 writeBoolean(serializer, restrictions, UserManager.ALLOW_INSTALL_APPS);
605 writeBoolean(serializer, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
606 serializer.endTag(null, TAG_RESTRICTIONS);
607 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700608 serializer.endTag(null, TAG_USER);
609
610 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700611 userFile.finishWrite(fos);
612 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700613 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700614 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700615 }
616 }
617
618 /*
619 * Writes the user list file in this format:
620 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700621 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700622 * <user id="0"></user>
623 * <user id="2"></user>
624 * </users>
625 */
Amith Yamasani13593602012-03-22 16:16:17 -0700626 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700627 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700628 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700629 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700630 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 final BufferedOutputStream bos = new BufferedOutputStream(fos);
632
633 // XmlSerializer serializer = XmlUtils.serializerInstance();
634 final XmlSerializer serializer = new FastXmlSerializer();
635 serializer.setOutput(bos, "utf-8");
636 serializer.startDocument(null, true);
637 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
638
639 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700640 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700641 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700642
643 for (int i = 0; i < mUsers.size(); i++) {
644 UserInfo user = mUsers.valueAt(i);
645 serializer.startTag(null, TAG_USER);
646 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
647 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700648 }
649
650 serializer.endTag(null, TAG_USERS);
651
652 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700653 userListFile.finishWrite(fos);
654 } catch (Exception e) {
655 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700656 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700657 }
658 }
659
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800660 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700661 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700662 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700663 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700664 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700665 long creationTime = 0L;
666 long lastLoggedInTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800668 Bundle restrictions = new Bundle();
669 initRestrictionsToDefaults(restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700670
671 FileInputStream fis = null;
672 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700673 AtomicFile userFile =
674 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
675 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700676 XmlPullParser parser = Xml.newPullParser();
677 parser.setInput(fis, null);
678 int type;
679 while ((type = parser.next()) != XmlPullParser.START_TAG
680 && type != XmlPullParser.END_DOCUMENT) {
681 ;
682 }
683
684 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700685 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700686 return null;
687 }
688
689 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700690 int storedId = readIntAttribute(parser, ATTR_ID, -1);
691 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700692 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 return null;
694 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700695 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
696 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700697 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700698 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
699 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700700 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
701 if ("true".equals(valueString)) {
702 partial = true;
703 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700704
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800705 int outerDepth = parser.getDepth();
706 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
707 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
708 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
709 continue;
710 }
711 String tag = parser.getName();
712 if (TAG_NAME.equals(tag)) {
713 type = parser.next();
714 if (type == XmlPullParser.TEXT) {
715 name = parser.getText();
716 }
717 } else if (TAG_RESTRICTIONS.equals(tag)) {
718 readBoolean(parser, restrictions, UserManager.ALLOW_CONFIG_WIFI);
719 readBoolean(parser, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
720 readBoolean(parser, restrictions, UserManager.ALLOW_INSTALL_APPS);
721 readBoolean(parser, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700722 }
723 }
724 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700725
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700726 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700727 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700728 userInfo.creationTime = creationTime;
729 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700730 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800731 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700732 return userInfo;
733
734 } catch (IOException ioe) {
735 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800736 } finally {
737 if (fis != null) {
738 try {
739 fis.close();
740 } catch (IOException e) {
741 }
742 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700743 }
744 return null;
745 }
746
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800747 private void readBoolean(XmlPullParser parser, Bundle restrictions,
748 String restrictionKey) {
749 String value = parser.getAttributeValue(null, restrictionKey);
750 restrictions.putBoolean(restrictionKey, value == null ? true : Boolean.parseBoolean(value));
751 }
752
753 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
754 throws IOException {
755 if (restrictions.containsKey(restrictionKey)) {
756 xml.attribute(null, restrictionKey,
757 Boolean.toString(restrictions.getBoolean(restrictionKey)));
758 }
759 }
760
761 private void initRestrictionsToDefaults(Bundle restrictions) {
762 restrictions.putBoolean(UserManager.ALLOW_CONFIG_WIFI, true);
763 restrictions.putBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS, true);
764 restrictions.putBoolean(UserManager.ALLOW_INSTALL_APPS, true);
765 restrictions.putBoolean(UserManager.ALLOW_UNINSTALL_APPS, true);
766 }
767
Amith Yamasani920ace02012-09-20 22:15:37 -0700768 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
769 String valueString = parser.getAttributeValue(null, attr);
770 if (valueString == null) return defaultValue;
771 try {
772 return Integer.parseInt(valueString);
773 } catch (NumberFormatException nfe) {
774 return defaultValue;
775 }
776 }
777
778 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
779 String valueString = parser.getAttributeValue(null, attr);
780 if (valueString == null) return defaultValue;
781 try {
782 return Long.parseLong(valueString);
783 } catch (NumberFormatException nfe) {
784 return defaultValue;
785 }
786 }
787
Amith Yamasani258848d2012-08-10 17:06:33 -0700788 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700789 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700790 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700791
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700792 final long ident = Binder.clearCallingIdentity();
793 final UserInfo userInfo;
794 try {
795 synchronized (mInstallLock) {
796 synchronized (mPackagesLock) {
797 if (isUserLimitReachedLocked()) return null;
798 int userId = getNextAvailableIdLocked();
799 userInfo = new UserInfo(userId, name, null, flags);
800 File userPath = new File(mBaseUserPath, Integer.toString(userId));
801 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700802 long now = System.currentTimeMillis();
803 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700804 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700805 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700806 mUsers.put(userId, userInfo);
807 writeUserListLocked();
808 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700809 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700810 userInfo.partial = false;
811 writeUserLocked(userInfo);
812 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500813 Bundle restrictions = new Bundle();
814 initRestrictionsToDefaults(restrictions);
815 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700816 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700817 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700818 if (userInfo != null) {
819 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
820 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
821 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
822 android.Manifest.permission.MANAGE_USERS);
823 }
824 } finally {
825 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700826 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700827 return userInfo;
828 }
829
Amith Yamasani0b285492011-04-14 17:35:23 -0700830 /**
831 * Removes a user and all data directories created for that user. This method should be called
832 * after the user's processes have been terminated.
833 * @param id the user's id
834 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700835 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700836 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700837 final UserInfo user;
838 synchronized (mPackagesLock) {
839 user = mUsers.get(userHandle);
840 if (userHandle == 0 || user == null) {
841 return false;
842 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800843 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700844 // Set this to a partially created user, so that the user will be purged
845 // on next startup, in case the runtime stops now before stopping and
846 // removing the user completely.
847 user.partial = true;
848 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700849 }
Amith Yamasani16389312012-10-17 21:20:14 -0700850 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700851 int res;
852 try {
853 res = ActivityManagerNative.getDefault().stopUser(userHandle,
854 new IStopUserCallback.Stub() {
855 @Override
856 public void userStopped(int userId) {
857 finishRemoveUser(userId);
858 }
859 @Override
860 public void userStopAborted(int userId) {
861 }
862 });
863 } catch (RemoteException e) {
864 return false;
865 }
866
867 return res == ActivityManager.USER_OP_SUCCESS;
868 }
869
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700870 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700871 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700872 // Let other services shutdown any activity and clean up their state before completely
873 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700874 long ident = Binder.clearCallingIdentity();
875 try {
876 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
877 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700878 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
879 android.Manifest.permission.MANAGE_USERS,
880
881 new BroadcastReceiver() {
882 @Override
883 public void onReceive(Context context, Intent intent) {
884 if (DBG) {
885 Slog.i(LOG_TAG,
886 "USER_REMOVED broadcast sent, cleaning up user data "
887 + userHandle);
888 }
889 new Thread() {
890 public void run() {
891 synchronized (mInstallLock) {
892 synchronized (mPackagesLock) {
893 removeUserStateLocked(userHandle);
894 }
895 }
896 }
897 }.start();
898 }
899 },
900
901 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700902 } finally {
903 Binder.restoreCallingIdentity(ident);
904 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700905 }
906
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800907 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700908 // Cleanup package manager settings
909 mPm.cleanUpUserLILPw(userHandle);
910
911 // Remove this user from the list
912 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800913
914 // Have user ID linger for several seconds to let external storage VFS
915 // cache entries expire. This must be greater than the 'entry_valid'
916 // timeout used by the FUSE daemon.
917 mHandler.postDelayed(new Runnable() {
918 @Override
919 public void run() {
920 synchronized (mPackagesLock) {
921 mRemovingUserIds.delete(userHandle);
922 }
923 }
924 }, MINUTE_IN_MILLIS);
925
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700926 // Remove user file
927 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
928 userFile.delete();
929 // Update the user list
930 writeUserListLocked();
931 updateUserIdsLocked();
932 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
933 }
934
Amith Yamasani61f57372012-08-31 12:12:28 -0700935 private void removeDirectoryRecursive(File parent) {
936 if (parent.isDirectory()) {
937 String[] files = parent.list();
938 for (String filename : files) {
939 File child = new File(parent, filename);
940 removeDirectoryRecursive(child);
941 }
942 }
943 parent.delete();
944 }
945
Amith Yamasani2a003292012-08-14 18:25:45 -0700946 @Override
947 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700948 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700949 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -0700950 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -0700951 }
952 }
953
954 @Override
955 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700956 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700957 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -0700958 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -0700959 }
960 // Not found
961 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -0700962 }
963 }
964
Amith Yamasani0b285492011-04-14 17:35:23 -0700965 /**
966 * Caches the list of user ids in an array, adjusting the array size when necessary.
967 */
Amith Yamasani13593602012-03-22 16:16:17 -0700968 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700969 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700970 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700971 if (!mUsers.valueAt(i).partial) {
972 num++;
973 }
974 }
Amith Yamasani16389312012-10-17 21:20:14 -0700975 final int[] newUsers = new int[num];
976 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700977 for (int i = 0; i < mUsers.size(); i++) {
978 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -0700979 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700980 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700981 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700982 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -0700983 }
984
985 /**
Amith Yamasani920ace02012-09-20 22:15:37 -0700986 * Make a note of the last started time of a user.
987 * @param userId the user that was just foregrounded
988 */
989 public void userForeground(int userId) {
990 synchronized (mPackagesLock) {
991 UserInfo user = mUsers.get(userId);
992 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700993 if (user == null || user.partial) {
994 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
995 return;
996 }
997 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700998 user.lastLoggedInTime = now;
999 writeUserLocked(user);
1000 }
1001 }
1002 }
1003
1004 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001005 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001006 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1007 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001008 * @return
1009 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001010 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001011 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001012 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001013 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001014 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001015 break;
1016 }
1017 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001018 }
Amith Yamasani195263742012-08-21 15:40:12 -07001019 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001020 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001021 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001022
1023 @Override
1024 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1025 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1026 != PackageManager.PERMISSION_GRANTED) {
1027 pw.println("Permission Denial: can't dump UserManager from from pid="
1028 + Binder.getCallingPid()
1029 + ", uid=" + Binder.getCallingUid()
1030 + " without permission "
1031 + android.Manifest.permission.DUMP);
1032 return;
1033 }
1034
1035 long now = System.currentTimeMillis();
1036 StringBuilder sb = new StringBuilder();
1037 synchronized (mPackagesLock) {
1038 pw.println("Users:");
1039 for (int i = 0; i < mUsers.size(); i++) {
1040 UserInfo user = mUsers.valueAt(i);
1041 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001042 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001043 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001044 if (user.partial) pw.print(" <partial>");
1045 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001046 pw.print(" Created: ");
1047 if (user.creationTime == 0) {
1048 pw.println("<unknown>");
1049 } else {
1050 sb.setLength(0);
1051 TimeUtils.formatDuration(now - user.creationTime, sb);
1052 sb.append(" ago");
1053 pw.println(sb);
1054 }
1055 pw.print(" Last logged in: ");
1056 if (user.lastLoggedInTime == 0) {
1057 pw.println("<unknown>");
1058 } else {
1059 sb.setLength(0);
1060 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1061 sb.append(" ago");
1062 pw.println(sb);
1063 }
1064 }
1065 }
1066 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001067}