blob: 636b0e59913a7754efe4d839b87d821f362690f5 [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 Yamasani195263742012-08-21 15:40:12 -0700229 /*
230 * Should be locked on mUsers before calling this.
231 */
232 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700233 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700234 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800235 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700236 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
237 return null;
238 }
239 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700240 }
241
Amith Yamasani13593602012-03-22 16:16:17 -0700242 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700243 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700244 return ArrayUtils.contains(mUserIds, userId);
245 }
246 }
247
Amith Yamasani258848d2012-08-10 17:06:33 -0700248 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700249 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700250 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700251 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700252 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700253 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700254 if (info == null || info.partial) {
255 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
256 return;
257 }
Amith Yamasani13593602012-03-22 16:16:17 -0700258 if (name != null && !name.equals(info.name)) {
259 info.name = name;
260 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700261 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700262 }
263 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700264 if (changed) {
265 sendUserInfoChangedBroadcast(userId);
266 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700267 }
268
Amith Yamasani258848d2012-08-10 17:06:33 -0700269 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700270 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700271 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700272 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700273 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700274 if (info == null || info.partial) {
275 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
276 return;
277 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700278 writeBitmapLocked(info, bitmap);
279 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700280 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700281 sendUserInfoChangedBroadcast(userId);
282 }
283
284 private void sendUserInfoChangedBroadcast(int userId) {
285 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
286 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
287 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
288 mContext.sendBroadcastAsUser(changedIntent, new UserHandle(userId));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700289 }
290
Amith Yamasani258848d2012-08-10 17:06:33 -0700291 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700292 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700293 checkManageUsersPermission("read users");
294 synchronized (mPackagesLock) {
295 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 if (info == null || info.partial) {
297 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
298 return null;
299 }
300 if (info.iconPath == null) {
301 return null;
302 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700303 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700304 }
305 }
306
307 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700308 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700309 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700310 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700311 if (mGuestEnabled != enable) {
312 mGuestEnabled = enable;
313 // Erase any guest user that currently exists
314 for (int i = 0; i < mUsers.size(); i++) {
315 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700316 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700317 if (!enable) {
318 removeUser(user.id);
319 }
320 return;
321 }
322 }
323 // No guest was found
324 if (enable) {
325 createUser("Guest", UserInfo.FLAG_GUEST);
326 }
327 }
328 }
329 }
330
331 @Override
332 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700333 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700334 return mGuestEnabled;
335 }
336 }
337
338 @Override
339 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700340 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700341 // TODO:
342 }
343
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700344 public void makeInitialized(int userId) {
345 checkManageUsersPermission("makeInitialized");
346 synchronized (mPackagesLock) {
347 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700348 if (info == null || info.partial) {
349 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
350 }
351 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700352 info.flags |= UserInfo.FLAG_INITIALIZED;
353 writeUserLocked(info);
354 }
355 }
356 }
357
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800358 @Override
359 public Bundle getUserRestrictions(int userId) {
360 // checkManageUsersPermission("getUserRestrictions");
361
362 synchronized (mPackagesLock) {
363 Bundle restrictions = mUserRestrictions.get(userId);
364 return restrictions != null ? restrictions : Bundle.EMPTY;
365 }
366 }
367
368 @Override
369 public void setUserRestrictions(Bundle restrictions, int userId) {
370 checkManageUsersPermission("setUserRestrictions");
371
372 synchronized (mPackagesLock) {
373 mUserRestrictions.get(userId).putAll(restrictions);
374 writeUserLocked(mUsers.get(userId));
375 }
376 }
377
Amith Yamasani258848d2012-08-10 17:06:33 -0700378 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700379 * Check if we've hit the limit of how many users can be created.
380 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700381 private boolean isUserLimitReachedLocked() {
382 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700383 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700384 }
385
386 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700387 * Enforces that only the system UID or root's UID or apps that have the
388 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
389 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700390 *
391 * @param message used as message if SecurityException is thrown
392 * @throws SecurityException if the caller is not system or root
393 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700394 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700395 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700396 if (uid != Process.SYSTEM_UID && uid != 0
397 && ActivityManager.checkComponentPermission(
398 android.Manifest.permission.MANAGE_USERS,
399 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
400 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700401 }
402 }
403
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700404 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700405 try {
406 File dir = new File(mUsersDir, Integer.toString(info.id));
407 File file = new File(dir, USER_PHOTO_FILENAME);
408 if (!dir.exists()) {
409 dir.mkdir();
410 FileUtils.setPermissions(
411 dir.getPath(),
412 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
413 -1, -1);
414 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700415 FileOutputStream os;
416 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700417 info.iconPath = file.getAbsolutePath();
418 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700419 try {
420 os.close();
421 } catch (IOException ioe) {
422 // What the ... !
423 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700424 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700425 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700426 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700427 }
428
Amith Yamasani0b285492011-04-14 17:35:23 -0700429 /**
430 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
431 * cache it elsewhere.
432 * @return the array of user ids.
433 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700434 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700435 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700436 return mUserIds;
437 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700438 }
439
Dianne Hackborn4428e172012-08-24 17:43:05 -0700440 int[] getUserIdsLPr() {
441 return mUserIds;
442 }
443
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700444 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700445 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700446 readUserListLocked();
447 }
448 }
449
450 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700451 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700452 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700453 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700454 return;
455 }
456 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700457 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700458 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700459 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700460 XmlPullParser parser = Xml.newPullParser();
461 parser.setInput(fis, null);
462 int type;
463 while ((type = parser.next()) != XmlPullParser.START_TAG
464 && type != XmlPullParser.END_DOCUMENT) {
465 ;
466 }
467
468 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700469 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700470 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700471 return;
472 }
473
Amith Yamasani2a003292012-08-14 18:25:45 -0700474 mNextSerialNumber = -1;
475 if (parser.getName().equals(TAG_USERS)) {
476 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
477 if (lastSerialNumber != null) {
478 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
479 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700480 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
481 if (versionNumber != null) {
482 mUserVersion = Integer.parseInt(versionNumber);
483 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700484 }
485
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700486 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
487 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
488 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800489 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700490
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700491 if (user != null) {
492 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700493 if (user.isGuest()) {
494 mGuestEnabled = true;
495 }
496 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
497 mNextSerialNumber = user.id + 1;
498 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700499 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 }
501 }
Amith Yamasani13593602012-03-22 16:16:17 -0700502 updateUserIdsLocked();
Amith Yamasani6f34b412012-10-22 18:19:27 -0700503 upgradeIfNecessary();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700504 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700505 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700506 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700507 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800508 } finally {
509 if (fis != null) {
510 try {
511 fis.close();
512 } catch (IOException e) {
513 }
514 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700515 }
516 }
517
Amith Yamasani6f34b412012-10-22 18:19:27 -0700518 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800519 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700520 */
521 private void upgradeIfNecessary() {
522 int userVersion = mUserVersion;
523 if (userVersion < 1) {
524 // Assign a proper name for the owner, if not initialized correctly before
525 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
526 if ("Primary".equals(user.name)) {
527 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
528 writeUserLocked(user);
529 }
530 userVersion = 1;
531 }
532
Amith Yamasanibc9625052012-11-15 14:39:18 -0800533 if (userVersion < 2) {
534 // Owner should be marked as initialized
535 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
536 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
537 user.flags |= UserInfo.FLAG_INITIALIZED;
538 writeUserLocked(user);
539 }
540 userVersion = 2;
541 }
542
Amith Yamasani6f34b412012-10-22 18:19:27 -0700543 if (userVersion < USER_VERSION) {
544 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
545 + USER_VERSION);
546 } else {
547 mUserVersion = userVersion;
548 writeUserListLocked();
549 }
550 }
551
Amith Yamasani13593602012-03-22 16:16:17 -0700552 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700553 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800554 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700555 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700556 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700557 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700558 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800559
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500560 Bundle restrictions = new Bundle();
561 initRestrictionsToDefaults(restrictions);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800562 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
563
Amith Yamasani13593602012-03-22 16:16:17 -0700564 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700565
Amith Yamasani13593602012-03-22 16:16:17 -0700566 writeUserListLocked();
567 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700568 }
569
570 /*
571 * Writes the user file in this format:
572 *
573 * <user flags="20039023" id="0">
574 * <name>Primary</name>
575 * </user>
576 */
Amith Yamasani13593602012-03-22 16:16:17 -0700577 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700578 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700579 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700580 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700581 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700582 final BufferedOutputStream bos = new BufferedOutputStream(fos);
583
584 // XmlSerializer serializer = XmlUtils.serializerInstance();
585 final XmlSerializer serializer = new FastXmlSerializer();
586 serializer.setOutput(bos, "utf-8");
587 serializer.startDocument(null, true);
588 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
589
590 serializer.startTag(null, TAG_USER);
591 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700592 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700593 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700594 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
595 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
596 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700597 if (userInfo.iconPath != null) {
598 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
599 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700600 if (userInfo.partial) {
601 serializer.attribute(null, ATTR_PARTIAL, "true");
602 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700603
604 serializer.startTag(null, TAG_NAME);
605 serializer.text(userInfo.name);
606 serializer.endTag(null, TAG_NAME);
607
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800608 Bundle restrictions = mUserRestrictions.get(userInfo.id);
609 if (restrictions != null) {
610 serializer.startTag(null, TAG_RESTRICTIONS);
611 writeBoolean(serializer, restrictions, UserManager.ALLOW_CONFIG_WIFI);
612 writeBoolean(serializer, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
613 writeBoolean(serializer, restrictions, UserManager.ALLOW_INSTALL_APPS);
614 writeBoolean(serializer, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
Maggie Benthall67944582013-02-22 14:58:27 -0500615 writeBoolean(serializer, restrictions, UserManager.ALLOW_CONFIG_LOCATION_ACCESS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800616 serializer.endTag(null, TAG_RESTRICTIONS);
617 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700618 serializer.endTag(null, TAG_USER);
619
620 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700621 userFile.finishWrite(fos);
622 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700623 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700624 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700625 }
626 }
627
628 /*
629 * Writes the user list file in this format:
630 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700631 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632 * <user id="0"></user>
633 * <user id="2"></user>
634 * </users>
635 */
Amith Yamasani13593602012-03-22 16:16:17 -0700636 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700637 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700638 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700639 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700640 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700641 final BufferedOutputStream bos = new BufferedOutputStream(fos);
642
643 // XmlSerializer serializer = XmlUtils.serializerInstance();
644 final XmlSerializer serializer = new FastXmlSerializer();
645 serializer.setOutput(bos, "utf-8");
646 serializer.startDocument(null, true);
647 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
648
649 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700650 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700651 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700652
653 for (int i = 0; i < mUsers.size(); i++) {
654 UserInfo user = mUsers.valueAt(i);
655 serializer.startTag(null, TAG_USER);
656 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
657 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700658 }
659
660 serializer.endTag(null, TAG_USERS);
661
662 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700663 userListFile.finishWrite(fos);
664 } catch (Exception e) {
665 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700666 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700667 }
668 }
669
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800670 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700671 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700672 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700673 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700674 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700675 long creationTime = 0L;
676 long lastLoggedInTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700677 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800678 Bundle restrictions = new Bundle();
679 initRestrictionsToDefaults(restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700680
681 FileInputStream fis = null;
682 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700683 AtomicFile userFile =
684 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
685 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700686 XmlPullParser parser = Xml.newPullParser();
687 parser.setInput(fis, null);
688 int type;
689 while ((type = parser.next()) != XmlPullParser.START_TAG
690 && type != XmlPullParser.END_DOCUMENT) {
691 ;
692 }
693
694 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700695 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700696 return null;
697 }
698
699 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700700 int storedId = readIntAttribute(parser, ATTR_ID, -1);
701 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700702 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700703 return null;
704 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700705 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
706 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700707 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700708 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
709 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700710 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
711 if ("true".equals(valueString)) {
712 partial = true;
713 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700714
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800715 int outerDepth = parser.getDepth();
716 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
717 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
718 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
719 continue;
720 }
721 String tag = parser.getName();
722 if (TAG_NAME.equals(tag)) {
723 type = parser.next();
724 if (type == XmlPullParser.TEXT) {
725 name = parser.getText();
726 }
727 } else if (TAG_RESTRICTIONS.equals(tag)) {
728 readBoolean(parser, restrictions, UserManager.ALLOW_CONFIG_WIFI);
729 readBoolean(parser, restrictions, UserManager.ALLOW_MODIFY_ACCOUNTS);
730 readBoolean(parser, restrictions, UserManager.ALLOW_INSTALL_APPS);
731 readBoolean(parser, restrictions, UserManager.ALLOW_UNINSTALL_APPS);
Maggie Benthall67944582013-02-22 14:58:27 -0500732 readBoolean(parser, restrictions, UserManager.ALLOW_CONFIG_LOCATION_ACCESS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700733 }
734 }
735 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700736
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700737 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700738 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700739 userInfo.creationTime = creationTime;
740 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700741 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800742 mUserRestrictions.append(id, restrictions);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700743 return userInfo;
744
745 } catch (IOException ioe) {
746 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800747 } finally {
748 if (fis != null) {
749 try {
750 fis.close();
751 } catch (IOException e) {
752 }
753 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700754 }
755 return null;
756 }
757
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800758 private void readBoolean(XmlPullParser parser, Bundle restrictions,
759 String restrictionKey) {
760 String value = parser.getAttributeValue(null, restrictionKey);
761 restrictions.putBoolean(restrictionKey, value == null ? true : Boolean.parseBoolean(value));
762 }
763
764 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
765 throws IOException {
766 if (restrictions.containsKey(restrictionKey)) {
767 xml.attribute(null, restrictionKey,
768 Boolean.toString(restrictions.getBoolean(restrictionKey)));
769 }
770 }
771
772 private void initRestrictionsToDefaults(Bundle restrictions) {
773 restrictions.putBoolean(UserManager.ALLOW_CONFIG_WIFI, true);
774 restrictions.putBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS, true);
775 restrictions.putBoolean(UserManager.ALLOW_INSTALL_APPS, true);
776 restrictions.putBoolean(UserManager.ALLOW_UNINSTALL_APPS, true);
Maggie Benthall67944582013-02-22 14:58:27 -0500777 restrictions.putBoolean(UserManager.ALLOW_CONFIG_LOCATION_ACCESS, true);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800778 }
779
Amith Yamasani920ace02012-09-20 22:15:37 -0700780 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
781 String valueString = parser.getAttributeValue(null, attr);
782 if (valueString == null) return defaultValue;
783 try {
784 return Integer.parseInt(valueString);
785 } catch (NumberFormatException nfe) {
786 return defaultValue;
787 }
788 }
789
790 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
791 String valueString = parser.getAttributeValue(null, attr);
792 if (valueString == null) return defaultValue;
793 try {
794 return Long.parseLong(valueString);
795 } catch (NumberFormatException nfe) {
796 return defaultValue;
797 }
798 }
799
Amith Yamasani258848d2012-08-10 17:06:33 -0700800 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700801 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700802 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700803
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700804 final long ident = Binder.clearCallingIdentity();
805 final UserInfo userInfo;
806 try {
807 synchronized (mInstallLock) {
808 synchronized (mPackagesLock) {
809 if (isUserLimitReachedLocked()) return null;
810 int userId = getNextAvailableIdLocked();
811 userInfo = new UserInfo(userId, name, null, flags);
812 File userPath = new File(mBaseUserPath, Integer.toString(userId));
813 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700814 long now = System.currentTimeMillis();
815 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700816 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700817 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700818 mUsers.put(userId, userInfo);
819 writeUserListLocked();
820 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700821 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700822 userInfo.partial = false;
823 writeUserLocked(userInfo);
824 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500825 Bundle restrictions = new Bundle();
826 initRestrictionsToDefaults(restrictions);
827 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700828 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700829 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700830 if (userInfo != null) {
831 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
832 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
833 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
834 android.Manifest.permission.MANAGE_USERS);
835 }
836 } finally {
837 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700838 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839 return userInfo;
840 }
841
Amith Yamasani0b285492011-04-14 17:35:23 -0700842 /**
843 * Removes a user and all data directories created for that user. This method should be called
844 * after the user's processes have been terminated.
845 * @param id the user's id
846 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700847 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700848 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700849 final UserInfo user;
850 synchronized (mPackagesLock) {
851 user = mUsers.get(userHandle);
852 if (userHandle == 0 || user == null) {
853 return false;
854 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800855 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700856 // Set this to a partially created user, so that the user will be purged
857 // on next startup, in case the runtime stops now before stopping and
858 // removing the user completely.
859 user.partial = true;
860 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700861 }
Amith Yamasani16389312012-10-17 21:20:14 -0700862 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700863 int res;
864 try {
865 res = ActivityManagerNative.getDefault().stopUser(userHandle,
866 new IStopUserCallback.Stub() {
867 @Override
868 public void userStopped(int userId) {
869 finishRemoveUser(userId);
870 }
871 @Override
872 public void userStopAborted(int userId) {
873 }
874 });
875 } catch (RemoteException e) {
876 return false;
877 }
878
879 return res == ActivityManager.USER_OP_SUCCESS;
880 }
881
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700882 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -0700883 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700884 // Let other services shutdown any activity and clean up their state before completely
885 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700886 long ident = Binder.clearCallingIdentity();
887 try {
888 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
889 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -0700890 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
891 android.Manifest.permission.MANAGE_USERS,
892
893 new BroadcastReceiver() {
894 @Override
895 public void onReceive(Context context, Intent intent) {
896 if (DBG) {
897 Slog.i(LOG_TAG,
898 "USER_REMOVED broadcast sent, cleaning up user data "
899 + userHandle);
900 }
901 new Thread() {
902 public void run() {
903 synchronized (mInstallLock) {
904 synchronized (mPackagesLock) {
905 removeUserStateLocked(userHandle);
906 }
907 }
908 }
909 }.start();
910 }
911 },
912
913 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700914 } finally {
915 Binder.restoreCallingIdentity(ident);
916 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700917 }
918
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800919 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700920 // Cleanup package manager settings
921 mPm.cleanUpUserLILPw(userHandle);
922
923 // Remove this user from the list
924 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800925
926 // Have user ID linger for several seconds to let external storage VFS
927 // cache entries expire. This must be greater than the 'entry_valid'
928 // timeout used by the FUSE daemon.
929 mHandler.postDelayed(new Runnable() {
930 @Override
931 public void run() {
932 synchronized (mPackagesLock) {
933 mRemovingUserIds.delete(userHandle);
934 }
935 }
936 }, MINUTE_IN_MILLIS);
937
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 // Remove user file
939 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
940 userFile.delete();
941 // Update the user list
942 writeUserListLocked();
943 updateUserIdsLocked();
944 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
945 }
946
Amith Yamasani61f57372012-08-31 12:12:28 -0700947 private void removeDirectoryRecursive(File parent) {
948 if (parent.isDirectory()) {
949 String[] files = parent.list();
950 for (String filename : files) {
951 File child = new File(parent, filename);
952 removeDirectoryRecursive(child);
953 }
954 }
955 parent.delete();
956 }
957
Amith Yamasani2a003292012-08-14 18:25:45 -0700958 @Override
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800959 public List<RestrictionEntry> getApplicationRestrictions(String packageName, int userId) {
960 if (UserHandle.getCallingUserId() != userId
961 || Binder.getCallingUid() != getUidForPackage(packageName)) {
962 checkManageUsersPermission("Only system can get restrictions for other users/apps");
963 }
964 synchronized (mPackagesLock) {
965 // Read the restrictions from XML
966 return readApplicationRestrictionsLocked(packageName, userId);
967 }
968 }
969
970 @Override
971 public void setApplicationRestrictions(String packageName, List<RestrictionEntry> entries,
972 int userId) {
973 if (UserHandle.getCallingUserId() != userId
974 || Binder.getCallingUid() != getUidForPackage(packageName)) {
975 checkManageUsersPermission("Only system can set restrictions for other users/apps");
976 }
977 synchronized (mPackagesLock) {
978 // Write the restrictions to XML
979 writeApplicationRestrictionsLocked(packageName, entries, userId);
980 }
981 }
982
983 private int getUidForPackage(String packageName) {
984 try {
985 return mContext.getPackageManager().getApplicationInfo(packageName,
986 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
987 } catch (NameNotFoundException nnfe) {
988 return -1;
989 }
990 }
991
992 private List<RestrictionEntry> readApplicationRestrictionsLocked(String packageName,
993 int userId) {
994 final ArrayList<RestrictionEntry> entries = new ArrayList<RestrictionEntry>();
995 final ArrayList<String> values = new ArrayList<String>();
996
997 FileInputStream fis = null;
998 try {
999 AtomicFile restrictionsFile =
1000 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1001 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1002 fis = restrictionsFile.openRead();
1003 XmlPullParser parser = Xml.newPullParser();
1004 parser.setInput(fis, null);
1005 int type;
1006 while ((type = parser.next()) != XmlPullParser.START_TAG
1007 && type != XmlPullParser.END_DOCUMENT) {
1008 ;
1009 }
1010
1011 if (type != XmlPullParser.START_TAG) {
1012 Slog.e(LOG_TAG, "Unable to read restrictions file "
1013 + restrictionsFile.getBaseFile());
1014 return entries;
1015 }
1016
1017 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1018 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1019 String key = parser.getAttributeValue(null, ATTR_KEY);
1020 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1021 if (multiple != null) {
1022 int count = Integer.parseInt(multiple);
1023 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1024 if (type == XmlPullParser.START_TAG
1025 && parser.getName().equals(TAG_VALUE)) {
1026 values.add(parser.nextText().trim());
1027 count--;
1028 }
1029 }
1030 String [] valueStrings = new String[values.size()];
1031 values.toArray(valueStrings);
1032 Slog.d(LOG_TAG, "Got RestrictionEntry " + key + "," + valueStrings);
1033 RestrictionEntry entry = new RestrictionEntry(key, valueStrings);
1034 entries.add(entry);
1035 } else {
1036 String value = parser.nextText().trim();
1037 Slog.d(LOG_TAG, "Got RestrictionEntry " + key + "," + value);
1038 RestrictionEntry entry = new RestrictionEntry(key, value);
1039 entries.add(entry);
1040 }
1041 }
1042 }
1043
1044 } catch (IOException ioe) {
1045 } catch (XmlPullParserException pe) {
1046 } finally {
1047 if (fis != null) {
1048 try {
1049 fis.close();
1050 } catch (IOException e) {
1051 }
1052 }
1053 }
1054 return entries;
1055 }
1056
1057 private void writeApplicationRestrictionsLocked(String packageName,
1058 List<RestrictionEntry> entries, int userId) {
1059 FileOutputStream fos = null;
1060 AtomicFile restrictionsFile = new AtomicFile(
1061 new File(Environment.getUserSystemDirectory(userId),
1062 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1063 try {
1064 fos = restrictionsFile.startWrite();
1065 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1066
1067 // XmlSerializer serializer = XmlUtils.serializerInstance();
1068 final XmlSerializer serializer = new FastXmlSerializer();
1069 serializer.setOutput(bos, "utf-8");
1070 serializer.startDocument(null, true);
1071 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1072
1073 serializer.startTag(null, TAG_RESTRICTIONS);
1074
1075 for (RestrictionEntry entry : entries) {
1076 serializer.startTag(null, TAG_ENTRY);
1077 serializer.attribute(null, ATTR_KEY, entry.key);
1078 if (entry.getStringValue() != null || entry.getMultipleValues() == null) {
1079 String value = entry.getStringValue();
1080 serializer.text(value != null ? value : "");
1081 } else {
1082 String[] values = entry.getMultipleValues();
1083 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
1084 for (String value : values) {
1085 serializer.startTag(null, TAG_VALUE);
1086 serializer.text(value != null ? value : "");
1087 serializer.endTag(null, TAG_VALUE);
1088 }
1089 }
1090 serializer.endTag(null, TAG_ENTRY);
1091 }
1092
1093 serializer.endTag(null, TAG_RESTRICTIONS);
1094
1095 serializer.endDocument();
1096 restrictionsFile.finishWrite(fos);
1097 } catch (Exception e) {
1098 restrictionsFile.failWrite(fos);
1099 Slog.e(LOG_TAG, "Error writing application restrictions list");
1100 }
1101 }
1102
1103 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001104 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001105 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001106 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001107 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001108 }
1109 }
1110
1111 @Override
1112 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001113 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001114 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001115 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001116 }
1117 // Not found
1118 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001119 }
1120 }
1121
Amith Yamasani0b285492011-04-14 17:35:23 -07001122 /**
1123 * Caches the list of user ids in an array, adjusting the array size when necessary.
1124 */
Amith Yamasani13593602012-03-22 16:16:17 -07001125 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001126 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001127 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001128 if (!mUsers.valueAt(i).partial) {
1129 num++;
1130 }
1131 }
Amith Yamasani16389312012-10-17 21:20:14 -07001132 final int[] newUsers = new int[num];
1133 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001134 for (int i = 0; i < mUsers.size(); i++) {
1135 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001136 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001137 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001138 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001139 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001140 }
1141
1142 /**
Amith Yamasani920ace02012-09-20 22:15:37 -07001143 * Make a note of the last started time of a user.
1144 * @param userId the user that was just foregrounded
1145 */
1146 public void userForeground(int userId) {
1147 synchronized (mPackagesLock) {
1148 UserInfo user = mUsers.get(userId);
1149 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001150 if (user == null || user.partial) {
1151 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1152 return;
1153 }
1154 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001155 user.lastLoggedInTime = now;
1156 writeUserLocked(user);
1157 }
1158 }
1159 }
1160
1161 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001162 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001163 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1164 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001165 * @return
1166 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001167 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001168 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001169 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001170 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001171 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001172 break;
1173 }
1174 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001175 }
Amith Yamasani195263742012-08-21 15:40:12 -07001176 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001177 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001178 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001179
1180 @Override
1181 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1182 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1183 != PackageManager.PERMISSION_GRANTED) {
1184 pw.println("Permission Denial: can't dump UserManager from from pid="
1185 + Binder.getCallingPid()
1186 + ", uid=" + Binder.getCallingUid()
1187 + " without permission "
1188 + android.Manifest.permission.DUMP);
1189 return;
1190 }
1191
1192 long now = System.currentTimeMillis();
1193 StringBuilder sb = new StringBuilder();
1194 synchronized (mPackagesLock) {
1195 pw.println("Users:");
1196 for (int i = 0; i < mUsers.size(); i++) {
1197 UserInfo user = mUsers.valueAt(i);
1198 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001199 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001200 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001201 if (user.partial) pw.print(" <partial>");
1202 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001203 pw.print(" Created: ");
1204 if (user.creationTime == 0) {
1205 pw.println("<unknown>");
1206 } else {
1207 sb.setLength(0);
1208 TimeUtils.formatDuration(now - user.creationTime, sb);
1209 sb.append(" ago");
1210 pw.println(sb);
1211 }
1212 pw.print(" Last logged in: ");
1213 if (user.lastLoggedInTime == 0) {
1214 pw.println("<unknown>");
1215 } else {
1216 sb.setLength(0);
1217 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1218 sb.append(" ago");
1219 pw.println(sb);
1220 }
1221 }
1222 }
1223 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001224}