blob: af60f8467f51f703ff16c3167220d152da7ddba6 [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_";
113
Amith Yamasani634cf312012-10-04 17:34:21 -0700114 private static final int MIN_USER_ID = 10;
115
Amith Yamasani5e486f52013-08-07 11:06:44 -0700116 private static final int USER_VERSION = 4;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700117
Amith Yamasani920ace02012-09-20 22:15:37 -0700118 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
119
Amith Yamasani655d0e22013-06-12 14:19:10 -0700120 // Number of attempts before jumping to the next BACKOFF_TIMES slot
121 private static final int BACKOFF_INC_INTERVAL = 5;
122
123 // Amount of time to force the user to wait before entering the PIN again, after failing
124 // BACKOFF_INC_INTERVAL times.
125 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
126
Dianne Hackborn4428e172012-08-24 17:43:05 -0700127 private final Context mContext;
128 private final PackageManagerService mPm;
129 private final Object mInstallLock;
130 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700131
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800132 private final Handler mHandler;
133
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134 private final File mUsersDir;
135 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700136 private final File mBaseUserPath;
137
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800138 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800139 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800140
Amith Yamasani655d0e22013-06-12 14:19:10 -0700141 class RestrictionsPinState {
142 long salt;
143 String pinHash;
144 int failedAttempts;
145 long lastAttemptTime;
146 }
147
148 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
149 new SparseArray<RestrictionsPinState>();
150
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800151 /**
152 * Set of user IDs being actively removed. Removed IDs linger in this set
153 * for several seconds to work around a VFS caching issue.
154 */
155 // @GuardedBy("mPackagesLock")
156 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700157
Amith Yamasani0b285492011-04-14 17:35:23 -0700158 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700159 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700160 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700161 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700162
Amith Yamasani258848d2012-08-10 17:06:33 -0700163 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700164
Dianne Hackborn4428e172012-08-24 17:43:05 -0700165 public static UserManagerService getInstance() {
166 synchronized (UserManagerService.class) {
167 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700168 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700169 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700170
171 /**
172 * Available for testing purposes.
173 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700175 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700176 }
177
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 /**
179 * Called by package manager to create the service. This is closely
180 * associated with the package manager, and the given lock is the
181 * package manager's own lock.
182 */
183 UserManagerService(Context context, PackageManagerService pm,
184 Object installLock, Object packagesLock) {
185 this(context, pm, installLock, packagesLock,
186 Environment.getDataDirectory(),
187 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700188 }
189
Dianne Hackborn4428e172012-08-24 17:43:05 -0700190 /**
191 * Available for testing purposes.
192 */
193 private UserManagerService(Context context, PackageManagerService pm,
194 Object installLock, Object packagesLock,
195 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700196 mContext = context;
197 mPm = pm;
198 mInstallLock = installLock;
199 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800200 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700201 synchronized (mInstallLock) {
202 synchronized (mPackagesLock) {
203 mUsersDir = new File(dataDir, USER_INFO_DIR);
204 mUsersDir.mkdirs();
205 // Make zeroth user directory, for services to migrate their files to that location
206 File userZeroDir = new File(mUsersDir, "0");
207 userZeroDir.mkdirs();
208 mBaseUserPath = baseUserPath;
209 FileUtils.setPermissions(mUsersDir.toString(),
210 FileUtils.S_IRWXU|FileUtils.S_IRWXG
211 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
212 -1, -1);
213 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
214 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700215 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700216 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
217 for (int i = 0; i < mUsers.size(); i++) {
218 UserInfo ui = mUsers.valueAt(i);
219 if (ui.partial && i != 0) {
220 partials.add(ui);
221 }
222 }
223 for (int i = 0; i < partials.size(); i++) {
224 UserInfo ui = partials.get(i);
225 Slog.w(LOG_TAG, "Removing partially created user #" + i
226 + " (name=" + ui.name + ")");
227 removeUserStateLocked(ui.id);
228 }
229 sInstance = this;
230 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700231 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700232 }
233
234 void systemReady() {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700235 final Context context = ActivityThread.systemMain().getSystemContext();
236 mUserPackageMonitor.register(context,
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700237 null, UserHandle.ALL, false);
238 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700239 }
240
241 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700242 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700243 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700244 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700245 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
246 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700247 UserInfo ui = mUsers.valueAt(i);
248 if (ui.partial) {
249 continue;
250 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800251 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700252 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700253 }
Amith Yamasani13593602012-03-22 16:16:17 -0700254 }
255 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700256 }
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258
Amith Yamasani258848d2012-08-10 17:06:33 -0700259 @Override
260 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700261 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700262 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700263 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700264 }
265 }
266
Amith Yamasani71e6c692013-03-24 17:39:28 -0700267 @Override
268 public boolean isRestricted() {
269 synchronized (mPackagesLock) {
270 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
271 }
272 }
273
Amith Yamasani195263742012-08-21 15:40:12 -0700274 /*
275 * Should be locked on mUsers before calling this.
276 */
277 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700278 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700279 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800280 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
282 return null;
283 }
284 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700285 }
286
Amith Yamasani13593602012-03-22 16:16:17 -0700287 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700288 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700289 return ArrayUtils.contains(mUserIds, userId);
290 }
291 }
292
Amith Yamasani258848d2012-08-10 17:06:33 -0700293 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700294 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700295 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700296 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700297 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700298 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700299 if (info == null || info.partial) {
300 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
301 return;
302 }
Amith Yamasani13593602012-03-22 16:16:17 -0700303 if (name != null && !name.equals(info.name)) {
304 info.name = name;
305 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700306 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700307 }
308 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700309 if (changed) {
310 sendUserInfoChangedBroadcast(userId);
311 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700312 }
313
Amith Yamasani258848d2012-08-10 17:06:33 -0700314 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700315 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700316 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700317 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700318 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700319 if (info == null || info.partial) {
320 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
321 return;
322 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700323 writeBitmapLocked(info, bitmap);
324 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700325 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700326 sendUserInfoChangedBroadcast(userId);
327 }
328
329 private void sendUserInfoChangedBroadcast(int userId) {
330 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
331 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
332 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700333 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700334 }
335
Amith Yamasani258848d2012-08-10 17:06:33 -0700336 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700337 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700338 checkManageUsersPermission("read users");
339 synchronized (mPackagesLock) {
340 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700341 if (info == null || info.partial) {
342 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
343 return null;
344 }
345 if (info.iconPath == null) {
346 return null;
347 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700348 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700349 }
350 }
351
352 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700353 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700354 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700355 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700356 if (mGuestEnabled != enable) {
357 mGuestEnabled = enable;
358 // Erase any guest user that currently exists
359 for (int i = 0; i < mUsers.size(); i++) {
360 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700361 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 if (!enable) {
363 removeUser(user.id);
364 }
365 return;
366 }
367 }
368 // No guest was found
369 if (enable) {
370 createUser("Guest", UserInfo.FLAG_GUEST);
371 }
372 }
373 }
374 }
375
376 @Override
377 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700378 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700379 return mGuestEnabled;
380 }
381 }
382
383 @Override
384 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700385 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700386 // TODO:
387 }
388
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700389 public void makeInitialized(int userId) {
390 checkManageUsersPermission("makeInitialized");
391 synchronized (mPackagesLock) {
392 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700393 if (info == null || info.partial) {
394 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
395 }
396 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700397 info.flags |= UserInfo.FLAG_INITIALIZED;
398 writeUserLocked(info);
399 }
400 }
401 }
402
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800403 @Override
404 public Bundle getUserRestrictions(int userId) {
405 // checkManageUsersPermission("getUserRestrictions");
406
407 synchronized (mPackagesLock) {
408 Bundle restrictions = mUserRestrictions.get(userId);
409 return restrictions != null ? restrictions : Bundle.EMPTY;
410 }
411 }
412
413 @Override
414 public void setUserRestrictions(Bundle restrictions, int userId) {
415 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700416 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800417
418 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -0700419 // If the user has restrictions already and call is trying to disallow restrictions,
420 // don't modify the flag.
421 if (hasRestrictionsPinLocked(userId)
422 && restrictions.getBoolean(UserManager.DISALLOW_APP_RESTRICTIONS, false)) {
423 restrictions.putBoolean(UserManager.DISALLOW_APP_RESTRICTIONS, false);
424 }
Amith Yamasani350962c2013-08-06 11:18:53 -0700425 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800426 mUserRestrictions.get(userId).putAll(restrictions);
427 writeUserLocked(mUsers.get(userId));
428 }
429 }
430
Amith Yamasani258848d2012-08-10 17:06:33 -0700431 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700432 * Check if we've hit the limit of how many users can be created.
433 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700434 private boolean isUserLimitReachedLocked() {
435 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700436 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700437 }
438
439 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700440 * Enforces that only the system UID or root's UID or apps that have the
441 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
442 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700443 *
444 * @param message used as message if SecurityException is thrown
445 * @throws SecurityException if the caller is not system or root
446 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700447 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700448 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700449 if (uid != Process.SYSTEM_UID && uid != 0
450 && ActivityManager.checkComponentPermission(
451 android.Manifest.permission.MANAGE_USERS,
452 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
453 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700454 }
455 }
456
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700457 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700458 try {
459 File dir = new File(mUsersDir, Integer.toString(info.id));
460 File file = new File(dir, USER_PHOTO_FILENAME);
461 if (!dir.exists()) {
462 dir.mkdir();
463 FileUtils.setPermissions(
464 dir.getPath(),
465 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
466 -1, -1);
467 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700468 FileOutputStream os;
469 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700470 info.iconPath = file.getAbsolutePath();
471 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700472 try {
473 os.close();
474 } catch (IOException ioe) {
475 // What the ... !
476 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700477 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700478 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700479 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700480 }
481
Amith Yamasani0b285492011-04-14 17:35:23 -0700482 /**
483 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
484 * cache it elsewhere.
485 * @return the array of user ids.
486 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700487 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700488 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700489 return mUserIds;
490 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700491 }
492
Dianne Hackborn4428e172012-08-24 17:43:05 -0700493 int[] getUserIdsLPr() {
494 return mUserIds;
495 }
496
Amith Yamasani13593602012-03-22 16:16:17 -0700497 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700498 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700499 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700500 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700501 return;
502 }
503 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700504 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700505 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700506 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700507 XmlPullParser parser = Xml.newPullParser();
508 parser.setInput(fis, null);
509 int type;
510 while ((type = parser.next()) != XmlPullParser.START_TAG
511 && type != XmlPullParser.END_DOCUMENT) {
512 ;
513 }
514
515 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700516 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700517 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700518 return;
519 }
520
Amith Yamasani2a003292012-08-14 18:25:45 -0700521 mNextSerialNumber = -1;
522 if (parser.getName().equals(TAG_USERS)) {
523 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
524 if (lastSerialNumber != null) {
525 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
526 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700527 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
528 if (versionNumber != null) {
529 mUserVersion = Integer.parseInt(versionNumber);
530 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700531 }
532
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700533 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
534 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
535 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800536 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700537
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700538 if (user != null) {
539 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700540 if (user.isGuest()) {
541 mGuestEnabled = true;
542 }
543 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
544 mNextSerialNumber = user.id + 1;
545 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700546 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700547 }
548 }
Amith Yamasani13593602012-03-22 16:16:17 -0700549 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700550 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700551 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700552 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700553 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700554 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800555 } finally {
556 if (fis != null) {
557 try {
558 fis.close();
559 } catch (IOException e) {
560 }
561 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700562 }
563 }
564
Amith Yamasani6f34b412012-10-22 18:19:27 -0700565 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800566 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700567 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700568 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700569 int userVersion = mUserVersion;
570 if (userVersion < 1) {
571 // Assign a proper name for the owner, if not initialized correctly before
572 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
573 if ("Primary".equals(user.name)) {
574 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
575 writeUserLocked(user);
576 }
577 userVersion = 1;
578 }
579
Amith Yamasanibc9625052012-11-15 14:39:18 -0800580 if (userVersion < 2) {
581 // Owner should be marked as initialized
582 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
583 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
584 user.flags |= UserInfo.FLAG_INITIALIZED;
585 writeUserLocked(user);
586 }
587 userVersion = 2;
588 }
589
Amith Yamasani350962c2013-08-06 11:18:53 -0700590
Amith Yamasani5e486f52013-08-07 11:06:44 -0700591 if (userVersion < 4) {
Amith Yamasani5e486f52013-08-07 11:06:44 -0700592 userVersion = 4;
593 }
594
Amith Yamasani6f34b412012-10-22 18:19:27 -0700595 if (userVersion < USER_VERSION) {
596 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
597 + USER_VERSION);
598 } else {
599 mUserVersion = userVersion;
600 writeUserListLocked();
601 }
602 }
603
Amith Yamasani13593602012-03-22 16:16:17 -0700604 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700605 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800606 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700607 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700608 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700609 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700610 mNextSerialNumber = MIN_USER_ID;
Geoffrey Borggaard15b8b2c2013-08-28 22:11:10 -0400611 mUserVersion = USER_VERSION;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800612
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500613 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800614 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
615
Amith Yamasani13593602012-03-22 16:16:17 -0700616 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700617
Amith Yamasani13593602012-03-22 16:16:17 -0700618 writeUserListLocked();
619 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700620 }
621
622 /*
623 * Writes the user file in this format:
624 *
625 * <user flags="20039023" id="0">
626 * <name>Primary</name>
627 * </user>
628 */
Amith Yamasani13593602012-03-22 16:16:17 -0700629 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700630 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700631 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700633 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700634 final BufferedOutputStream bos = new BufferedOutputStream(fos);
635
636 // XmlSerializer serializer = XmlUtils.serializerInstance();
637 final XmlSerializer serializer = new FastXmlSerializer();
638 serializer.setOutput(bos, "utf-8");
639 serializer.startDocument(null, true);
640 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
641
642 serializer.startTag(null, TAG_USER);
643 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700644 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700645 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700646 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
647 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
648 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700649 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
650 if (pinState != null) {
651 if (pinState.salt != 0) {
652 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
653 }
654 if (pinState.pinHash != null) {
655 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
656 }
657 if (pinState.failedAttempts != 0) {
658 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
659 Integer.toString(pinState.failedAttempts));
660 serializer.attribute(null, ATTR_LAST_RETRY_MS,
661 Long.toString(pinState.lastAttemptTime));
662 }
663 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700664 if (userInfo.iconPath != null) {
665 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
666 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700667 if (userInfo.partial) {
668 serializer.attribute(null, ATTR_PARTIAL, "true");
669 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700670
671 serializer.startTag(null, TAG_NAME);
672 serializer.text(userInfo.name);
673 serializer.endTag(null, TAG_NAME);
674
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800675 Bundle restrictions = mUserRestrictions.get(userInfo.id);
676 if (restrictions != null) {
677 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700678 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
679 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
680 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
681 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
682 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400683 writeBoolean(serializer, restrictions,
684 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
685 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
686 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400687 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
688 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani0343ec32013-07-22 14:52:06 -0700689 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APP_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800690 serializer.endTag(null, TAG_RESTRICTIONS);
691 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700692 serializer.endTag(null, TAG_USER);
693
694 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700695 userFile.finishWrite(fos);
696 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700697 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700698 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700699 }
700 }
701
702 /*
703 * Writes the user list file in this format:
704 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700705 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700706 * <user id="0"></user>
707 * <user id="2"></user>
708 * </users>
709 */
Amith Yamasani13593602012-03-22 16:16:17 -0700710 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700711 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700712 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700713 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700714 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700715 final BufferedOutputStream bos = new BufferedOutputStream(fos);
716
717 // XmlSerializer serializer = XmlUtils.serializerInstance();
718 final XmlSerializer serializer = new FastXmlSerializer();
719 serializer.setOutput(bos, "utf-8");
720 serializer.startDocument(null, true);
721 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
722
723 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700724 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700725 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700726
727 for (int i = 0; i < mUsers.size(); i++) {
728 UserInfo user = mUsers.valueAt(i);
729 serializer.startTag(null, TAG_USER);
730 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
731 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700732 }
733
734 serializer.endTag(null, TAG_USERS);
735
736 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700737 userListFile.finishWrite(fos);
738 } catch (Exception e) {
739 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700740 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741 }
742 }
743
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800744 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700745 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700746 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700747 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700748 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700749 long creationTime = 0L;
750 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700751 long salt = 0L;
752 String pinHash = null;
753 int failedAttempts = 0;
754 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700755 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800756 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700757
758 FileInputStream fis = null;
759 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700760 AtomicFile userFile =
761 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
762 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700763 XmlPullParser parser = Xml.newPullParser();
764 parser.setInput(fis, null);
765 int type;
766 while ((type = parser.next()) != XmlPullParser.START_TAG
767 && type != XmlPullParser.END_DOCUMENT) {
768 ;
769 }
770
771 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700772 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700773 return null;
774 }
775
776 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700777 int storedId = readIntAttribute(parser, ATTR_ID, -1);
778 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700779 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700780 return null;
781 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700782 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
783 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700784 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700785 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
786 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700787 salt = readLongAttribute(parser, ATTR_SALT, 0L);
788 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
789 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
790 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700791 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
792 if ("true".equals(valueString)) {
793 partial = true;
794 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700795
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800796 int outerDepth = parser.getDepth();
797 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
798 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
799 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
800 continue;
801 }
802 String tag = parser.getName();
803 if (TAG_NAME.equals(tag)) {
804 type = parser.next();
805 if (type == XmlPullParser.TEXT) {
806 name = parser.getText();
807 }
808 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700809 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
810 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
811 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
812 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
813 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400814 readBoolean(parser, restrictions,
815 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
816 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
817 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400818 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
819 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani0343ec32013-07-22 14:52:06 -0700820 readBoolean(parser, restrictions, UserManager.DISALLOW_APP_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700821 }
822 }
823 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700824
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700825 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700826 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700827 userInfo.creationTime = creationTime;
828 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700829 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800830 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700831 if (salt != 0L) {
832 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
833 if (pinState == null) {
834 pinState = new RestrictionsPinState();
835 mRestrictionsPinStates.put(id, pinState);
836 }
837 pinState.salt = salt;
838 pinState.pinHash = pinHash;
839 pinState.failedAttempts = failedAttempts;
840 pinState.lastAttemptTime = lastAttemptTime;
841 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700842 return userInfo;
843
844 } catch (IOException ioe) {
845 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800846 } finally {
847 if (fis != null) {
848 try {
849 fis.close();
850 } catch (IOException e) {
851 }
852 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700853 }
854 return null;
855 }
856
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800857 private void readBoolean(XmlPullParser parser, Bundle restrictions,
858 String restrictionKey) {
859 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700860 if (value != null) {
861 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
862 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800863 }
864
865 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
866 throws IOException {
867 if (restrictions.containsKey(restrictionKey)) {
868 xml.attribute(null, restrictionKey,
869 Boolean.toString(restrictions.getBoolean(restrictionKey)));
870 }
871 }
872
Amith Yamasani920ace02012-09-20 22:15:37 -0700873 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
874 String valueString = parser.getAttributeValue(null, attr);
875 if (valueString == null) return defaultValue;
876 try {
877 return Integer.parseInt(valueString);
878 } catch (NumberFormatException nfe) {
879 return defaultValue;
880 }
881 }
882
883 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
884 String valueString = parser.getAttributeValue(null, attr);
885 if (valueString == null) return defaultValue;
886 try {
887 return Long.parseLong(valueString);
888 } catch (NumberFormatException nfe) {
889 return defaultValue;
890 }
891 }
892
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700893 private boolean isPackageInstalled(String pkg, int userId) {
894 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
895 PackageManager.GET_UNINSTALLED_PACKAGES,
896 userId);
897 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
898 return false;
899 }
900 return true;
901 }
902
Amith Yamasanib82add22013-07-09 11:24:44 -0700903 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700904 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
905 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700906 * Does not do any permissions checking.
907 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700908 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700909 synchronized (mPackagesLock) {
910 File dir = Environment.getUserSystemDirectory(userId);
911 String[] files = dir.list();
912 if (files == null) return;
913 for (String fileName : files) {
914 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
915 File resFile = new File(dir, fileName);
916 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700917 if (all) {
918 resFile.delete();
919 } else {
920 String pkg = fileName.substring(RESTRICTIONS_FILE_PREFIX.length());
921 if (!isPackageInstalled(pkg, userId)) {
922 resFile.delete();
923 }
924 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700925 }
926 }
927 }
928 }
929 }
930
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700931 /**
932 * Removes the app restrictions file for a specific package and user id, if it exists.
933 */
934 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
935 synchronized (mPackagesLock) {
936 File dir = Environment.getUserSystemDirectory(userId);
937 File resFile = new File(dir, RESTRICTIONS_FILE_PREFIX + pkg);
938 if (resFile.exists()) {
939 resFile.delete();
940 }
941 }
942 }
943
Amith Yamasani258848d2012-08-10 17:06:33 -0700944 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700945 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700946 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700947
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700948 final long ident = Binder.clearCallingIdentity();
949 final UserInfo userInfo;
950 try {
951 synchronized (mInstallLock) {
952 synchronized (mPackagesLock) {
953 if (isUserLimitReachedLocked()) return null;
954 int userId = getNextAvailableIdLocked();
955 userInfo = new UserInfo(userId, name, null, flags);
956 File userPath = new File(mBaseUserPath, Integer.toString(userId));
957 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700958 long now = System.currentTimeMillis();
959 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700960 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700961 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700962 mUsers.put(userId, userInfo);
963 writeUserListLocked();
964 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700965 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700966 userInfo.partial = false;
967 writeUserLocked(userInfo);
968 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500969 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500970 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700971 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700972 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700973 if (userInfo != null) {
974 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
975 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
976 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
977 android.Manifest.permission.MANAGE_USERS);
978 }
979 } finally {
980 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700981 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700982 return userInfo;
983 }
984
Amith Yamasani0b285492011-04-14 17:35:23 -0700985 /**
986 * Removes a user and all data directories created for that user. This method should be called
987 * after the user's processes have been terminated.
988 * @param id the user's id
989 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700990 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700991 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700992 final UserInfo user;
993 synchronized (mPackagesLock) {
994 user = mUsers.get(userHandle);
995 if (userHandle == 0 || user == null) {
996 return false;
997 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800998 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -0700999 // Set this to a partially created user, so that the user will be purged
1000 // on next startup, in case the runtime stops now before stopping and
1001 // removing the user completely.
1002 user.partial = true;
1003 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001004 }
Amith Yamasani16389312012-10-17 21:20:14 -07001005 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001006 int res;
1007 try {
1008 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1009 new IStopUserCallback.Stub() {
1010 @Override
1011 public void userStopped(int userId) {
1012 finishRemoveUser(userId);
1013 }
1014 @Override
1015 public void userStopAborted(int userId) {
1016 }
1017 });
1018 } catch (RemoteException e) {
1019 return false;
1020 }
1021
1022 return res == ActivityManager.USER_OP_SUCCESS;
1023 }
1024
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001025 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001026 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001027 // Let other services shutdown any activity and clean up their state before completely
1028 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001029 long ident = Binder.clearCallingIdentity();
1030 try {
1031 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1032 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001033 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1034 android.Manifest.permission.MANAGE_USERS,
1035
1036 new BroadcastReceiver() {
1037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 if (DBG) {
1040 Slog.i(LOG_TAG,
1041 "USER_REMOVED broadcast sent, cleaning up user data "
1042 + userHandle);
1043 }
1044 new Thread() {
1045 public void run() {
1046 synchronized (mInstallLock) {
1047 synchronized (mPackagesLock) {
1048 removeUserStateLocked(userHandle);
1049 }
1050 }
1051 }
1052 }.start();
1053 }
1054 },
1055
1056 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001057 } finally {
1058 Binder.restoreCallingIdentity(ident);
1059 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001060 }
1061
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001062 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001063 // Cleanup package manager settings
1064 mPm.cleanUpUserLILPw(userHandle);
1065
1066 // Remove this user from the list
1067 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001068
1069 // Have user ID linger for several seconds to let external storage VFS
1070 // cache entries expire. This must be greater than the 'entry_valid'
1071 // timeout used by the FUSE daemon.
1072 mHandler.postDelayed(new Runnable() {
1073 @Override
1074 public void run() {
1075 synchronized (mPackagesLock) {
1076 mRemovingUserIds.delete(userHandle);
1077 }
1078 }
1079 }, MINUTE_IN_MILLIS);
1080
Amith Yamasani655d0e22013-06-12 14:19:10 -07001081 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001082 // Remove user file
1083 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
1084 userFile.delete();
1085 // Update the user list
1086 writeUserListLocked();
1087 updateUserIdsLocked();
1088 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1089 }
1090
Amith Yamasani61f57372012-08-31 12:12:28 -07001091 private void removeDirectoryRecursive(File parent) {
1092 if (parent.isDirectory()) {
1093 String[] files = parent.list();
1094 for (String filename : files) {
1095 File child = new File(parent, filename);
1096 removeDirectoryRecursive(child);
1097 }
1098 }
1099 parent.delete();
1100 }
1101
Amith Yamasani2a003292012-08-14 18:25:45 -07001102 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001103 public Bundle getApplicationRestrictions(String packageName) {
1104 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1105 }
1106
1107 @Override
1108 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001109 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001110 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001111 checkManageUsersPermission("Only system can get restrictions for other users/apps");
1112 }
1113 synchronized (mPackagesLock) {
1114 // Read the restrictions from XML
1115 return readApplicationRestrictionsLocked(packageName, userId);
1116 }
1117 }
1118
1119 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001120 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001121 int userId) {
1122 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001123 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001124 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1125 }
1126 synchronized (mPackagesLock) {
1127 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001128 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001129 }
1130 }
1131
Amith Yamasani655d0e22013-06-12 14:19:10 -07001132 @Override
1133 public boolean changeRestrictionsPin(String newPin) {
1134 checkManageUsersPermission("Only system can modify the restrictions pin");
1135 int userId = UserHandle.getCallingUserId();
1136 synchronized (mPackagesLock) {
1137 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1138 if (pinState == null) {
1139 pinState = new RestrictionsPinState();
1140 }
1141 if (newPin == null) {
1142 pinState.salt = 0;
1143 pinState.pinHash = null;
1144 } else {
1145 try {
1146 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1147 } catch (NoSuchAlgorithmException e) {
1148 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1149 }
1150 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1151 pinState.failedAttempts = 0;
1152 }
1153 mRestrictionsPinStates.put(userId, pinState);
1154 writeUserLocked(mUsers.get(userId));
1155 }
1156 return true;
1157 }
1158
1159 @Override
1160 public int checkRestrictionsPin(String pin) {
1161 checkManageUsersPermission("Only system can verify the restrictions pin");
1162 int userId = UserHandle.getCallingUserId();
1163 synchronized (mPackagesLock) {
1164 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1165 // If there's no pin set, return error code
1166 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1167 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1168 } else if (pin == null) {
1169 // If just checking if user can be prompted, return remaining time
1170 int waitTime = getRemainingTimeForPinAttempt(pinState);
1171 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1172 return waitTime;
1173 } else {
1174 int waitTime = getRemainingTimeForPinAttempt(pinState);
1175 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1176 if (waitTime > 0) {
1177 return waitTime;
1178 }
1179 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1180 pinState.failedAttempts = 0;
1181 writeUserLocked(mUsers.get(userId));
1182 return UserManager.PIN_VERIFICATION_SUCCESS;
1183 } else {
1184 pinState.failedAttempts++;
1185 pinState.lastAttemptTime = System.currentTimeMillis();
1186 writeUserLocked(mUsers.get(userId));
1187 return waitTime;
1188 }
1189 }
1190 }
1191 }
1192
1193 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1194 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1195 BACKOFF_TIMES.length - 1);
1196 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1197 BACKOFF_TIMES[backoffIndex] : 0;
1198 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1199 0);
1200 }
1201
1202 @Override
1203 public boolean hasRestrictionsPin() {
1204 int userId = UserHandle.getCallingUserId();
1205 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001206 return hasRestrictionsPinLocked(userId);
1207 }
1208 }
1209
1210 private boolean hasRestrictionsPinLocked(int userId) {
1211 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1212 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1213 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001214 }
1215 return true;
1216 }
1217
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001218 @Override
1219 public void removeRestrictions() {
1220 checkManageUsersPermission("Only system can remove restrictions");
1221 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani5e486f52013-08-07 11:06:44 -07001222 removeRestrictionsForUser(userHandle, true);
Amith Yamasani350962c2013-08-06 11:18:53 -07001223 }
1224
Amith Yamasani5e486f52013-08-07 11:06:44 -07001225 private void removeRestrictionsForUser(final int userHandle, boolean unblockApps) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001226 synchronized (mPackagesLock) {
1227 // Remove all user restrictions
1228 setUserRestrictions(new Bundle(), userHandle);
1229 // Remove restrictions pin
1230 changeRestrictionsPin(null);
1231 // Remove any app restrictions
1232 cleanAppRestrictions(userHandle, true);
1233 }
Amith Yamasani5e486f52013-08-07 11:06:44 -07001234 if (unblockApps) {
1235 unblockAllAppsForUser(userHandle);
1236 }
1237 }
1238
1239 private void unblockAllAppsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001240 mHandler.post(new Runnable() {
1241 @Override
1242 public void run() {
1243 List<ApplicationInfo> apps =
1244 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1245 userHandle).getList();
1246 final long ident = Binder.clearCallingIdentity();
1247 try {
1248 for (ApplicationInfo appInfo : apps) {
1249 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1250 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1251 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1252 userHandle);
1253 }
1254 }
1255 } finally {
1256 Binder.restoreCallingIdentity(ident);
1257 }
1258 }
1259 });
1260 }
1261
Amith Yamasani655d0e22013-06-12 14:19:10 -07001262 /*
1263 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1264 * Not the most secure, but it is at least a second level of protection. First level is that
1265 * the file is in a location only readable by the system process.
1266 * @param password the password.
1267 * @param salt the randomly generated salt
1268 * @return the hash of the pattern in a String.
1269 */
1270 private String passwordToHash(String password, long salt) {
1271 if (password == null) {
1272 return null;
1273 }
1274 String algo = null;
1275 String hashed = salt + password;
1276 try {
1277 byte[] saltedPassword = (password + salt).getBytes();
1278 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1279 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1280 hashed = toHex(sha1) + toHex(md5);
1281 } catch (NoSuchAlgorithmException e) {
1282 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1283 }
1284 return hashed;
1285 }
1286
1287 private static String toHex(byte[] ary) {
1288 final String hex = "0123456789ABCDEF";
1289 String ret = "";
1290 for (int i = 0; i < ary.length; i++) {
1291 ret += hex.charAt((ary[i] >> 4) & 0xf);
1292 ret += hex.charAt(ary[i] & 0xf);
1293 }
1294 return ret;
1295 }
1296
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001297 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001298 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001299 try {
1300 return mContext.getPackageManager().getApplicationInfo(packageName,
1301 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1302 } catch (NameNotFoundException nnfe) {
1303 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001304 } finally {
1305 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001306 }
1307 }
1308
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001309 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001310 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001311 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001312 final ArrayList<String> values = new ArrayList<String>();
1313
1314 FileInputStream fis = null;
1315 try {
1316 AtomicFile restrictionsFile =
1317 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1318 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1319 fis = restrictionsFile.openRead();
1320 XmlPullParser parser = Xml.newPullParser();
1321 parser.setInput(fis, null);
1322 int type;
1323 while ((type = parser.next()) != XmlPullParser.START_TAG
1324 && type != XmlPullParser.END_DOCUMENT) {
1325 ;
1326 }
1327
1328 if (type != XmlPullParser.START_TAG) {
1329 Slog.e(LOG_TAG, "Unable to read restrictions file "
1330 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001331 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001332 }
1333
1334 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1335 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1336 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001337 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001338 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1339 if (multiple != null) {
1340 int count = Integer.parseInt(multiple);
1341 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1342 if (type == XmlPullParser.START_TAG
1343 && parser.getName().equals(TAG_VALUE)) {
1344 values.add(parser.nextText().trim());
1345 count--;
1346 }
1347 }
1348 String [] valueStrings = new String[values.size()];
1349 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001350 restrictions.putStringArray(key, valueStrings);
1351 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1352 restrictions.putBoolean(key, Boolean.parseBoolean(
1353 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001354 } else {
1355 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001356 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001357 }
1358 }
1359 }
1360
1361 } catch (IOException ioe) {
1362 } catch (XmlPullParserException pe) {
1363 } finally {
1364 if (fis != null) {
1365 try {
1366 fis.close();
1367 } catch (IOException e) {
1368 }
1369 }
1370 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001371 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001372 }
1373
1374 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001375 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001376 FileOutputStream fos = null;
1377 AtomicFile restrictionsFile = new AtomicFile(
1378 new File(Environment.getUserSystemDirectory(userId),
1379 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1380 try {
1381 fos = restrictionsFile.startWrite();
1382 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1383
1384 // XmlSerializer serializer = XmlUtils.serializerInstance();
1385 final XmlSerializer serializer = new FastXmlSerializer();
1386 serializer.setOutput(bos, "utf-8");
1387 serializer.startDocument(null, true);
1388 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1389
1390 serializer.startTag(null, TAG_RESTRICTIONS);
1391
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001392 for (String key : restrictions.keySet()) {
1393 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001394 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001395 serializer.attribute(null, ATTR_KEY, key);
1396
1397 if (value instanceof Boolean) {
1398 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1399 serializer.text(value.toString());
1400 } else if (value == null || value instanceof String) {
1401 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1402 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001403 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001404 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1405 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001406 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001407 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001408 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001409 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001410 serializer.endTag(null, TAG_VALUE);
1411 }
1412 }
1413 serializer.endTag(null, TAG_ENTRY);
1414 }
1415
1416 serializer.endTag(null, TAG_RESTRICTIONS);
1417
1418 serializer.endDocument();
1419 restrictionsFile.finishWrite(fos);
1420 } catch (Exception e) {
1421 restrictionsFile.failWrite(fos);
1422 Slog.e(LOG_TAG, "Error writing application restrictions list");
1423 }
1424 }
1425
1426 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001427 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001428 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001429 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001430 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001431 }
1432 }
1433
1434 @Override
1435 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001436 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001437 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001438 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001439 }
1440 // Not found
1441 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001442 }
1443 }
1444
Amith Yamasani0b285492011-04-14 17:35:23 -07001445 /**
1446 * Caches the list of user ids in an array, adjusting the array size when necessary.
1447 */
Amith Yamasani13593602012-03-22 16:16:17 -07001448 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001449 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001450 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001451 if (!mUsers.valueAt(i).partial) {
1452 num++;
1453 }
1454 }
Amith Yamasani16389312012-10-17 21:20:14 -07001455 final int[] newUsers = new int[num];
1456 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001457 for (int i = 0; i < mUsers.size(); i++) {
1458 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001459 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001460 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001461 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001462 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001463 }
1464
1465 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001466 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001467 * @param userId the user that was just foregrounded
1468 */
1469 public void userForeground(int userId) {
1470 synchronized (mPackagesLock) {
1471 UserInfo user = mUsers.get(userId);
1472 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001473 if (user == null || user.partial) {
1474 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1475 return;
1476 }
1477 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001478 user.lastLoggedInTime = now;
1479 writeUserLocked(user);
1480 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001481 // If this is not a restricted profile and there is no restrictions pin, clean up
1482 // all restrictions files that might have been left behind, else clean up just the
1483 // ones with uninstalled packages
1484 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1485 final long salt = pinState == null ? 0 : pinState.salt;
1486 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001487 }
1488 }
1489
1490 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001491 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001492 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1493 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001494 * @return
1495 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001496 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001497 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001498 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001499 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001500 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001501 break;
1502 }
1503 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001504 }
Amith Yamasani195263742012-08-21 15:40:12 -07001505 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001506 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001507 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001508
1509 @Override
1510 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1511 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1512 != PackageManager.PERMISSION_GRANTED) {
1513 pw.println("Permission Denial: can't dump UserManager from from pid="
1514 + Binder.getCallingPid()
1515 + ", uid=" + Binder.getCallingUid()
1516 + " without permission "
1517 + android.Manifest.permission.DUMP);
1518 return;
1519 }
1520
1521 long now = System.currentTimeMillis();
1522 StringBuilder sb = new StringBuilder();
1523 synchronized (mPackagesLock) {
1524 pw.println("Users:");
1525 for (int i = 0; i < mUsers.size(); i++) {
1526 UserInfo user = mUsers.valueAt(i);
1527 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001528 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001529 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001530 if (user.partial) pw.print(" <partial>");
1531 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001532 pw.print(" Created: ");
1533 if (user.creationTime == 0) {
1534 pw.println("<unknown>");
1535 } else {
1536 sb.setLength(0);
1537 TimeUtils.formatDuration(now - user.creationTime, sb);
1538 sb.append(" ago");
1539 pw.println(sb);
1540 }
1541 pw.print(" Last logged in: ");
1542 if (user.lastLoggedInTime == 0) {
1543 pw.println("<unknown>");
1544 } else {
1545 sb.setLength(0);
1546 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1547 sb.append(" ago");
1548 pw.println(sb);
1549 }
1550 }
1551 }
1552 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001553
1554 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1555 @Override
1556 public void onPackageRemoved(String pkg, int uid) {
1557 final int userId = this.getChangingUserId();
1558 // Package could be disappearing because it is being blocked, so also check if
1559 // it has been uninstalled.
1560 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1561 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1562 cleanAppRestrictionsForPackage(pkg, userId);
1563 }
1564 }
1565 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001566}