blob: 2edc700f6197359d21a52a661ee3da5cd14fde98 [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
Amith Yamasanib8151ec2012-04-18 18:02:48 -070019import static android.os.ParcelFileDescriptor.MODE_CREATE;
20import static android.os.ParcelFileDescriptor.MODE_READ_WRITE;
21
Amith Yamasani13593602012-03-22 16:16:17 -070022import com.android.internal.util.ArrayUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070023import com.android.internal.util.FastXmlSerializer;
24
Amith Yamasani2a003292012-08-14 18:25:45 -070025import android.app.ActivityManager;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070026import android.app.ActivityManagerNative;
27import android.app.IStopUserCallback;
Amith Yamasani258848d2012-08-10 17:06:33 -070028import android.content.Context;
29import android.content.Intent;
Amith Yamasani0b285492011-04-14 17:35:23 -070030import android.content.pm.PackageManager;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070031import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070032import android.graphics.Bitmap;
33import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070034import android.os.Binder;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070035import android.os.Environment;
36import android.os.FileUtils;
Amith Yamasani258848d2012-08-10 17:06:33 -070037import android.os.IUserManager;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070038import android.os.ParcelFileDescriptor;
Amith Yamasani258848d2012-08-10 17:06:33 -070039import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070040import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070041import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070042import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070043import android.util.AtomicFile;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070044import android.util.Slog;
45import android.util.SparseArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070046import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Xml;
48
49import java.io.BufferedOutputStream;
50import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070051import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070052import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070053import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import java.io.FileOutputStream;
55import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070056import java.io.PrintWriter;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070057import java.util.ArrayList;
Amith Yamasani920ace02012-09-20 22:15:37 -070058import java.util.HashSet;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070059import java.util.List;
60
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63import org.xmlpull.v1.XmlSerializer;
64
Amith Yamasani258848d2012-08-10 17:06:33 -070065public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070066
Amith Yamasani2a003292012-08-14 18:25:45 -070067 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070068
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070070 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070071 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070073 private static final String ATTR_CREATION_TIME = "created";
74 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani2a003292012-08-14 18:25:45 -070075 private static final String ATTR_SERIAL_NO = "serialNumber";
76 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070077 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070078 private static final String TAG_USER = "user";
79
Amith Yamasani0b285492011-04-14 17:35:23 -070080 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070082 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070083
Amith Yamasani920ace02012-09-20 22:15:37 -070084 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
85
Dianne Hackborn4428e172012-08-24 17:43:05 -070086 private final Context mContext;
87 private final PackageManagerService mPm;
88 private final Object mInstallLock;
89 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070090
91 private final File mUsersDir;
92 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -070093 private final File mBaseUserPath;
94
95 private SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasani920ace02012-09-20 22:15:37 -070096 private HashSet<Integer> mRemovingUserIds = new HashSet<Integer>();
Dianne Hackborn4428e172012-08-24 17:43:05 -070097
Amith Yamasani0b285492011-04-14 17:35:23 -070098 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -070099 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700100 private int mNextSerialNumber;
Amith Yamasani0b285492011-04-14 17:35:23 -0700101
Amith Yamasani258848d2012-08-10 17:06:33 -0700102 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700103
Dianne Hackborn4428e172012-08-24 17:43:05 -0700104 public static UserManagerService getInstance() {
105 synchronized (UserManagerService.class) {
106 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700107 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700108 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109
110 /**
111 * Available for testing purposes.
112 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700113 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700114 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700115 }
116
Dianne Hackborn4428e172012-08-24 17:43:05 -0700117 /**
118 * Called by package manager to create the service. This is closely
119 * associated with the package manager, and the given lock is the
120 * package manager's own lock.
121 */
122 UserManagerService(Context context, PackageManagerService pm,
123 Object installLock, Object packagesLock) {
124 this(context, pm, installLock, packagesLock,
125 Environment.getDataDirectory(),
126 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700127 }
128
Dianne Hackborn4428e172012-08-24 17:43:05 -0700129 /**
130 * Available for testing purposes.
131 */
132 private UserManagerService(Context context, PackageManagerService pm,
133 Object installLock, Object packagesLock,
134 File dataDir, File baseUserPath) {
135 synchronized (UserManagerService.class) {
136 mContext = context;
137 mPm = pm;
138 mInstallLock = installLock;
139 mPackagesLock = packagesLock;
140 mUsersDir = new File(dataDir, USER_INFO_DIR);
141 mUsersDir.mkdirs();
142 // Make zeroth user directory, for services to migrate their files to that location
143 File userZeroDir = new File(mUsersDir, "0");
144 userZeroDir.mkdirs();
145 mBaseUserPath = baseUserPath;
146 FileUtils.setPermissions(mUsersDir.toString(),
147 FileUtils.S_IRWXU|FileUtils.S_IRWXG
148 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
149 -1, -1);
150 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
151 readUserList();
152 sInstance = this;
153 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700154 }
155
156 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700157 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700158 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700159 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700160 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
161 for (int i = 0; i < mUsers.size(); i++) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700162 if (!excludeDying || !mRemovingUserIds.contains(mUsers.keyAt(i))) {
163 users.add(mUsers.valueAt(i));
164 }
Amith Yamasani13593602012-03-22 16:16:17 -0700165 }
166 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700167 }
Amith Yamasani13593602012-03-22 16:16:17 -0700168 }
169
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 @Override
171 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700172 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700173 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700174 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700175 }
176 }
177
Amith Yamasani195263742012-08-21 15:40:12 -0700178 /*
179 * Should be locked on mUsers before calling this.
180 */
181 private UserInfo getUserInfoLocked(int userId) {
182 return mUsers.get(userId);
183 }
184
Amith Yamasani13593602012-03-22 16:16:17 -0700185 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700186 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700187 return ArrayUtils.contains(mUserIds, userId);
188 }
189 }
190
Amith Yamasani258848d2012-08-10 17:06:33 -0700191 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700192 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700193 checkManageUsersPermission("rename users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700194 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700195 UserInfo info = mUsers.get(userId);
196 if (name != null && !name.equals(info.name)) {
197 info.name = name;
198 writeUserLocked(info);
199 }
200 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700201 sendUserInfoChangedBroadcast(userId);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700202 }
203
Amith Yamasani258848d2012-08-10 17:06:33 -0700204 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700205 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700206 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700207 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700208 UserInfo info = mUsers.get(userId);
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700209 if (info == null) return;
210 writeBitmapLocked(info, bitmap);
211 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700212 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700213 sendUserInfoChangedBroadcast(userId);
214 }
215
216 private void sendUserInfoChangedBroadcast(int userId) {
217 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
218 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
219 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
220 mContext.sendBroadcastAsUser(changedIntent, new UserHandle(userId));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700221 }
222
Amith Yamasani258848d2012-08-10 17:06:33 -0700223 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700224 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700225 checkManageUsersPermission("read users");
226 synchronized (mPackagesLock) {
227 UserInfo info = mUsers.get(userId);
228 if (info == null || info.iconPath == null) return null;
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700229 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700230 }
231 }
232
233 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700234 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700235 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700236 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700237 if (mGuestEnabled != enable) {
238 mGuestEnabled = enable;
239 // Erase any guest user that currently exists
240 for (int i = 0; i < mUsers.size(); i++) {
241 UserInfo user = mUsers.valueAt(i);
242 if (user.isGuest()) {
243 if (!enable) {
244 removeUser(user.id);
245 }
246 return;
247 }
248 }
249 // No guest was found
250 if (enable) {
251 createUser("Guest", UserInfo.FLAG_GUEST);
252 }
253 }
254 }
255 }
256
257 @Override
258 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700259 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 return mGuestEnabled;
261 }
262 }
263
264 @Override
265 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700266 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700267 // TODO:
268 }
269
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700270 public void makeInitialized(int userId) {
271 checkManageUsersPermission("makeInitialized");
272 synchronized (mPackagesLock) {
273 UserInfo info = mUsers.get(userId);
274 if (info != null && (info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
275 info.flags |= UserInfo.FLAG_INITIALIZED;
276 writeUserLocked(info);
277 }
278 }
279 }
280
Amith Yamasani258848d2012-08-10 17:06:33 -0700281 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700282 * Check if we've hit the limit of how many users can be created.
283 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700284 private boolean isUserLimitReachedLocked() {
285 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700286 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700287 }
288
289 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700290 * Enforces that only the system UID or root's UID or apps that have the
291 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
292 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700293 *
294 * @param message used as message if SecurityException is thrown
295 * @throws SecurityException if the caller is not system or root
296 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700297 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700298 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700299 if (uid != Process.SYSTEM_UID && uid != 0
300 && ActivityManager.checkComponentPermission(
301 android.Manifest.permission.MANAGE_USERS,
302 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
303 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700304 }
305 }
306
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700307 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700308 try {
309 File dir = new File(mUsersDir, Integer.toString(info.id));
310 File file = new File(dir, USER_PHOTO_FILENAME);
311 if (!dir.exists()) {
312 dir.mkdir();
313 FileUtils.setPermissions(
314 dir.getPath(),
315 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
316 -1, -1);
317 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700318 FileOutputStream os;
319 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700320 info.iconPath = file.getAbsolutePath();
321 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700322 try {
323 os.close();
324 } catch (IOException ioe) {
325 // What the ... !
326 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700327 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700328 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700329 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700330 }
331
Amith Yamasani0b285492011-04-14 17:35:23 -0700332 /**
333 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
334 * cache it elsewhere.
335 * @return the array of user ids.
336 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700337 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700338 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700339 return mUserIds;
340 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700341 }
342
Dianne Hackborn4428e172012-08-24 17:43:05 -0700343 int[] getUserIdsLPr() {
344 return mUserIds;
345 }
346
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700347 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700348 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700349 readUserListLocked();
350 }
351 }
352
353 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700354 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700355 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700356 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700357 return;
358 }
359 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700360 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700361 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700362 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700363 XmlPullParser parser = Xml.newPullParser();
364 parser.setInput(fis, null);
365 int type;
366 while ((type = parser.next()) != XmlPullParser.START_TAG
367 && type != XmlPullParser.END_DOCUMENT) {
368 ;
369 }
370
371 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700372 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700373 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700374 return;
375 }
376
Amith Yamasani2a003292012-08-14 18:25:45 -0700377 mNextSerialNumber = -1;
378 if (parser.getName().equals(TAG_USERS)) {
379 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
380 if (lastSerialNumber != null) {
381 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
382 }
383 }
384
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700385 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
386 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
387 String id = parser.getAttributeValue(null, ATTR_ID);
388 UserInfo user = readUser(Integer.parseInt(id));
389 if (user != null) {
390 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700391 if (user.isGuest()) {
392 mGuestEnabled = true;
393 }
394 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
395 mNextSerialNumber = user.id + 1;
396 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700397 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700398 }
399 }
Amith Yamasani13593602012-03-22 16:16:17 -0700400 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700401 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700402 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700403 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700404 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800405 } finally {
406 if (fis != null) {
407 try {
408 fis.close();
409 } catch (IOException e) {
410 }
411 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700412 }
413 }
414
Amith Yamasani13593602012-03-22 16:16:17 -0700415 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700416 // Create the primary user
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700417 UserInfo primary = new UserInfo(0, "Primary", null,
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700418 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY);
419 mUsers.put(0, primary);
Amith Yamasani13593602012-03-22 16:16:17 -0700420 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700421
Amith Yamasani13593602012-03-22 16:16:17 -0700422 writeUserListLocked();
423 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700424 }
425
426 /*
427 * Writes the user file in this format:
428 *
429 * <user flags="20039023" id="0">
430 * <name>Primary</name>
431 * </user>
432 */
Amith Yamasani13593602012-03-22 16:16:17 -0700433 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700434 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700435 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700436 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700437 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700438 final BufferedOutputStream bos = new BufferedOutputStream(fos);
439
440 // XmlSerializer serializer = XmlUtils.serializerInstance();
441 final XmlSerializer serializer = new FastXmlSerializer();
442 serializer.setOutput(bos, "utf-8");
443 serializer.startDocument(null, true);
444 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
445
446 serializer.startTag(null, TAG_USER);
447 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700448 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700449 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700450 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
451 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
452 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700453 if (userInfo.iconPath != null) {
454 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
455 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700456
457 serializer.startTag(null, TAG_NAME);
458 serializer.text(userInfo.name);
459 serializer.endTag(null, TAG_NAME);
460
461 serializer.endTag(null, TAG_USER);
462
463 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700464 userFile.finishWrite(fos);
465 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700466 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700467 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700468 }
469 }
470
471 /*
472 * Writes the user list file in this format:
473 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700474 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700475 * <user id="0"></user>
476 * <user id="2"></user>
477 * </users>
478 */
Amith Yamasani13593602012-03-22 16:16:17 -0700479 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700480 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700481 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700482 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700483 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700484 final BufferedOutputStream bos = new BufferedOutputStream(fos);
485
486 // XmlSerializer serializer = XmlUtils.serializerInstance();
487 final XmlSerializer serializer = new FastXmlSerializer();
488 serializer.setOutput(bos, "utf-8");
489 serializer.startDocument(null, true);
490 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
491
492 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700493 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700494
495 for (int i = 0; i < mUsers.size(); i++) {
496 UserInfo user = mUsers.valueAt(i);
497 serializer.startTag(null, TAG_USER);
498 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
499 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 }
501
502 serializer.endTag(null, TAG_USERS);
503
504 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700505 userListFile.finishWrite(fos);
506 } catch (Exception e) {
507 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700508 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700509 }
510 }
511
512 private UserInfo readUser(int id) {
513 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700514 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700515 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700516 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700517 long creationTime = 0L;
518 long lastLoggedInTime = 0L;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700519
520 FileInputStream fis = null;
521 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700522 AtomicFile userFile =
523 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
524 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700525 XmlPullParser parser = Xml.newPullParser();
526 parser.setInput(fis, null);
527 int type;
528 while ((type = parser.next()) != XmlPullParser.START_TAG
529 && type != XmlPullParser.END_DOCUMENT) {
530 ;
531 }
532
533 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700534 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700535 return null;
536 }
537
538 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700539 int storedId = readIntAttribute(parser, ATTR_ID, -1);
540 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700541 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700542 return null;
543 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700544 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
545 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700546 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700547 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
548 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700549
550 while ((type = parser.next()) != XmlPullParser.START_TAG
551 && type != XmlPullParser.END_DOCUMENT) {
552 }
553 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_NAME)) {
554 type = parser.next();
555 if (type == XmlPullParser.TEXT) {
556 name = parser.getText();
557 }
558 }
559 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700560
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700561 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700562 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700563 userInfo.creationTime = creationTime;
564 userInfo.lastLoggedInTime = lastLoggedInTime;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700565 return userInfo;
566
567 } catch (IOException ioe) {
568 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800569 } finally {
570 if (fis != null) {
571 try {
572 fis.close();
573 } catch (IOException e) {
574 }
575 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700576 }
577 return null;
578 }
579
Amith Yamasani920ace02012-09-20 22:15:37 -0700580 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
581 String valueString = parser.getAttributeValue(null, attr);
582 if (valueString == null) return defaultValue;
583 try {
584 return Integer.parseInt(valueString);
585 } catch (NumberFormatException nfe) {
586 return defaultValue;
587 }
588 }
589
590 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
591 String valueString = parser.getAttributeValue(null, attr);
592 if (valueString == null) return defaultValue;
593 try {
594 return Long.parseLong(valueString);
595 } catch (NumberFormatException nfe) {
596 return defaultValue;
597 }
598 }
599
Amith Yamasani258848d2012-08-10 17:06:33 -0700600 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700601 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700602 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700603
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700604 final long ident = Binder.clearCallingIdentity();
605 final UserInfo userInfo;
606 try {
607 synchronized (mInstallLock) {
608 synchronized (mPackagesLock) {
609 if (isUserLimitReachedLocked()) return null;
610 int userId = getNextAvailableIdLocked();
611 userInfo = new UserInfo(userId, name, null, flags);
612 File userPath = new File(mBaseUserPath, Integer.toString(userId));
613 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700614 long now = System.currentTimeMillis();
615 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700616 mUsers.put(userId, userInfo);
617 writeUserListLocked();
618 writeUserLocked(userInfo);
619 updateUserIdsLocked();
620 mPm.createNewUserLILPw(userId, userPath);
621 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700622 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700623 if (userInfo != null) {
624 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
625 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
626 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
627 android.Manifest.permission.MANAGE_USERS);
628 }
629 } finally {
630 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700631 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632 return userInfo;
633 }
634
Amith Yamasani0b285492011-04-14 17:35:23 -0700635 /**
636 * Removes a user and all data directories created for that user. This method should be called
637 * after the user's processes have been terminated.
638 * @param id the user's id
639 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700640 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700641 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700642 final UserInfo user;
643 synchronized (mPackagesLock) {
644 user = mUsers.get(userHandle);
645 if (userHandle == 0 || user == null) {
646 return false;
647 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700648 mRemovingUserIds.add(userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700649 }
650
651 int res;
652 try {
653 res = ActivityManagerNative.getDefault().stopUser(userHandle,
654 new IStopUserCallback.Stub() {
655 @Override
656 public void userStopped(int userId) {
657 finishRemoveUser(userId);
658 }
659 @Override
660 public void userStopAborted(int userId) {
661 }
662 });
663 } catch (RemoteException e) {
664 return false;
665 }
666
667 return res == ActivityManager.USER_OP_SUCCESS;
668 }
669
670 void finishRemoveUser(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700671 synchronized (mInstallLock) {
672 synchronized (mPackagesLock) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700673 // Cleanup package manager settings
674 mPm.cleanUpUserLILPw(userHandle);
675
676 // Remove this user from the list
677 mUsers.remove(userHandle);
Amith Yamasani920ace02012-09-20 22:15:37 -0700678 mRemovingUserIds.remove(userHandle);
Dianne Hackborn4428e172012-08-24 17:43:05 -0700679 // Remove user file
680 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
681 userFile.delete();
682 // Update the user list
683 writeUserListLocked();
684 updateUserIdsLocked();
Amith Yamasani61f57372012-08-31 12:12:28 -0700685 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
Dianne Hackborn4428e172012-08-24 17:43:05 -0700686 }
687 }
Amith Yamasani0cd867c2012-08-22 16:45:47 -0700688
Amith Yamasani2a003292012-08-14 18:25:45 -0700689 // Let other services shutdown any activity
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700690 long ident = Binder.clearCallingIdentity();
691 try {
692 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
693 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
694 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
695 android.Manifest.permission.MANAGE_USERS);
696 } finally {
697 Binder.restoreCallingIdentity(ident);
698 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700699 }
700
Amith Yamasani61f57372012-08-31 12:12:28 -0700701 private void removeDirectoryRecursive(File parent) {
702 if (parent.isDirectory()) {
703 String[] files = parent.list();
704 for (String filename : files) {
705 File child = new File(parent, filename);
706 removeDirectoryRecursive(child);
707 }
708 }
709 parent.delete();
710 }
711
Amith Yamasani2a003292012-08-14 18:25:45 -0700712 @Override
713 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700714 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700715 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -0700716 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -0700717 }
718 }
719
720 @Override
721 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700722 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700723 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -0700724 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -0700725 }
726 // Not found
727 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -0700728 }
729 }
730
Amith Yamasani0b285492011-04-14 17:35:23 -0700731 /**
732 * Caches the list of user ids in an array, adjusting the array size when necessary.
733 */
Amith Yamasani13593602012-03-22 16:16:17 -0700734 private void updateUserIdsLocked() {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700735 int[] newUsers = new int[mUsers.size()];
Amith Yamasani0b285492011-04-14 17:35:23 -0700736 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700737 newUsers[i] = mUsers.keyAt(i);
Amith Yamasani0b285492011-04-14 17:35:23 -0700738 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700739 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -0700740 }
741
742 /**
Amith Yamasani920ace02012-09-20 22:15:37 -0700743 * Make a note of the last started time of a user.
744 * @param userId the user that was just foregrounded
745 */
746 public void userForeground(int userId) {
747 synchronized (mPackagesLock) {
748 UserInfo user = mUsers.get(userId);
749 long now = System.currentTimeMillis();
750 if (user != null && now > EPOCH_PLUS_30_YEARS) {
751 user.lastLoggedInTime = now;
752 writeUserLocked(user);
753 }
754 }
755 }
756
757 /**
Amith Yamasani0b285492011-04-14 17:35:23 -0700758 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -0700759 * TODO: May not be a good idea to recycle ids, in case it results in confusion
760 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -0700761 * @return
762 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700763 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700764 synchronized (mPackagesLock) {
Amith Yamasani07a0ede2012-09-17 14:54:26 -0700765 int i = 10;
Amith Yamasani195263742012-08-21 15:40:12 -0700766 while (i < Integer.MAX_VALUE) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700767 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.contains(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -0700768 break;
769 }
770 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700771 }
Amith Yamasani195263742012-08-21 15:40:12 -0700772 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700775
776 @Override
777 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
778 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
779 != PackageManager.PERMISSION_GRANTED) {
780 pw.println("Permission Denial: can't dump UserManager from from pid="
781 + Binder.getCallingPid()
782 + ", uid=" + Binder.getCallingUid()
783 + " without permission "
784 + android.Manifest.permission.DUMP);
785 return;
786 }
787
788 long now = System.currentTimeMillis();
789 StringBuilder sb = new StringBuilder();
790 synchronized (mPackagesLock) {
791 pw.println("Users:");
792 for (int i = 0; i < mUsers.size(); i++) {
793 UserInfo user = mUsers.valueAt(i);
794 if (user == null) continue;
795 pw.print(" "); pw.print(user);
796 pw.println(mRemovingUserIds.contains(mUsers.keyAt(i)) ? " <removing> " : "");
797 pw.print(" Created: ");
798 if (user.creationTime == 0) {
799 pw.println("<unknown>");
800 } else {
801 sb.setLength(0);
802 TimeUtils.formatDuration(now - user.creationTime, sb);
803 sb.append(" ago");
804 pw.println(sb);
805 }
806 pw.print(" Last logged in: ");
807 if (user.lastLoggedInTime == 0) {
808 pw.println("<unknown>");
809 } else {
810 sb.setLength(0);
811 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
812 sb.append(" ago");
813 pw.println(sb);
814 }
815 }
816 }
817 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700818}