blob: fecc2dfdfd4e78969cf6bd5d707f4ef5d14c7d76 [file] [log] [blame]
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080019import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070020
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070021import android.app.Activity;
Amith Yamasani2a003292012-08-14 18:25:45 -070022import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070023import android.app.ActivityManagerNative;
24import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070025import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070026import android.content.Context;
27import android.content.Intent;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080028import android.content.RestrictionEntry;
29import android.content.SharedPreferences;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080031import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070032import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070035import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080036import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070037import android.os.Environment;
38import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080039import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070040import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070042import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070043import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070044import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070045import android.util.AtomicFile;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070046import android.util.Slog;
47import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080048import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070049import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070050import android.util.Xml;
51
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080052import com.android.internal.util.ArrayUtils;
53import com.android.internal.util.FastXmlSerializer;
54
55import org.xmlpull.v1.XmlPullParser;
56import org.xmlpull.v1.XmlPullParserException;
57import org.xmlpull.v1.XmlSerializer;
58
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import java.io.BufferedOutputStream;
60import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070061import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070062import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070063import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileOutputStream;
65import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import java.io.PrintWriter;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.util.ArrayList;
68import java.util.List;
69
Amith Yamasani258848d2012-08-10 17:06:33 -070070public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070071
Amith Yamasani2a003292012-08-14 18:25:45 -070072 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070073
Amith Yamasani16389312012-10-17 21:20:14 -070074 private static final boolean DBG = false;
75
Amith Yamasani4b2e9342011-03-31 12:38:53 -070076 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070079 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070080 private static final String ATTR_CREATION_TIME = "created";
81 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070082 private static final String ATTR_SERIAL_NO = "serialNumber";
83 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070084 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070085 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070086 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080088 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080089 private static final String TAG_ENTRY = "entry";
90 private static final String TAG_VALUE = "value";
91 private static final String ATTR_KEY = "key";
92 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070093
Amith Yamasani0b285492011-04-14 17:35:23 -070094 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070096 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070097
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080098 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
99
Amith Yamasani634cf312012-10-04 17:34:21 -0700100 private static final int MIN_USER_ID = 10;
101
Amith Yamasanibc9625052012-11-15 14:39:18 -0800102 private static final int USER_VERSION = 2;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700103
Amith Yamasani920ace02012-09-20 22:15:37 -0700104 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
105
Dianne Hackborn4428e172012-08-24 17:43:05 -0700106 private final Context mContext;
107 private final PackageManagerService mPm;
108 private final Object mInstallLock;
109 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700110
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800111 private final Handler mHandler;
112
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700113 private final File mUsersDir;
114 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700115 private final File mBaseUserPath;
116
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800117 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800118 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800119
120 /**
121 * Set of user IDs being actively removed. Removed IDs linger in this set
122 * for several seconds to work around a VFS caching issue.
123 */
124 // @GuardedBy("mPackagesLock")
125 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700126
Amith Yamasani0b285492011-04-14 17:35:23 -0700127 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700128 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700129 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700130 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700131
Amith Yamasani258848d2012-08-10 17:06:33 -0700132 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700133
Dianne Hackborn4428e172012-08-24 17:43:05 -0700134 public static UserManagerService getInstance() {
135 synchronized (UserManagerService.class) {
136 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700137 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700138 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700139
140 /**
141 * Available for testing purposes.
142 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700143 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700144 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700145 }
146
Dianne Hackborn4428e172012-08-24 17:43:05 -0700147 /**
148 * Called by package manager to create the service. This is closely
149 * associated with the package manager, and the given lock is the
150 * package manager's own lock.
151 */
152 UserManagerService(Context context, PackageManagerService pm,
153 Object installLock, Object packagesLock) {
154 this(context, pm, installLock, packagesLock,
155 Environment.getDataDirectory(),
156 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700157 }
158
Dianne Hackborn4428e172012-08-24 17:43:05 -0700159 /**
160 * Available for testing purposes.
161 */
162 private UserManagerService(Context context, PackageManagerService pm,
163 Object installLock, Object packagesLock,
164 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700165 mContext = context;
166 mPm = pm;
167 mInstallLock = installLock;
168 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800169 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700170 synchronized (mInstallLock) {
171 synchronized (mPackagesLock) {
172 mUsersDir = new File(dataDir, USER_INFO_DIR);
173 mUsersDir.mkdirs();
174 // Make zeroth user directory, for services to migrate their files to that location
175 File userZeroDir = new File(mUsersDir, "0");
176 userZeroDir.mkdirs();
177 mBaseUserPath = baseUserPath;
178 FileUtils.setPermissions(mUsersDir.toString(),
179 FileUtils.S_IRWXU|FileUtils.S_IRWXG
180 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
181 -1, -1);
182 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
183 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700184 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700185 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
186 for (int i = 0; i < mUsers.size(); i++) {
187 UserInfo ui = mUsers.valueAt(i);
188 if (ui.partial && i != 0) {
189 partials.add(ui);
190 }
191 }
192 for (int i = 0; i < partials.size(); i++) {
193 UserInfo ui = partials.get(i);
194 Slog.w(LOG_TAG, "Removing partially created user #" + i
195 + " (name=" + ui.name + ")");
196 removeUserStateLocked(ui.id);
197 }
198 sInstance = this;
199 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700200 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700201 }
202
203 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700204 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700205 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700206 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700207 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
208 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700209 UserInfo ui = mUsers.valueAt(i);
210 if (ui.partial) {
211 continue;
212 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800213 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700214 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700215 }
Amith Yamasani13593602012-03-22 16:16:17 -0700216 }
217 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700218 }
Amith Yamasani13593602012-03-22 16:16:17 -0700219 }
220
Amith Yamasani258848d2012-08-10 17:06:33 -0700221 @Override
222 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700223 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700224 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700225 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700226 }
227 }
228
Amith Yamasani71e6c692013-03-24 17:39:28 -0700229 @Override
230 public boolean isRestricted() {
231 synchronized (mPackagesLock) {
232 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
233 }
234 }
235
Amith Yamasani195263742012-08-21 15:40:12 -0700236 /*
237 * Should be locked on mUsers before calling this.
238 */
239 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700240 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700241 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800242 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700243 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
244 return null;
245 }
246 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700247 }
248
Amith Yamasani13593602012-03-22 16:16:17 -0700249 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700250 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700251 return ArrayUtils.contains(mUserIds, userId);
252 }
253 }
254
Amith Yamasani258848d2012-08-10 17:06:33 -0700255 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700256 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700257 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700258 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700259 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700260 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 if (info == null || info.partial) {
262 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
263 return;
264 }
Amith Yamasani13593602012-03-22 16:16:17 -0700265 if (name != null && !name.equals(info.name)) {
266 info.name = name;
267 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700268 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700269 }
270 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700271 if (changed) {
272 sendUserInfoChangedBroadcast(userId);
273 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700274 }
275
Amith Yamasani258848d2012-08-10 17:06:33 -0700276 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700277 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700278 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700279 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700280 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 if (info == null || info.partial) {
282 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
283 return;
284 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700285 writeBitmapLocked(info, bitmap);
286 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700287 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700288 sendUserInfoChangedBroadcast(userId);
289 }
290
291 private void sendUserInfoChangedBroadcast(int userId) {
292 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
293 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
294 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
295 mContext.sendBroadcastAsUser(changedIntent, new UserHandle(userId));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700296 }
297
Amith Yamasani258848d2012-08-10 17:06:33 -0700298 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700299 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700300 checkManageUsersPermission("read users");
301 synchronized (mPackagesLock) {
302 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700303 if (info == null || info.partial) {
304 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
305 return null;
306 }
307 if (info.iconPath == null) {
308 return null;
309 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700310 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700311 }
312 }
313
314 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700315 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700316 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700318 if (mGuestEnabled != enable) {
319 mGuestEnabled = enable;
320 // Erase any guest user that currently exists
321 for (int i = 0; i < mUsers.size(); i++) {
322 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700323 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700324 if (!enable) {
325 removeUser(user.id);
326 }
327 return;
328 }
329 }
330 // No guest was found
331 if (enable) {
332 createUser("Guest", UserInfo.FLAG_GUEST);
333 }
334 }
335 }
336 }
337
338 @Override
339 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700340 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700341 return mGuestEnabled;
342 }
343 }
344
345 @Override
346 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700347 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700348 // TODO:
349 }
350
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700351 public void makeInitialized(int userId) {
352 checkManageUsersPermission("makeInitialized");
353 synchronized (mPackagesLock) {
354 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700355 if (info == null || info.partial) {
356 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
357 }
358 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700359 info.flags |= UserInfo.FLAG_INITIALIZED;
360 writeUserLocked(info);
361 }
362 }
363 }
364
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800365 @Override
366 public Bundle getUserRestrictions(int userId) {
367 // checkManageUsersPermission("getUserRestrictions");
368
369 synchronized (mPackagesLock) {
370 Bundle restrictions = mUserRestrictions.get(userId);
371 return restrictions != null ? restrictions : Bundle.EMPTY;
372 }
373 }
374
375 @Override
376 public void setUserRestrictions(Bundle restrictions, int userId) {
377 checkManageUsersPermission("setUserRestrictions");
378
379 synchronized (mPackagesLock) {
380 mUserRestrictions.get(userId).putAll(restrictions);
381 writeUserLocked(mUsers.get(userId));
382 }
383 }
384
Amith Yamasani258848d2012-08-10 17:06:33 -0700385 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700386 * Check if we've hit the limit of how many users can be created.
387 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700388 private boolean isUserLimitReachedLocked() {
389 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700390 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700391 }
392
393 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700394 * Enforces that only the system UID or root's UID or apps that have the
395 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
396 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700397 *
398 * @param message used as message if SecurityException is thrown
399 * @throws SecurityException if the caller is not system or root
400 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700401 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700402 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700403 if (uid != Process.SYSTEM_UID && uid != 0
404 && ActivityManager.checkComponentPermission(
405 android.Manifest.permission.MANAGE_USERS,
406 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
407 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700408 }
409 }
410
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700411 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700412 try {
413 File dir = new File(mUsersDir, Integer.toString(info.id));
414 File file = new File(dir, USER_PHOTO_FILENAME);
415 if (!dir.exists()) {
416 dir.mkdir();
417 FileUtils.setPermissions(
418 dir.getPath(),
419 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
420 -1, -1);
421 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700422 FileOutputStream os;
423 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700424 info.iconPath = file.getAbsolutePath();
425 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700426 try {
427 os.close();
428 } catch (IOException ioe) {
429 // What the ... !
430 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700431 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700432 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700433 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700434 }
435
Amith Yamasani0b285492011-04-14 17:35:23 -0700436 /**
437 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
438 * cache it elsewhere.
439 * @return the array of user ids.
440 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700441 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700442 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700443 return mUserIds;
444 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700445 }
446
Dianne Hackborn4428e172012-08-24 17:43:05 -0700447 int[] getUserIdsLPr() {
448 return mUserIds;
449 }
450
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700451 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700452 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700453 readUserListLocked();
454 }
455 }
456
457 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700458 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700459 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700460 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700461 return;
462 }
463 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700464 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700465 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700466 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700467 XmlPullParser parser = Xml.newPullParser();
468 parser.setInput(fis, null);
469 int type;
470 while ((type = parser.next()) != XmlPullParser.START_TAG
471 && type != XmlPullParser.END_DOCUMENT) {
472 ;
473 }
474
475 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700476 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700477 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700478 return;
479 }
480
Amith Yamasani2a003292012-08-14 18:25:45 -0700481 mNextSerialNumber = -1;
482 if (parser.getName().equals(TAG_USERS)) {
483 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
484 if (lastSerialNumber != null) {
485 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
486 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700487 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
488 if (versionNumber != null) {
489 mUserVersion = Integer.parseInt(versionNumber);
490 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700491 }
492
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700493 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
494 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
495 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800496 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700497
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700498 if (user != null) {
499 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700500 if (user.isGuest()) {
501 mGuestEnabled = true;
502 }
503 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
504 mNextSerialNumber = user.id + 1;
505 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700506 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700507 }
508 }
Amith Yamasani13593602012-03-22 16:16:17 -0700509 updateUserIdsLocked();
Amith Yamasani6f34b412012-10-22 18:19:27 -0700510 upgradeIfNecessary();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700511 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700512 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700513 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700514 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800515 } finally {
516 if (fis != null) {
517 try {
518 fis.close();
519 } catch (IOException e) {
520 }
521 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700522 }
523 }
524
Amith Yamasani6f34b412012-10-22 18:19:27 -0700525 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800526 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700527 */
528 private void upgradeIfNecessary() {
529 int userVersion = mUserVersion;
530 if (userVersion < 1) {
531 // Assign a proper name for the owner, if not initialized correctly before
532 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
533 if ("Primary".equals(user.name)) {
534 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
535 writeUserLocked(user);
536 }
537 userVersion = 1;
538 }
539
Amith Yamasanibc9625052012-11-15 14:39:18 -0800540 if (userVersion < 2) {
541 // Owner should be marked as initialized
542 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
543 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
544 user.flags |= UserInfo.FLAG_INITIALIZED;
545 writeUserLocked(user);
546 }
547 userVersion = 2;
548 }
549
Amith Yamasani6f34b412012-10-22 18:19:27 -0700550 if (userVersion < USER_VERSION) {
551 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
552 + USER_VERSION);
553 } else {
554 mUserVersion = userVersion;
555 writeUserListLocked();
556 }
557 }
558
Amith Yamasani13593602012-03-22 16:16:17 -0700559 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700560 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800561 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700562 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700563 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700564 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700565 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800566
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500567 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800568 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
569
Amith Yamasani13593602012-03-22 16:16:17 -0700570 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571
Amith Yamasani13593602012-03-22 16:16:17 -0700572 writeUserListLocked();
573 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700574 }
575
576 /*
577 * Writes the user file in this format:
578 *
579 * <user flags="20039023" id="0">
580 * <name>Primary</name>
581 * </user>
582 */
Amith Yamasani13593602012-03-22 16:16:17 -0700583 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700584 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700585 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700586 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700587 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700588 final BufferedOutputStream bos = new BufferedOutputStream(fos);
589
590 // XmlSerializer serializer = XmlUtils.serializerInstance();
591 final XmlSerializer serializer = new FastXmlSerializer();
592 serializer.setOutput(bos, "utf-8");
593 serializer.startDocument(null, true);
594 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
595
596 serializer.startTag(null, TAG_USER);
597 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700598 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700599 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700600 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
601 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
602 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700603 if (userInfo.iconPath != null) {
604 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
605 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700606 if (userInfo.partial) {
607 serializer.attribute(null, ATTR_PARTIAL, "true");
608 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700609
610 serializer.startTag(null, TAG_NAME);
611 serializer.text(userInfo.name);
612 serializer.endTag(null, TAG_NAME);
613
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800614 Bundle restrictions = mUserRestrictions.get(userInfo.id);
615 if (restrictions != null) {
616 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700617 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
618 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
619 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
620 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
621 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800622 serializer.endTag(null, TAG_RESTRICTIONS);
623 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700624 serializer.endTag(null, TAG_USER);
625
626 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700627 userFile.finishWrite(fos);
628 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700629 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700630 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700631 }
632 }
633
634 /*
635 * Writes the user list file in this format:
636 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700637 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700638 * <user id="0"></user>
639 * <user id="2"></user>
640 * </users>
641 */
Amith Yamasani13593602012-03-22 16:16:17 -0700642 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700643 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700644 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700645 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700646 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700647 final BufferedOutputStream bos = new BufferedOutputStream(fos);
648
649 // XmlSerializer serializer = XmlUtils.serializerInstance();
650 final XmlSerializer serializer = new FastXmlSerializer();
651 serializer.setOutput(bos, "utf-8");
652 serializer.startDocument(null, true);
653 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
654
655 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700656 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700657 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700658
659 for (int i = 0; i < mUsers.size(); i++) {
660 UserInfo user = mUsers.valueAt(i);
661 serializer.startTag(null, TAG_USER);
662 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
663 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700664 }
665
666 serializer.endTag(null, TAG_USERS);
667
668 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700669 userListFile.finishWrite(fos);
670 } catch (Exception e) {
671 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700672 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700673 }
674 }
675
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800676 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700677 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700678 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700679 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700680 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700681 long creationTime = 0L;
682 long lastLoggedInTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700683 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800684 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700685
686 FileInputStream fis = null;
687 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700688 AtomicFile userFile =
689 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
690 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700691 XmlPullParser parser = Xml.newPullParser();
692 parser.setInput(fis, null);
693 int type;
694 while ((type = parser.next()) != XmlPullParser.START_TAG
695 && type != XmlPullParser.END_DOCUMENT) {
696 ;
697 }
698
699 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700700 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700701 return null;
702 }
703
704 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700705 int storedId = readIntAttribute(parser, ATTR_ID, -1);
706 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700707 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700708 return null;
709 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700710 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
711 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700712 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700713 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
714 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700715 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
716 if ("true".equals(valueString)) {
717 partial = true;
718 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700719
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800720 int outerDepth = parser.getDepth();
721 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
722 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
723 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
724 continue;
725 }
726 String tag = parser.getName();
727 if (TAG_NAME.equals(tag)) {
728 type = parser.next();
729 if (type == XmlPullParser.TEXT) {
730 name = parser.getText();
731 }
732 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700733 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
734 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
735 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
736 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
737 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700738 }
739 }
740 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700742 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700743 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700744 userInfo.creationTime = creationTime;
745 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700746 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800747 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700748 return userInfo;
749
750 } catch (IOException ioe) {
751 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800752 } finally {
753 if (fis != null) {
754 try {
755 fis.close();
756 } catch (IOException e) {
757 }
758 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700759 }
760 return null;
761 }
762
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800763 private void readBoolean(XmlPullParser parser, Bundle restrictions,
764 String restrictionKey) {
765 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700766 if (value != null) {
767 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
768 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800769 }
770
771 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
772 throws IOException {
773 if (restrictions.containsKey(restrictionKey)) {
774 xml.attribute(null, restrictionKey,
775 Boolean.toString(restrictions.getBoolean(restrictionKey)));
776 }
777 }
778
Amith Yamasani920ace02012-09-20 22:15:37 -0700779 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
780 String valueString = parser.getAttributeValue(null, attr);
781 if (valueString == null) return defaultValue;
782 try {
783 return Integer.parseInt(valueString);
784 } catch (NumberFormatException nfe) {
785 return defaultValue;
786 }
787 }
788
789 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
790 String valueString = parser.getAttributeValue(null, attr);
791 if (valueString == null) return defaultValue;
792 try {
793 return Long.parseLong(valueString);
794 } catch (NumberFormatException nfe) {
795 return defaultValue;
796 }
797 }
798
Amith Yamasani258848d2012-08-10 17:06:33 -0700799 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700800 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700801 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700802
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700803 final long ident = Binder.clearCallingIdentity();
804 final UserInfo userInfo;
805 try {
806 synchronized (mInstallLock) {
807 synchronized (mPackagesLock) {
808 if (isUserLimitReachedLocked()) return null;
809 int userId = getNextAvailableIdLocked();
810 userInfo = new UserInfo(userId, name, null, flags);
811 File userPath = new File(mBaseUserPath, Integer.toString(userId));
812 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700813 long now = System.currentTimeMillis();
814 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700815 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700816 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700817 mUsers.put(userId, userInfo);
818 writeUserListLocked();
819 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700820 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700821 userInfo.partial = false;
822 writeUserLocked(userInfo);
823 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500824 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500825 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700826 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700827 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700828 if (userInfo != null) {
829 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
830 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
831 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
832 android.Manifest.permission.MANAGE_USERS);
833 }
834 } finally {
835 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700836 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700837 return userInfo;
838 }
839
Amith Yamasani0b285492011-04-14 17:35:23 -0700840 /**
841 * Removes a user and all data directories created for that user. This method should be called
842 * after the user's processes have been terminated.
843 * @param id the user's id
844 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700845 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700846 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700847 final UserInfo user;
848 synchronized (mPackagesLock) {
849 user = mUsers.get(userHandle);
850 if (userHandle == 0 || user == null) {
851 return false;
852 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800853 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700854 // Set this to a partially created user, so that the user will be purged
855 // on next startup, in case the runtime stops now before stopping and
856 // removing the user completely.
857 user.partial = true;
858 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700859 }
Amith Yamasani16389312012-10-17 21:20:14 -0700860 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700861 int res;
862 try {
863 res = ActivityManagerNative.getDefault().stopUser(userHandle,
864 new IStopUserCallback.Stub() {
865 @Override
866 public void userStopped(int userId) {
867 finishRemoveUser(userId);
868 }
869 @Override
870 public void userStopAborted(int userId) {
871 }
872 });
873 } catch (RemoteException e) {
874 return false;
875 }
876
877 return res == ActivityManager.USER_OP_SUCCESS;
878 }
879
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700880 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700881 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700882 // Let other services shutdown any activity and clean up their state before completely
883 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700884 long ident = Binder.clearCallingIdentity();
885 try {
886 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
887 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700888 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
889 android.Manifest.permission.MANAGE_USERS,
890
891 new BroadcastReceiver() {
892 @Override
893 public void onReceive(Context context, Intent intent) {
894 if (DBG) {
895 Slog.i(LOG_TAG,
896 "USER_REMOVED broadcast sent, cleaning up user data "
897 + userHandle);
898 }
899 new Thread() {
900 public void run() {
901 synchronized (mInstallLock) {
902 synchronized (mPackagesLock) {
903 removeUserStateLocked(userHandle);
904 }
905 }
906 }
907 }.start();
908 }
909 },
910
911 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700912 } finally {
913 Binder.restoreCallingIdentity(ident);
914 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700915 }
916
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800917 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700918 // Cleanup package manager settings
919 mPm.cleanUpUserLILPw(userHandle);
920
921 // Remove this user from the list
922 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800923
924 // Have user ID linger for several seconds to let external storage VFS
925 // cache entries expire. This must be greater than the 'entry_valid'
926 // timeout used by the FUSE daemon.
927 mHandler.postDelayed(new Runnable() {
928 @Override
929 public void run() {
930 synchronized (mPackagesLock) {
931 mRemovingUserIds.delete(userHandle);
932 }
933 }
934 }, MINUTE_IN_MILLIS);
935
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700936 // Remove user file
937 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
938 userFile.delete();
939 // Update the user list
940 writeUserListLocked();
941 updateUserIdsLocked();
942 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
943 }
944
Amith Yamasani61f57372012-08-31 12:12:28 -0700945 private void removeDirectoryRecursive(File parent) {
946 if (parent.isDirectory()) {
947 String[] files = parent.list();
948 for (String filename : files) {
949 File child = new File(parent, filename);
950 removeDirectoryRecursive(child);
951 }
952 }
953 parent.delete();
954 }
955
Amith Yamasani2a003292012-08-14 18:25:45 -0700956 @Override
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800957 public List<RestrictionEntry> getApplicationRestrictions(String packageName, int userId) {
958 if (UserHandle.getCallingUserId() != userId
959 || Binder.getCallingUid() != getUidForPackage(packageName)) {
960 checkManageUsersPermission("Only system can get restrictions for other users/apps");
961 }
962 synchronized (mPackagesLock) {
963 // Read the restrictions from XML
964 return readApplicationRestrictionsLocked(packageName, userId);
965 }
966 }
967
968 @Override
969 public void setApplicationRestrictions(String packageName, List<RestrictionEntry> entries,
970 int userId) {
971 if (UserHandle.getCallingUserId() != userId
972 || Binder.getCallingUid() != getUidForPackage(packageName)) {
973 checkManageUsersPermission("Only system can set restrictions for other users/apps");
974 }
975 synchronized (mPackagesLock) {
976 // Write the restrictions to XML
977 writeApplicationRestrictionsLocked(packageName, entries, userId);
978 }
979 }
980
981 private int getUidForPackage(String packageName) {
982 try {
983 return mContext.getPackageManager().getApplicationInfo(packageName,
984 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
985 } catch (NameNotFoundException nnfe) {
986 return -1;
987 }
988 }
989
990 private List<RestrictionEntry> readApplicationRestrictionsLocked(String packageName,
991 int userId) {
992 final ArrayList<RestrictionEntry> entries = new ArrayList<RestrictionEntry>();
993 final ArrayList<String> values = new ArrayList<String>();
994
995 FileInputStream fis = null;
996 try {
997 AtomicFile restrictionsFile =
998 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
999 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1000 fis = restrictionsFile.openRead();
1001 XmlPullParser parser = Xml.newPullParser();
1002 parser.setInput(fis, null);
1003 int type;
1004 while ((type = parser.next()) != XmlPullParser.START_TAG
1005 && type != XmlPullParser.END_DOCUMENT) {
1006 ;
1007 }
1008
1009 if (type != XmlPullParser.START_TAG) {
1010 Slog.e(LOG_TAG, "Unable to read restrictions file "
1011 + restrictionsFile.getBaseFile());
1012 return entries;
1013 }
1014
1015 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1016 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1017 String key = parser.getAttributeValue(null, ATTR_KEY);
1018 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1019 if (multiple != null) {
1020 int count = Integer.parseInt(multiple);
1021 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1022 if (type == XmlPullParser.START_TAG
1023 && parser.getName().equals(TAG_VALUE)) {
1024 values.add(parser.nextText().trim());
1025 count--;
1026 }
1027 }
1028 String [] valueStrings = new String[values.size()];
1029 values.toArray(valueStrings);
1030 Slog.d(LOG_TAG, "Got RestrictionEntry " + key + "," + valueStrings);
1031 RestrictionEntry entry = new RestrictionEntry(key, valueStrings);
1032 entries.add(entry);
1033 } else {
1034 String value = parser.nextText().trim();
1035 Slog.d(LOG_TAG, "Got RestrictionEntry " + key + "," + value);
1036 RestrictionEntry entry = new RestrictionEntry(key, value);
1037 entries.add(entry);
1038 }
1039 }
1040 }
1041
1042 } catch (IOException ioe) {
1043 } catch (XmlPullParserException pe) {
1044 } finally {
1045 if (fis != null) {
1046 try {
1047 fis.close();
1048 } catch (IOException e) {
1049 }
1050 }
1051 }
1052 return entries;
1053 }
1054
1055 private void writeApplicationRestrictionsLocked(String packageName,
1056 List<RestrictionEntry> entries, int userId) {
1057 FileOutputStream fos = null;
1058 AtomicFile restrictionsFile = new AtomicFile(
1059 new File(Environment.getUserSystemDirectory(userId),
1060 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1061 try {
1062 fos = restrictionsFile.startWrite();
1063 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1064
1065 // XmlSerializer serializer = XmlUtils.serializerInstance();
1066 final XmlSerializer serializer = new FastXmlSerializer();
1067 serializer.setOutput(bos, "utf-8");
1068 serializer.startDocument(null, true);
1069 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1070
1071 serializer.startTag(null, TAG_RESTRICTIONS);
1072
1073 for (RestrictionEntry entry : entries) {
1074 serializer.startTag(null, TAG_ENTRY);
1075 serializer.attribute(null, ATTR_KEY, entry.key);
1076 if (entry.getStringValue() != null || entry.getMultipleValues() == null) {
1077 String value = entry.getStringValue();
1078 serializer.text(value != null ? value : "");
1079 } else {
1080 String[] values = entry.getMultipleValues();
1081 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1082 for (String value : values) {
1083 serializer.startTag(null, TAG_VALUE);
1084 serializer.text(value != null ? value : "");
1085 serializer.endTag(null, TAG_VALUE);
1086 }
1087 }
1088 serializer.endTag(null, TAG_ENTRY);
1089 }
1090
1091 serializer.endTag(null, TAG_RESTRICTIONS);
1092
1093 serializer.endDocument();
1094 restrictionsFile.finishWrite(fos);
1095 } catch (Exception e) {
1096 restrictionsFile.failWrite(fos);
1097 Slog.e(LOG_TAG, "Error writing application restrictions list");
1098 }
1099 }
1100
1101 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001102 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001103 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001104 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001105 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001106 }
1107 }
1108
1109 @Override
1110 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001111 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001112 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001113 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001114 }
1115 // Not found
1116 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001117 }
1118 }
1119
Amith Yamasani0b285492011-04-14 17:35:23 -07001120 /**
1121 * Caches the list of user ids in an array, adjusting the array size when necessary.
1122 */
Amith Yamasani13593602012-03-22 16:16:17 -07001123 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001124 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001125 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001126 if (!mUsers.valueAt(i).partial) {
1127 num++;
1128 }
1129 }
Amith Yamasani16389312012-10-17 21:20:14 -07001130 final int[] newUsers = new int[num];
1131 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001132 for (int i = 0; i < mUsers.size(); i++) {
1133 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001134 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001135 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001136 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001137 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001138 }
1139
1140 /**
Amith Yamasani920ace02012-09-20 22:15:37 -07001141 * Make a note of the last started time of a user.
1142 * @param userId the user that was just foregrounded
1143 */
1144 public void userForeground(int userId) {
1145 synchronized (mPackagesLock) {
1146 UserInfo user = mUsers.get(userId);
1147 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001148 if (user == null || user.partial) {
1149 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1150 return;
1151 }
1152 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001153 user.lastLoggedInTime = now;
1154 writeUserLocked(user);
1155 }
1156 }
1157 }
1158
1159 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001160 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001161 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1162 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001163 * @return
1164 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001165 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001166 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001167 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001168 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001169 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001170 break;
1171 }
1172 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001173 }
Amith Yamasani195263742012-08-21 15:40:12 -07001174 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001175 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001176 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001177
1178 @Override
1179 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1180 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1181 != PackageManager.PERMISSION_GRANTED) {
1182 pw.println("Permission Denial: can't dump UserManager from from pid="
1183 + Binder.getCallingPid()
1184 + ", uid=" + Binder.getCallingUid()
1185 + " without permission "
1186 + android.Manifest.permission.DUMP);
1187 return;
1188 }
1189
1190 long now = System.currentTimeMillis();
1191 StringBuilder sb = new StringBuilder();
1192 synchronized (mPackagesLock) {
1193 pw.println("Users:");
1194 for (int i = 0; i < mUsers.size(); i++) {
1195 UserInfo user = mUsers.valueAt(i);
1196 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001197 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001198 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001199 if (user.partial) pw.print(" <partial>");
1200 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001201 pw.print(" Created: ");
1202 if (user.creationTime == 0) {
1203 pw.println("<unknown>");
1204 } else {
1205 sb.setLength(0);
1206 TimeUtils.formatDuration(now - user.creationTime, sb);
1207 sb.append(" ago");
1208 pw.println(sb);
1209 }
1210 pw.print(" Last logged in: ");
1211 if (user.lastLoggedInTime == 0) {
1212 pw.println("<unknown>");
1213 } else {
1214 sb.setLength(0);
1215 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1216 sb.append(" ago");
1217 pw.println(sb);
1218 }
1219 }
1220 }
1221 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001222}