blob: c33134a24d19947bbc8c914d12db87b00966727c [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;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070024import android.app.ActivityThread;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070025import android.app.IStopUserCallback;
Amith Yamasanidb6a14c2012-10-17 21:16:52 -070026import android.content.BroadcastReceiver;
Amith Yamasani258848d2012-08-10 17:06:33 -070027import android.content.Context;
28import android.content.Intent;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070029import android.content.pm.ApplicationInfo;
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 Yamasani655d0e22013-06-12 14:19:10 -070046import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070047import android.util.Slog;
48import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080049import android.util.SparseBooleanArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070050import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070051import android.util.Xml;
52
Amith Yamasani1a7472e2013-07-02 11:17:30 -070053import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080054import com.android.internal.util.ArrayUtils;
55import com.android.internal.util.FastXmlSerializer;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
Amith Yamasani4b2e9342011-03-31 12:38:53 -070061import java.io.BufferedOutputStream;
62import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070063import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070065import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070066import java.io.FileOutputStream;
67import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070068import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070069import java.security.MessageDigest;
70import java.security.NoSuchAlgorithmException;
71import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070072import java.util.ArrayList;
73import java.util.List;
74
Amith Yamasani258848d2012-08-10 17:06:33 -070075public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070076
Amith Yamasani2a003292012-08-14 18:25:45 -070077 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070078
Amith Yamasani16389312012-10-17 21:20:14 -070079 private static final boolean DBG = false;
80
Amith Yamasani4b2e9342011-03-31 12:38:53 -070081 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070082 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070083 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070085 private static final String ATTR_CREATION_TIME = "created";
86 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070087 private static final String ATTR_SALT = "salt";
88 private static final String ATTR_PIN_HASH = "pinHash";
89 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
90 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070091 private static final String ATTR_SERIAL_NO = "serialNumber";
92 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070093 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070094 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070095 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070096 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -080097 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080098 private static final String TAG_ENTRY = "entry";
99 private static final String TAG_VALUE = "value";
100 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700101 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800102 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700103
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
105 private static final String ATTR_TYPE_STRING = "s";
106 private static final String ATTR_TYPE_BOOLEAN = "b";
107
Amith Yamasani0b285492011-04-14 17:35:23 -0700108 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700109 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700110 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700111
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800112 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
Amith Yamasanifc95e702013-09-26 13:20:17 -0700113 private static final String XML_SUFFIX = ".xml";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800114
Amith Yamasani634cf312012-10-04 17:34:21 -0700115 private static final int MIN_USER_ID = 10;
116
Amith Yamasani5e486f52013-08-07 11:06:44 -0700117 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700118
Amith Yamasani920ace02012-09-20 22:15:37 -0700119 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
120
Amith Yamasani655d0e22013-06-12 14:19:10 -0700121 // Number of attempts before jumping to the next BACKOFF_TIMES slot
122 private static final int BACKOFF_INC_INTERVAL = 5;
123
124 // Amount of time to force the user to wait before entering the PIN again, after failing
125 // BACKOFF_INC_INTERVAL times.
126 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
127
Dianne Hackborn4428e172012-08-24 17:43:05 -0700128 private final Context mContext;
129 private final PackageManagerService mPm;
130 private final Object mInstallLock;
131 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700132
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800133 private final Handler mHandler;
134
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700135 private final File mUsersDir;
136 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700137 private final File mBaseUserPath;
138
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800139 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800140 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800141
Amith Yamasani655d0e22013-06-12 14:19:10 -0700142 class RestrictionsPinState {
143 long salt;
144 String pinHash;
145 int failedAttempts;
146 long lastAttemptTime;
147 }
148
149 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
150 new SparseArray<RestrictionsPinState>();
151
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800152 /**
153 * Set of user IDs being actively removed. Removed IDs linger in this set
154 * for several seconds to work around a VFS caching issue.
155 */
156 // @GuardedBy("mPackagesLock")
157 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700158
Amith Yamasani0b285492011-04-14 17:35:23 -0700159 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700160 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700161 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700162 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700163
Amith Yamasani258848d2012-08-10 17:06:33 -0700164 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700165
Dianne Hackborn4428e172012-08-24 17:43:05 -0700166 public static UserManagerService getInstance() {
167 synchronized (UserManagerService.class) {
168 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700169 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700170 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700171
172 /**
173 * Available for testing purposes.
174 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700175 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700176 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700177 }
178
Dianne Hackborn4428e172012-08-24 17:43:05 -0700179 /**
180 * Called by package manager to create the service. This is closely
181 * associated with the package manager, and the given lock is the
182 * package manager's own lock.
183 */
184 UserManagerService(Context context, PackageManagerService pm,
185 Object installLock, Object packagesLock) {
186 this(context, pm, installLock, packagesLock,
187 Environment.getDataDirectory(),
188 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700189 }
190
Dianne Hackborn4428e172012-08-24 17:43:05 -0700191 /**
192 * Available for testing purposes.
193 */
194 private UserManagerService(Context context, PackageManagerService pm,
195 Object installLock, Object packagesLock,
196 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700197 mContext = context;
198 mPm = pm;
199 mInstallLock = installLock;
200 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800201 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700202 synchronized (mInstallLock) {
203 synchronized (mPackagesLock) {
204 mUsersDir = new File(dataDir, USER_INFO_DIR);
205 mUsersDir.mkdirs();
206 // Make zeroth user directory, for services to migrate their files to that location
207 File userZeroDir = new File(mUsersDir, "0");
208 userZeroDir.mkdirs();
209 mBaseUserPath = baseUserPath;
210 FileUtils.setPermissions(mUsersDir.toString(),
211 FileUtils.S_IRWXU|FileUtils.S_IRWXG
212 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
213 -1, -1);
214 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
215 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700216 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700217 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
218 for (int i = 0; i < mUsers.size(); i++) {
219 UserInfo ui = mUsers.valueAt(i);
220 if (ui.partial && i != 0) {
221 partials.add(ui);
222 }
223 }
224 for (int i = 0; i < partials.size(); i++) {
225 UserInfo ui = partials.get(i);
226 Slog.w(LOG_TAG, "Removing partially created user #" + i
227 + " (name=" + ui.name + ")");
228 removeUserStateLocked(ui.id);
229 }
230 sInstance = this;
231 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700232 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700233 }
234
235 void systemReady() {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700236 final Context context = ActivityThread.systemMain().getSystemContext();
237 mUserPackageMonitor.register(context,
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700238 null, UserHandle.ALL, false);
239 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700240 }
241
242 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700243 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700244 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700245 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700246 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
247 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700248 UserInfo ui = mUsers.valueAt(i);
249 if (ui.partial) {
250 continue;
251 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800252 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700253 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700254 }
Amith Yamasani13593602012-03-22 16:16:17 -0700255 }
256 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700257 }
Amith Yamasani13593602012-03-22 16:16:17 -0700258 }
259
Amith Yamasani258848d2012-08-10 17:06:33 -0700260 @Override
261 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700262 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700263 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700264 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700265 }
266 }
267
Amith Yamasani71e6c692013-03-24 17:39:28 -0700268 @Override
269 public boolean isRestricted() {
270 synchronized (mPackagesLock) {
271 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
272 }
273 }
274
Amith Yamasani195263742012-08-21 15:40:12 -0700275 /*
276 * Should be locked on mUsers before calling this.
277 */
278 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700279 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700280 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800281 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700282 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
283 return null;
284 }
285 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700286 }
287
Amith Yamasani13593602012-03-22 16:16:17 -0700288 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700289 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700290 return ArrayUtils.contains(mUserIds, userId);
291 }
292 }
293
Amith Yamasani258848d2012-08-10 17:06:33 -0700294 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700295 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700296 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700297 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700298 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700299 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700300 if (info == null || info.partial) {
301 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
302 return;
303 }
Amith Yamasani13593602012-03-22 16:16:17 -0700304 if (name != null && !name.equals(info.name)) {
305 info.name = name;
306 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700307 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700308 }
309 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700310 if (changed) {
311 sendUserInfoChangedBroadcast(userId);
312 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700313 }
314
Amith Yamasani258848d2012-08-10 17:06:33 -0700315 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700316 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700317 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700318 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700319 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700320 if (info == null || info.partial) {
321 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
322 return;
323 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700324 writeBitmapLocked(info, bitmap);
325 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700326 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700327 sendUserInfoChangedBroadcast(userId);
328 }
329
330 private void sendUserInfoChangedBroadcast(int userId) {
331 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
332 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
333 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700334 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700335 }
336
Amith Yamasani258848d2012-08-10 17:06:33 -0700337 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700338 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700339 checkManageUsersPermission("read users");
340 synchronized (mPackagesLock) {
341 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700342 if (info == null || info.partial) {
343 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
344 return null;
345 }
346 if (info.iconPath == null) {
347 return null;
348 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700349 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700350 }
351 }
352
353 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700354 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700355 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700356 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700357 if (mGuestEnabled != enable) {
358 mGuestEnabled = enable;
359 // Erase any guest user that currently exists
360 for (int i = 0; i < mUsers.size(); i++) {
361 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700362 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700363 if (!enable) {
364 removeUser(user.id);
365 }
366 return;
367 }
368 }
369 // No guest was found
370 if (enable) {
371 createUser("Guest", UserInfo.FLAG_GUEST);
372 }
373 }
374 }
375 }
376
377 @Override
378 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700379 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700380 return mGuestEnabled;
381 }
382 }
383
384 @Override
385 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700386 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700387 // TODO:
388 }
389
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700390 public void makeInitialized(int userId) {
391 checkManageUsersPermission("makeInitialized");
392 synchronized (mPackagesLock) {
393 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700394 if (info == null || info.partial) {
395 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
396 }
397 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700398 info.flags |= UserInfo.FLAG_INITIALIZED;
399 writeUserLocked(info);
400 }
401 }
402 }
403
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800404 @Override
405 public Bundle getUserRestrictions(int userId) {
406 // checkManageUsersPermission("getUserRestrictions");
407
408 synchronized (mPackagesLock) {
409 Bundle restrictions = mUserRestrictions.get(userId);
410 return restrictions != null ? restrictions : Bundle.EMPTY;
411 }
412 }
413
414 @Override
415 public void setUserRestrictions(Bundle restrictions, int userId) {
416 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700417 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800418
419 synchronized (mPackagesLock) {
Amith Yamasani350962c2013-08-06 11:18:53 -0700420 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800421 mUserRestrictions.get(userId).putAll(restrictions);
422 writeUserLocked(mUsers.get(userId));
423 }
424 }
425
Amith Yamasani258848d2012-08-10 17:06:33 -0700426 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700427 * Check if we've hit the limit of how many users can be created.
428 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700429 private boolean isUserLimitReachedLocked() {
430 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700431 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700432 }
433
434 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700435 * Enforces that only the system UID or root's UID or apps that have the
436 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
437 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700438 *
439 * @param message used as message if SecurityException is thrown
440 * @throws SecurityException if the caller is not system or root
441 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700442 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700444 if (uid != Process.SYSTEM_UID && uid != 0
445 && ActivityManager.checkComponentPermission(
446 android.Manifest.permission.MANAGE_USERS,
447 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
448 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700449 }
450 }
451
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700452 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700453 try {
454 File dir = new File(mUsersDir, Integer.toString(info.id));
455 File file = new File(dir, USER_PHOTO_FILENAME);
456 if (!dir.exists()) {
457 dir.mkdir();
458 FileUtils.setPermissions(
459 dir.getPath(),
460 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
461 -1, -1);
462 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700463 FileOutputStream os;
464 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700465 info.iconPath = file.getAbsolutePath();
466 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700467 try {
468 os.close();
469 } catch (IOException ioe) {
470 // What the ... !
471 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700472 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700473 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700474 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700475 }
476
Amith Yamasani0b285492011-04-14 17:35:23 -0700477 /**
478 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
479 * cache it elsewhere.
480 * @return the array of user ids.
481 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700482 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700483 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700484 return mUserIds;
485 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700486 }
487
Dianne Hackborn4428e172012-08-24 17:43:05 -0700488 int[] getUserIdsLPr() {
489 return mUserIds;
490 }
491
Amith Yamasani13593602012-03-22 16:16:17 -0700492 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700493 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700494 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700495 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700496 return;
497 }
498 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700499 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700501 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700502 XmlPullParser parser = Xml.newPullParser();
503 parser.setInput(fis, null);
504 int type;
505 while ((type = parser.next()) != XmlPullParser.START_TAG
506 && type != XmlPullParser.END_DOCUMENT) {
507 ;
508 }
509
510 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700511 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700512 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700513 return;
514 }
515
Amith Yamasani2a003292012-08-14 18:25:45 -0700516 mNextSerialNumber = -1;
517 if (parser.getName().equals(TAG_USERS)) {
518 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
519 if (lastSerialNumber != null) {
520 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
521 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700522 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
523 if (versionNumber != null) {
524 mUserVersion = Integer.parseInt(versionNumber);
525 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700526 }
527
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700528 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
529 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
530 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800531 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700532
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700533 if (user != null) {
534 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700535 if (user.isGuest()) {
536 mGuestEnabled = true;
537 }
538 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
539 mNextSerialNumber = user.id + 1;
540 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700541 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700542 }
543 }
Amith Yamasani13593602012-03-22 16:16:17 -0700544 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700545 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700546 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700547 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700548 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700549 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800550 } finally {
551 if (fis != null) {
552 try {
553 fis.close();
554 } catch (IOException e) {
555 }
556 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700557 }
558 }
559
Amith Yamasani6f34b412012-10-22 18:19:27 -0700560 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800561 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700562 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700563 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700564 int userVersion = mUserVersion;
565 if (userVersion < 1) {
566 // Assign a proper name for the owner, if not initialized correctly before
567 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
568 if ("Primary".equals(user.name)) {
569 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
570 writeUserLocked(user);
571 }
572 userVersion = 1;
573 }
574
Amith Yamasanibc9625052012-11-15 14:39:18 -0800575 if (userVersion < 2) {
576 // Owner should be marked as initialized
577 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
578 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
579 user.flags |= UserInfo.FLAG_INITIALIZED;
580 writeUserLocked(user);
581 }
582 userVersion = 2;
583 }
584
Amith Yamasani350962c2013-08-06 11:18:53 -0700585
Amith Yamasani5e486f52013-08-07 11:06:44 -0700586 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700587 userVersion = 4;
588 }
589
Amith Yamasani6f34b412012-10-22 18:19:27 -0700590 if (userVersion < USER_VERSION) {
591 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
592 + USER_VERSION);
593 } else {
594 mUserVersion = userVersion;
595 writeUserListLocked();
596 }
597 }
598
Amith Yamasani13593602012-03-22 16:16:17 -0700599 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700600 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800601 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700602 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700603 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700604 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700605 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400606 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800607
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500608 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800609 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
610
Amith Yamasani13593602012-03-22 16:16:17 -0700611 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700612
Amith Yamasani13593602012-03-22 16:16:17 -0700613 writeUserListLocked();
614 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700615 }
616
617 /*
618 * Writes the user file in this format:
619 *
620 * <user flags="20039023" id="0">
621 * <name>Primary</name>
622 * </user>
623 */
Amith Yamasani13593602012-03-22 16:16:17 -0700624 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700625 FileOutputStream fos = null;
Amith Yamasanifc95e702013-09-26 13:20:17 -0700626 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + XML_SUFFIX));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700627 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700628 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700629 final BufferedOutputStream bos = new BufferedOutputStream(fos);
630
631 // XmlSerializer serializer = XmlUtils.serializerInstance();
632 final XmlSerializer serializer = new FastXmlSerializer();
633 serializer.setOutput(bos, "utf-8");
634 serializer.startDocument(null, true);
635 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
636
637 serializer.startTag(null, TAG_USER);
638 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700639 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700640 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700641 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
642 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
643 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700644 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
645 if (pinState != null) {
646 if (pinState.salt != 0) {
647 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
648 }
649 if (pinState.pinHash != null) {
650 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
651 }
652 if (pinState.failedAttempts != 0) {
653 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
654 Integer.toString(pinState.failedAttempts));
655 serializer.attribute(null, ATTR_LAST_RETRY_MS,
656 Long.toString(pinState.lastAttemptTime));
657 }
658 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700659 if (userInfo.iconPath != null) {
660 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
661 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700662 if (userInfo.partial) {
663 serializer.attribute(null, ATTR_PARTIAL, "true");
664 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700665
666 serializer.startTag(null, TAG_NAME);
667 serializer.text(userInfo.name);
668 serializer.endTag(null, TAG_NAME);
669
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800670 Bundle restrictions = mUserRestrictions.get(userInfo.id);
671 if (restrictions != null) {
672 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700673 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
674 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
675 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
676 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
677 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400678 writeBoolean(serializer, restrictions,
679 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
680 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
681 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400682 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
683 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800684 serializer.endTag(null, TAG_RESTRICTIONS);
685 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700686 serializer.endTag(null, TAG_USER);
687
688 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700689 userFile.finishWrite(fos);
690 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700691 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700692 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700693 }
694 }
695
696 /*
697 * Writes the user list file in this format:
698 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700699 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700700 * <user id="0"></user>
701 * <user id="2"></user>
702 * </users>
703 */
Amith Yamasani13593602012-03-22 16:16:17 -0700704 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700705 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700706 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700707 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700708 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700709 final BufferedOutputStream bos = new BufferedOutputStream(fos);
710
711 // XmlSerializer serializer = XmlUtils.serializerInstance();
712 final XmlSerializer serializer = new FastXmlSerializer();
713 serializer.setOutput(bos, "utf-8");
714 serializer.startDocument(null, true);
715 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
716
717 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700718 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700719 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700720
721 for (int i = 0; i < mUsers.size(); i++) {
722 UserInfo user = mUsers.valueAt(i);
723 serializer.startTag(null, TAG_USER);
724 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
725 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726 }
727
728 serializer.endTag(null, TAG_USERS);
729
730 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700731 userListFile.finishWrite(fos);
732 } catch (Exception e) {
733 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700734 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700735 }
736 }
737
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800738 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700739 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700740 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700742 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700743 long creationTime = 0L;
744 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700745 long salt = 0L;
746 String pinHash = null;
747 int failedAttempts = 0;
748 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700749 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800750 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700751
752 FileInputStream fis = null;
753 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700754 AtomicFile userFile =
Amith Yamasanifc95e702013-09-26 13:20:17 -0700755 new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
Amith Yamasani2a003292012-08-14 18:25:45 -0700756 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757 XmlPullParser parser = Xml.newPullParser();
758 parser.setInput(fis, null);
759 int type;
760 while ((type = parser.next()) != XmlPullParser.START_TAG
761 && type != XmlPullParser.END_DOCUMENT) {
762 ;
763 }
764
765 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700766 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700767 return null;
768 }
769
770 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700771 int storedId = readIntAttribute(parser, ATTR_ID, -1);
772 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700773 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700774 return null;
775 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700776 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
777 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700778 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700779 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
780 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700781 salt = readLongAttribute(parser, ATTR_SALT, 0L);
782 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
783 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
784 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700785 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
786 if ("true".equals(valueString)) {
787 partial = true;
788 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700789
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800790 int outerDepth = parser.getDepth();
791 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
792 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
793 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
794 continue;
795 }
796 String tag = parser.getName();
797 if (TAG_NAME.equals(tag)) {
798 type = parser.next();
799 if (type == XmlPullParser.TEXT) {
800 name = parser.getText();
801 }
802 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700803 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
804 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
805 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
806 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
807 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400808 readBoolean(parser, restrictions,
809 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
810 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
811 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400812 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
813 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700814 }
815 }
816 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700817
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700818 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700819 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700820 userInfo.creationTime = creationTime;
821 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700822 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800823 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700824 if (salt != 0L) {
825 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
826 if (pinState == null) {
827 pinState = new RestrictionsPinState();
828 mRestrictionsPinStates.put(id, pinState);
829 }
830 pinState.salt = salt;
831 pinState.pinHash = pinHash;
832 pinState.failedAttempts = failedAttempts;
833 pinState.lastAttemptTime = lastAttemptTime;
834 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700835 return userInfo;
836
837 } catch (IOException ioe) {
838 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800839 } finally {
840 if (fis != null) {
841 try {
842 fis.close();
843 } catch (IOException e) {
844 }
845 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700846 }
847 return null;
848 }
849
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800850 private void readBoolean(XmlPullParser parser, Bundle restrictions,
851 String restrictionKey) {
852 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700853 if (value != null) {
854 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
855 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800856 }
857
858 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
859 throws IOException {
860 if (restrictions.containsKey(restrictionKey)) {
861 xml.attribute(null, restrictionKey,
862 Boolean.toString(restrictions.getBoolean(restrictionKey)));
863 }
864 }
865
Amith Yamasani920ace02012-09-20 22:15:37 -0700866 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
867 String valueString = parser.getAttributeValue(null, attr);
868 if (valueString == null) return defaultValue;
869 try {
870 return Integer.parseInt(valueString);
871 } catch (NumberFormatException nfe) {
872 return defaultValue;
873 }
874 }
875
876 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
877 String valueString = parser.getAttributeValue(null, attr);
878 if (valueString == null) return defaultValue;
879 try {
880 return Long.parseLong(valueString);
881 } catch (NumberFormatException nfe) {
882 return defaultValue;
883 }
884 }
885
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700886 private boolean isPackageInstalled(String pkg, int userId) {
887 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
888 PackageManager.GET_UNINSTALLED_PACKAGES,
889 userId);
890 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
891 return false;
892 }
893 return true;
894 }
895
Amith Yamasanib82add22013-07-09 11:24:44 -0700896 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700897 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
898 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700899 * Does not do any permissions checking.
900 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700901 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700902 synchronized (mPackagesLock) {
903 File dir = Environment.getUserSystemDirectory(userId);
904 String[] files = dir.list();
905 if (files == null) return;
906 for (String fileName : files) {
907 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
908 File resFile = new File(dir, fileName);
909 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700910 if (all) {
911 resFile.delete();
912 } else {
Amith Yamasanifc95e702013-09-26 13:20:17 -0700913 String pkg = restrictionsFileNameToPackage(fileName);
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700914 if (!isPackageInstalled(pkg, userId)) {
915 resFile.delete();
916 }
917 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700918 }
919 }
920 }
921 }
922 }
923
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700924 /**
925 * Removes the app restrictions file for a specific package and user id, if it exists.
926 */
927 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
928 synchronized (mPackagesLock) {
929 File dir = Environment.getUserSystemDirectory(userId);
Amith Yamasanifc95e702013-09-26 13:20:17 -0700930 File resFile = new File(dir, packageToRestrictionsFileName(pkg));
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700931 if (resFile.exists()) {
932 resFile.delete();
933 }
934 }
935 }
936
Amith Yamasani258848d2012-08-10 17:06:33 -0700937 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700938 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700939 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700940
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700941 final long ident = Binder.clearCallingIdentity();
942 final UserInfo userInfo;
943 try {
944 synchronized (mInstallLock) {
945 synchronized (mPackagesLock) {
946 if (isUserLimitReachedLocked()) return null;
947 int userId = getNextAvailableIdLocked();
948 userInfo = new UserInfo(userId, name, null, flags);
949 File userPath = new File(mBaseUserPath, Integer.toString(userId));
950 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700951 long now = System.currentTimeMillis();
952 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700953 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700954 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700955 mUsers.put(userId, userInfo);
956 writeUserListLocked();
957 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700958 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700959 userInfo.partial = false;
960 writeUserLocked(userInfo);
961 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500962 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500963 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700964 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700965 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700966 if (userInfo != null) {
967 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
968 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
969 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
970 android.Manifest.permission.MANAGE_USERS);
971 }
972 } finally {
973 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700974 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700975 return userInfo;
976 }
977
Amith Yamasani0b285492011-04-14 17:35:23 -0700978 /**
979 * Removes a user and all data directories created for that user. This method should be called
980 * after the user's processes have been terminated.
981 * @param id the user's id
982 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700983 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700984 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700985 final UserInfo user;
986 synchronized (mPackagesLock) {
987 user = mUsers.get(userHandle);
988 if (userHandle == 0 || user == null) {
989 return false;
990 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800991 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700992 // Set this to a partially created user, so that the user will be purged
993 // on next startup, in case the runtime stops now before stopping and
994 // removing the user completely.
995 user.partial = true;
996 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700997 }
Amith Yamasani16389312012-10-17 21:20:14 -0700998 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700999 int res;
1000 try {
1001 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1002 new IStopUserCallback.Stub() {
1003 @Override
1004 public void userStopped(int userId) {
1005 finishRemoveUser(userId);
1006 }
1007 @Override
1008 public void userStopAborted(int userId) {
1009 }
1010 });
1011 } catch (RemoteException e) {
1012 return false;
1013 }
1014
1015 return res == ActivityManager.USER_OP_SUCCESS;
1016 }
1017
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001018 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001019 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001020 // Let other services shutdown any activity and clean up their state before completely
1021 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001022 long ident = Binder.clearCallingIdentity();
1023 try {
1024 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1025 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001026 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1027 android.Manifest.permission.MANAGE_USERS,
1028
1029 new BroadcastReceiver() {
1030 @Override
1031 public void onReceive(Context context, Intent intent) {
1032 if (DBG) {
1033 Slog.i(LOG_TAG,
1034 "USER_REMOVED broadcast sent, cleaning up user data "
1035 + userHandle);
1036 }
1037 new Thread() {
1038 public void run() {
1039 synchronized (mInstallLock) {
1040 synchronized (mPackagesLock) {
1041 removeUserStateLocked(userHandle);
1042 }
1043 }
1044 }
1045 }.start();
1046 }
1047 },
1048
1049 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001050 } finally {
1051 Binder.restoreCallingIdentity(ident);
1052 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001053 }
1054
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001055 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001056 // Cleanup package manager settings
1057 mPm.cleanUpUserLILPw(userHandle);
1058
1059 // Remove this user from the list
1060 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001061
1062 // Have user ID linger for several seconds to let external storage VFS
1063 // cache entries expire. This must be greater than the 'entry_valid'
1064 // timeout used by the FUSE daemon.
1065 mHandler.postDelayed(new Runnable() {
1066 @Override
1067 public void run() {
1068 synchronized (mPackagesLock) {
1069 mRemovingUserIds.delete(userHandle);
1070 }
1071 }
1072 }, MINUTE_IN_MILLIS);
1073
Amith Yamasani655d0e22013-06-12 14:19:10 -07001074 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001075 // Remove user file
Amith Yamasanifc95e702013-09-26 13:20:17 -07001076 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + XML_SUFFIX));
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001077 userFile.delete();
1078 // Update the user list
1079 writeUserListLocked();
1080 updateUserIdsLocked();
1081 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1082 }
1083
Amith Yamasani61f57372012-08-31 12:12:28 -07001084 private void removeDirectoryRecursive(File parent) {
1085 if (parent.isDirectory()) {
1086 String[] files = parent.list();
1087 for (String filename : files) {
1088 File child = new File(parent, filename);
1089 removeDirectoryRecursive(child);
1090 }
1091 }
1092 parent.delete();
1093 }
1094
Amith Yamasani2a003292012-08-14 18:25:45 -07001095 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001096 public Bundle getApplicationRestrictions(String packageName) {
1097 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1098 }
1099
1100 @Override
1101 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001102 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001103 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001104 checkManageUsersPermission("Only system can get restrictions for other users/apps");
1105 }
1106 synchronized (mPackagesLock) {
1107 // Read the restrictions from XML
1108 return readApplicationRestrictionsLocked(packageName, userId);
1109 }
1110 }
1111
1112 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001113 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001114 int userId) {
1115 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001116 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001117 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1118 }
1119 synchronized (mPackagesLock) {
1120 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001121 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001122 }
1123 }
1124
Amith Yamasani655d0e22013-06-12 14:19:10 -07001125 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001126 public boolean setRestrictionsChallenge(String newPin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001127 checkManageUsersPermission("Only system can modify the restrictions pin");
1128 int userId = UserHandle.getCallingUserId();
1129 synchronized (mPackagesLock) {
1130 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1131 if (pinState == null) {
1132 pinState = new RestrictionsPinState();
1133 }
1134 if (newPin == null) {
1135 pinState.salt = 0;
1136 pinState.pinHash = null;
1137 } else {
1138 try {
1139 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1140 } catch (NoSuchAlgorithmException e) {
1141 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1142 }
1143 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1144 pinState.failedAttempts = 0;
1145 }
1146 mRestrictionsPinStates.put(userId, pinState);
1147 writeUserLocked(mUsers.get(userId));
1148 }
1149 return true;
1150 }
1151
1152 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001153 public int checkRestrictionsChallenge(String pin) {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001154 checkManageUsersPermission("Only system can verify the restrictions pin");
1155 int userId = UserHandle.getCallingUserId();
1156 synchronized (mPackagesLock) {
1157 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1158 // If there's no pin set, return error code
1159 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1160 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1161 } else if (pin == null) {
1162 // If just checking if user can be prompted, return remaining time
1163 int waitTime = getRemainingTimeForPinAttempt(pinState);
1164 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1165 return waitTime;
1166 } else {
1167 int waitTime = getRemainingTimeForPinAttempt(pinState);
1168 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1169 if (waitTime > 0) {
1170 return waitTime;
1171 }
1172 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1173 pinState.failedAttempts = 0;
1174 writeUserLocked(mUsers.get(userId));
1175 return UserManager.PIN_VERIFICATION_SUCCESS;
1176 } else {
1177 pinState.failedAttempts++;
1178 pinState.lastAttemptTime = System.currentTimeMillis();
1179 writeUserLocked(mUsers.get(userId));
1180 return waitTime;
1181 }
1182 }
1183 }
1184 }
1185
1186 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1187 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1188 BACKOFF_TIMES.length - 1);
1189 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1190 BACKOFF_TIMES[backoffIndex] : 0;
1191 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1192 0);
1193 }
1194
1195 @Override
Amith Yamasanid304af62013-09-05 09:30:23 -07001196 public boolean hasRestrictionsChallenge() {
Amith Yamasani655d0e22013-06-12 14:19:10 -07001197 int userId = UserHandle.getCallingUserId();
1198 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001199 return hasRestrictionsPinLocked(userId);
1200 }
1201 }
1202
1203 private boolean hasRestrictionsPinLocked(int userId) {
1204 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1205 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1206 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001207 }
1208 return true;
1209 }
1210
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001211 @Override
1212 public void removeRestrictions() {
1213 checkManageUsersPermission("Only system can remove restrictions");
1214 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001215 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001216 }
1217
Amith Yamasani5e486f52013-08-07 11:06:44 -07001218 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001219 synchronized (mPackagesLock) {
1220 // Remove all user restrictions
1221 setUserRestrictions(new Bundle(), userHandle);
1222 // Remove restrictions pin
Amith Yamasanid304af62013-09-05 09:30:23 -07001223 setRestrictionsChallenge(null);
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001224 // Remove any app restrictions
1225 cleanAppRestrictions(userHandle, true);
1226 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001227 if (unblockApps) {
1228 unblockAllAppsForUser(userHandle);
1229 }
1230 }
1231
1232 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001233 mHandler.post(new Runnable() {
1234 @Override
1235 public void run() {
1236 List<ApplicationInfo> apps =
1237 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1238 userHandle).getList();
1239 final long ident = Binder.clearCallingIdentity();
1240 try {
1241 for (ApplicationInfo appInfo : apps) {
1242 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1243 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1244 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1245 userHandle);
1246 }
1247 }
1248 } finally {
1249 Binder.restoreCallingIdentity(ident);
1250 }
1251 }
1252 });
1253 }
1254
Amith Yamasani655d0e22013-06-12 14:19:10 -07001255 /*
1256 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1257 * Not the most secure, but it is at least a second level of protection. First level is that
1258 * the file is in a location only readable by the system process.
1259 * @param password the password.
1260 * @param salt the randomly generated salt
1261 * @return the hash of the pattern in a String.
1262 */
1263 private String passwordToHash(String password, long salt) {
1264 if (password == null) {
1265 return null;
1266 }
1267 String algo = null;
1268 String hashed = salt + password;
1269 try {
1270 byte[] saltedPassword = (password + salt).getBytes();
1271 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1272 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1273 hashed = toHex(sha1) + toHex(md5);
1274 } catch (NoSuchAlgorithmException e) {
1275 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1276 }
1277 return hashed;
1278 }
1279
1280 private static String toHex(byte[] ary) {
1281 final String hex = "0123456789ABCDEF";
1282 String ret = "";
1283 for (int i = 0; i < ary.length; i++) {
1284 ret += hex.charAt((ary[i] >> 4) & 0xf);
1285 ret += hex.charAt(ary[i] & 0xf);
1286 }
1287 return ret;
1288 }
1289
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001290 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001291 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001292 try {
1293 return mContext.getPackageManager().getApplicationInfo(packageName,
1294 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1295 } catch (NameNotFoundException nnfe) {
1296 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001297 } finally {
1298 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001299 }
1300 }
1301
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001302 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001303 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001304 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001305 final ArrayList<String> values = new ArrayList<String>();
1306
1307 FileInputStream fis = null;
1308 try {
1309 AtomicFile restrictionsFile =
1310 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001311 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001312 fis = restrictionsFile.openRead();
1313 XmlPullParser parser = Xml.newPullParser();
1314 parser.setInput(fis, null);
1315 int type;
1316 while ((type = parser.next()) != XmlPullParser.START_TAG
1317 && type != XmlPullParser.END_DOCUMENT) {
1318 ;
1319 }
1320
1321 if (type != XmlPullParser.START_TAG) {
1322 Slog.e(LOG_TAG, "Unable to read restrictions file "
1323 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001324 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001325 }
1326
1327 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1328 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1329 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001330 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001331 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1332 if (multiple != null) {
1333 int count = Integer.parseInt(multiple);
1334 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1335 if (type == XmlPullParser.START_TAG
1336 && parser.getName().equals(TAG_VALUE)) {
1337 values.add(parser.nextText().trim());
1338 count--;
1339 }
1340 }
1341 String [] valueStrings = new String[values.size()];
1342 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001343 restrictions.putStringArray(key, valueStrings);
1344 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1345 restrictions.putBoolean(key, Boolean.parseBoolean(
1346 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001347 } else {
1348 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001349 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001350 }
1351 }
1352 }
1353
1354 } catch (IOException ioe) {
1355 } catch (XmlPullParserException pe) {
1356 } finally {
1357 if (fis != null) {
1358 try {
1359 fis.close();
1360 } catch (IOException e) {
1361 }
1362 }
1363 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001364 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001365 }
1366
1367 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001368 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001369 FileOutputStream fos = null;
1370 AtomicFile restrictionsFile = new AtomicFile(
1371 new File(Environment.getUserSystemDirectory(userId),
Amith Yamasanifc95e702013-09-26 13:20:17 -07001372 packageToRestrictionsFileName(packageName)));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001373 try {
1374 fos = restrictionsFile.startWrite();
1375 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1376
1377 // XmlSerializer serializer = XmlUtils.serializerInstance();
1378 final XmlSerializer serializer = new FastXmlSerializer();
1379 serializer.setOutput(bos, "utf-8");
1380 serializer.startDocument(null, true);
1381 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1382
1383 serializer.startTag(null, TAG_RESTRICTIONS);
1384
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001385 for (String key : restrictions.keySet()) {
1386 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001387 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001388 serializer.attribute(null, ATTR_KEY, key);
1389
1390 if (value instanceof Boolean) {
1391 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1392 serializer.text(value.toString());
1393 } else if (value == null || value instanceof String) {
1394 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1395 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001396 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001397 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1398 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001399 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001400 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001401 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001402 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001403 serializer.endTag(null, TAG_VALUE);
1404 }
1405 }
1406 serializer.endTag(null, TAG_ENTRY);
1407 }
1408
1409 serializer.endTag(null, TAG_RESTRICTIONS);
1410
1411 serializer.endDocument();
1412 restrictionsFile.finishWrite(fos);
1413 } catch (Exception e) {
1414 restrictionsFile.failWrite(fos);
1415 Slog.e(LOG_TAG, "Error writing application restrictions list");
1416 }
1417 }
1418
1419 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001420 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001421 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001422 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001423 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001424 }
1425 }
1426
1427 @Override
1428 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001429 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001430 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001431 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001432 }
1433 // Not found
1434 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001435 }
1436 }
1437
Amith Yamasani0b285492011-04-14 17:35:23 -07001438 /**
1439 * Caches the list of user ids in an array, adjusting the array size when necessary.
1440 */
Amith Yamasani13593602012-03-22 16:16:17 -07001441 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001442 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001443 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001444 if (!mUsers.valueAt(i).partial) {
1445 num++;
1446 }
1447 }
Amith Yamasani16389312012-10-17 21:20:14 -07001448 final int[] newUsers = new int[num];
1449 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001450 for (int i = 0; i < mUsers.size(); i++) {
1451 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001452 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001453 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001454 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001455 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001456 }
1457
1458 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001459 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001460 * @param userId the user that was just foregrounded
1461 */
1462 public void userForeground(int userId) {
1463 synchronized (mPackagesLock) {
1464 UserInfo user = mUsers.get(userId);
1465 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001466 if (user == null || user.partial) {
1467 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1468 return;
1469 }
1470 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001471 user.lastLoggedInTime = now;
1472 writeUserLocked(user);
1473 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001474 // If this is not a restricted profile and there is no restrictions pin, clean up
1475 // all restrictions files that might have been left behind, else clean up just the
1476 // ones with uninstalled packages
1477 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1478 final long salt = pinState == null ? 0 : pinState.salt;
1479 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001480 }
1481 }
1482
1483 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001484 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001485 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1486 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001487 * @return
1488 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001489 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001490 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001491 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001492 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001493 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001494 break;
1495 }
1496 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001497 }
Amith Yamasani195263742012-08-21 15:40:12 -07001498 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001499 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001500 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001501
Amith Yamasanifc95e702013-09-26 13:20:17 -07001502 private String packageToRestrictionsFileName(String packageName) {
1503 return RESTRICTIONS_FILE_PREFIX + packageName + XML_SUFFIX;
1504 }
1505
1506 private String restrictionsFileNameToPackage(String fileName) {
1507 return fileName.substring(RESTRICTIONS_FILE_PREFIX.length(),
1508 (int) (fileName.length() - XML_SUFFIX.length()));
1509 }
1510
Amith Yamasani920ace02012-09-20 22:15:37 -07001511 @Override
1512 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1513 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1514 != PackageManager.PERMISSION_GRANTED) {
1515 pw.println("Permission Denial: can't dump UserManager from from pid="
1516 + Binder.getCallingPid()
1517 + ", uid=" + Binder.getCallingUid()
1518 + " without permission "
1519 + android.Manifest.permission.DUMP);
1520 return;
1521 }
1522
1523 long now = System.currentTimeMillis();
1524 StringBuilder sb = new StringBuilder();
1525 synchronized (mPackagesLock) {
1526 pw.println("Users:");
1527 for (int i = 0; i < mUsers.size(); i++) {
1528 UserInfo user = mUsers.valueAt(i);
1529 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001530 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001531 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001532 if (user.partial) pw.print(" <partial>");
1533 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001534 pw.print(" Created: ");
1535 if (user.creationTime == 0) {
1536 pw.println("<unknown>");
1537 } else {
1538 sb.setLength(0);
1539 TimeUtils.formatDuration(now - user.creationTime, sb);
1540 sb.append(" ago");
1541 pw.println(sb);
1542 }
1543 pw.print(" Last logged in: ");
1544 if (user.lastLoggedInTime == 0) {
1545 pw.println("<unknown>");
1546 } else {
1547 sb.setLength(0);
1548 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1549 sb.append(" ago");
1550 pw.println(sb);
1551 }
1552 }
1553 }
1554 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001555
1556 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1557 @Override
1558 public void onPackageRemoved(String pkg, int uid) {
1559 final int userId = this.getChangingUserId();
1560 // Package could be disappearing because it is being blocked, so also check if
1561 // it has been uninstalled.
1562 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1563 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1564 cleanAppRestrictionsForPackage(pkg, userId);
1565 }
1566 }
1567 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001568}