blob: 35b5c85c0952d16dbe1208481d671752e24d7810 [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 Yamasanidf2e92a2013-03-01 17:04:38 -080029import android.content.RestrictionEntry;
Amith Yamasani1a7472e2013-07-02 11:17:30 -070030import android.content.pm.ApplicationInfo;
Amith Yamasani0b285492011-04-14 17:35:23 -070031import android.content.pm.PackageManager;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -080032import android.content.pm.PackageManager.NameNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070033import android.content.pm.UserInfo;
Amith Yamasanie928d7d2012-09-17 21:46:51 -070034import android.graphics.Bitmap;
35import android.graphics.BitmapFactory;
Amith Yamasani258848d2012-08-10 17:06:33 -070036import android.os.Binder;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080037import android.os.Bundle;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070038import android.os.Environment;
39import android.os.FileUtils;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080040import android.os.Handler;
Amith Yamasani258848d2012-08-10 17:06:33 -070041import android.os.IUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070042import android.os.Process;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070043import android.os.RemoteException;
Amith Yamasani655d0e22013-06-12 14:19:10 -070044import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070046import android.os.UserManager;
Amith Yamasani2a003292012-08-14 18:25:45 -070047import android.util.AtomicFile;
Amith Yamasani655d0e22013-06-12 14:19:10 -070048import android.util.Log;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070049import android.util.Slog;
50import android.util.SparseArray;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080051import android.util.SparseBooleanArray;
Amith Yamasani655d0e22013-06-12 14:19:10 -070052import android.util.SparseLongArray;
Amith Yamasani920ace02012-09-20 22:15:37 -070053import android.util.TimeUtils;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070054import android.util.Xml;
55
Amith Yamasani1a7472e2013-07-02 11:17:30 -070056import com.android.internal.content.PackageMonitor;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -080057import com.android.internal.util.ArrayUtils;
58import com.android.internal.util.FastXmlSerializer;
59
60import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
62import org.xmlpull.v1.XmlSerializer;
63
Amith Yamasani4b2e9342011-03-31 12:38:53 -070064import java.io.BufferedOutputStream;
65import java.io.File;
Amith Yamasani920ace02012-09-20 22:15:37 -070066import java.io.FileDescriptor;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070067import java.io.FileInputStream;
Amith Yamasanib8151ec2012-04-18 18:02:48 -070068import java.io.FileNotFoundException;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070069import java.io.FileOutputStream;
70import java.io.IOException;
Amith Yamasani920ace02012-09-20 22:15:37 -070071import java.io.PrintWriter;
Amith Yamasani655d0e22013-06-12 14:19:10 -070072import java.security.MessageDigest;
73import java.security.NoSuchAlgorithmException;
74import java.security.SecureRandom;
Amith Yamasani4b2e9342011-03-31 12:38:53 -070075import java.util.ArrayList;
76import java.util.List;
77
Amith Yamasani258848d2012-08-10 17:06:33 -070078public class UserManagerService extends IUserManager.Stub {
Amith Yamasanib8151ec2012-04-18 18:02:48 -070079
Amith Yamasani2a003292012-08-14 18:25:45 -070080 private static final String LOG_TAG = "UserManagerService";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070081
Amith Yamasani16389312012-10-17 21:20:14 -070082 private static final boolean DBG = false;
83
Amith Yamasani4b2e9342011-03-31 12:38:53 -070084 private static final String TAG_NAME = "name";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070085 private static final String ATTR_FLAGS = "flags";
Amith Yamasanib8151ec2012-04-18 18:02:48 -070086 private static final String ATTR_ICON_PATH = "icon";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070087 private static final String ATTR_ID = "id";
Amith Yamasani920ace02012-09-20 22:15:37 -070088 private static final String ATTR_CREATION_TIME = "created";
89 private static final String ATTR_LAST_LOGGED_IN_TIME = "lastLoggedIn";
Amith Yamasani655d0e22013-06-12 14:19:10 -070090 private static final String ATTR_SALT = "salt";
91 private static final String ATTR_PIN_HASH = "pinHash";
92 private static final String ATTR_FAILED_ATTEMPTS = "failedAttempts";
93 private static final String ATTR_LAST_RETRY_MS = "lastAttemptMs";
Amith Yamasani2a003292012-08-14 18:25:45 -070094 private static final String ATTR_SERIAL_NO = "serialNumber";
95 private static final String ATTR_NEXT_SERIAL_NO = "nextSerialNumber";
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070096 private static final String ATTR_PARTIAL = "partial";
Amith Yamasani6f34b412012-10-22 18:19:27 -070097 private static final String ATTR_USER_VERSION = "version";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070098 private static final String TAG_USERS = "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -070099 private static final String TAG_USER = "user";
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800100 private static final String TAG_RESTRICTIONS = "restrictions";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800101 private static final String TAG_ENTRY = "entry";
102 private static final String TAG_VALUE = "value";
103 private static final String ATTR_KEY = "key";
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700104 private static final String ATTR_VALUE_TYPE = "type";
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800105 private static final String ATTR_MULTIPLE = "m";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700106
Amith Yamasani7e99bc02013-04-16 18:24:51 -0700107 private static final String ATTR_TYPE_STRING_ARRAY = "sa";
108 private static final String ATTR_TYPE_STRING = "s";
109 private static final String ATTR_TYPE_BOOLEAN = "b";
110
Amith Yamasani0b285492011-04-14 17:35:23 -0700111 private static final String USER_INFO_DIR = "system" + File.separator + "users";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700112 private static final String USER_LIST_FILENAME = "userlist.xml";
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700113 private static final String USER_PHOTO_FILENAME = "photo.png";
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700114
Amith Yamasanidf2e92a2013-03-01 17:04:38 -0800115 private static final String RESTRICTIONS_FILE_PREFIX = "res_";
116
Amith Yamasani634cf312012-10-04 17:34:21 -0700117 private static final int MIN_USER_ID = 10;
118
Amith Yamasani350962c2013-08-06 11:18:53 -0700119 private static final int USER_VERSION = 3;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700120
Amith Yamasani920ace02012-09-20 22:15:37 -0700121 private static final long EPOCH_PLUS_30_YEARS = 30L * 365 * 24 * 60 * 60 * 1000L; // ms
122
Amith Yamasani655d0e22013-06-12 14:19:10 -0700123 // Number of attempts before jumping to the next BACKOFF_TIMES slot
124 private static final int BACKOFF_INC_INTERVAL = 5;
125
126 // Amount of time to force the user to wait before entering the PIN again, after failing
127 // BACKOFF_INC_INTERVAL times.
128 private static final int[] BACKOFF_TIMES = { 0, 30*1000, 60*1000, 5*60*1000, 30*60*1000 };
129
Dianne Hackborn4428e172012-08-24 17:43:05 -0700130 private final Context mContext;
131 private final PackageManagerService mPm;
132 private final Object mInstallLock;
133 private final Object mPackagesLock;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700134
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800135 private final Handler mHandler;
136
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700137 private final File mUsersDir;
138 private final File mUserListFile;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700139 private final File mBaseUserPath;
140
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800141 private final SparseArray<UserInfo> mUsers = new SparseArray<UserInfo>();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800142 private final SparseArray<Bundle> mUserRestrictions = new SparseArray<Bundle>();
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800143
Amith Yamasani655d0e22013-06-12 14:19:10 -0700144 class RestrictionsPinState {
145 long salt;
146 String pinHash;
147 int failedAttempts;
148 long lastAttemptTime;
149 }
150
151 private final SparseArray<RestrictionsPinState> mRestrictionsPinStates =
152 new SparseArray<RestrictionsPinState>();
153
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800154 /**
155 * Set of user IDs being actively removed. Removed IDs linger in this set
156 * for several seconds to work around a VFS caching issue.
157 */
158 // @GuardedBy("mPackagesLock")
159 private final SparseBooleanArray mRemovingUserIds = new SparseBooleanArray();
Dianne Hackborn4428e172012-08-24 17:43:05 -0700160
Amith Yamasani0b285492011-04-14 17:35:23 -0700161 private int[] mUserIds;
Amith Yamasani258848d2012-08-10 17:06:33 -0700162 private boolean mGuestEnabled;
Amith Yamasani2a003292012-08-14 18:25:45 -0700163 private int mNextSerialNumber;
Amith Yamasani6f34b412012-10-22 18:19:27 -0700164 private int mUserVersion = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -0700165
Amith Yamasani258848d2012-08-10 17:06:33 -0700166 private static UserManagerService sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700167
Dianne Hackborn4428e172012-08-24 17:43:05 -0700168 public static UserManagerService getInstance() {
169 synchronized (UserManagerService.class) {
170 return sInstance;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700173
174 /**
175 * Available for testing purposes.
176 */
Amith Yamasani258848d2012-08-10 17:06:33 -0700177 UserManagerService(File dataDir, File baseUserPath) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700178 this(null, null, new Object(), new Object(), dataDir, baseUserPath);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700179 }
180
Dianne Hackborn4428e172012-08-24 17:43:05 -0700181 /**
182 * Called by package manager to create the service. This is closely
183 * associated with the package manager, and the given lock is the
184 * package manager's own lock.
185 */
186 UserManagerService(Context context, PackageManagerService pm,
187 Object installLock, Object packagesLock) {
188 this(context, pm, installLock, packagesLock,
189 Environment.getDataDirectory(),
190 new File(Environment.getDataDirectory(), "user"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700191 }
192
Dianne Hackborn4428e172012-08-24 17:43:05 -0700193 /**
194 * Available for testing purposes.
195 */
196 private UserManagerService(Context context, PackageManagerService pm,
197 Object installLock, Object packagesLock,
198 File dataDir, File baseUserPath) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700199 mContext = context;
200 mPm = pm;
201 mInstallLock = installLock;
202 mPackagesLock = packagesLock;
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800203 mHandler = new Handler();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700204 synchronized (mInstallLock) {
205 synchronized (mPackagesLock) {
206 mUsersDir = new File(dataDir, USER_INFO_DIR);
207 mUsersDir.mkdirs();
208 // Make zeroth user directory, for services to migrate their files to that location
209 File userZeroDir = new File(mUsersDir, "0");
210 userZeroDir.mkdirs();
211 mBaseUserPath = baseUserPath;
212 FileUtils.setPermissions(mUsersDir.toString(),
213 FileUtils.S_IRWXU|FileUtils.S_IRWXG
214 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
215 -1, -1);
216 mUserListFile = new File(mUsersDir, USER_LIST_FILENAME);
217 readUserListLocked();
Amith Yamasani756901d2012-10-12 12:30:07 -0700218 // Prune out any partially created/partially removed users.
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700219 ArrayList<UserInfo> partials = new ArrayList<UserInfo>();
220 for (int i = 0; i < mUsers.size(); i++) {
221 UserInfo ui = mUsers.valueAt(i);
222 if (ui.partial && i != 0) {
223 partials.add(ui);
224 }
225 }
226 for (int i = 0; i < partials.size(); i++) {
227 UserInfo ui = partials.get(i);
228 Slog.w(LOG_TAG, "Removing partially created user #" + i
229 + " (name=" + ui.name + ")");
230 removeUserStateLocked(ui.id);
231 }
232 sInstance = this;
233 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700234 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700235
236 }
237
238 void systemReady() {
239 mUserPackageMonitor.register(ActivityThread.systemMain().getSystemContext(),
240 null, UserHandle.ALL, false);
241 userForeground(UserHandle.USER_OWNER);
Amith Yamasani258848d2012-08-10 17:06:33 -0700242 }
243
244 @Override
Amith Yamasani920ace02012-09-20 22:15:37 -0700245 public List<UserInfo> getUsers(boolean excludeDying) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700246 checkManageUsersPermission("query users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700247 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700248 ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
249 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700250 UserInfo ui = mUsers.valueAt(i);
251 if (ui.partial) {
252 continue;
253 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800254 if (!excludeDying || !mRemovingUserIds.get(ui.id)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700255 users.add(ui);
Amith Yamasani920ace02012-09-20 22:15:37 -0700256 }
Amith Yamasani13593602012-03-22 16:16:17 -0700257 }
258 return users;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700259 }
Amith Yamasani13593602012-03-22 16:16:17 -0700260 }
261
Amith Yamasani258848d2012-08-10 17:06:33 -0700262 @Override
263 public UserInfo getUserInfo(int userId) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700264 checkManageUsersPermission("query user");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700265 synchronized (mPackagesLock) {
Amith Yamasani195263742012-08-21 15:40:12 -0700266 return getUserInfoLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
268 }
269
Amith Yamasani71e6c692013-03-24 17:39:28 -0700270 @Override
271 public boolean isRestricted() {
272 synchronized (mPackagesLock) {
273 return getUserInfoLocked(UserHandle.getCallingUserId()).isRestricted();
274 }
275 }
276
Amith Yamasani195263742012-08-21 15:40:12 -0700277 /*
278 * Should be locked on mUsers before calling this.
279 */
280 private UserInfo getUserInfoLocked(int userId) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700281 UserInfo ui = mUsers.get(userId);
Amith Yamasani16389312012-10-17 21:20:14 -0700282 // If it is partial and not in the process of being removed, return as unknown user.
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -0800283 if (ui != null && ui.partial && !mRemovingUserIds.get(userId)) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700284 Slog.w(LOG_TAG, "getUserInfo: unknown user #" + userId);
285 return null;
286 }
287 return ui;
Amith Yamasani195263742012-08-21 15:40:12 -0700288 }
289
Amith Yamasani13593602012-03-22 16:16:17 -0700290 public boolean exists(int userId) {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700291 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700292 return ArrayUtils.contains(mUserIds, userId);
293 }
294 }
295
Amith Yamasani258848d2012-08-10 17:06:33 -0700296 @Override
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700297 public void setUserName(int userId, String name) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700298 checkManageUsersPermission("rename users");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700299 boolean changed = false;
Dianne Hackborn4428e172012-08-24 17:43:05 -0700300 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700301 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700302 if (info == null || info.partial) {
303 Slog.w(LOG_TAG, "setUserName: unknown user #" + userId);
304 return;
305 }
Amith Yamasani13593602012-03-22 16:16:17 -0700306 if (name != null && !name.equals(info.name)) {
307 info.name = name;
308 writeUserLocked(info);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700309 changed = true;
Amith Yamasani13593602012-03-22 16:16:17 -0700310 }
311 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700312 if (changed) {
313 sendUserInfoChangedBroadcast(userId);
314 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700315 }
316
Amith Yamasani258848d2012-08-10 17:06:33 -0700317 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700318 public void setUserIcon(int userId, Bitmap bitmap) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700319 checkManageUsersPermission("update users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700320 synchronized (mPackagesLock) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700321 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700322 if (info == null || info.partial) {
323 Slog.w(LOG_TAG, "setUserIcon: unknown user #" + userId);
324 return;
325 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700326 writeBitmapLocked(info, bitmap);
327 writeUserLocked(info);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700328 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700329 sendUserInfoChangedBroadcast(userId);
330 }
331
332 private void sendUserInfoChangedBroadcast(int userId) {
333 Intent changedIntent = new Intent(Intent.ACTION_USER_INFO_CHANGED);
334 changedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
335 changedIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Amith Yamasani6fc1d4e2013-05-08 16:43:58 -0700336 mContext.sendBroadcastAsUser(changedIntent, UserHandle.ALL);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700337 }
338
Amith Yamasani258848d2012-08-10 17:06:33 -0700339 @Override
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700340 public Bitmap getUserIcon(int userId) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700341 checkManageUsersPermission("read users");
342 synchronized (mPackagesLock) {
343 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700344 if (info == null || info.partial) {
345 Slog.w(LOG_TAG, "getUserIcon: unknown user #" + userId);
346 return null;
347 }
348 if (info.iconPath == null) {
349 return null;
350 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700351 return BitmapFactory.decodeFile(info.iconPath);
Amith Yamasani3b49f072012-09-17 10:21:43 -0700352 }
353 }
354
355 @Override
Amith Yamasani258848d2012-08-10 17:06:33 -0700356 public void setGuestEnabled(boolean enable) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700357 checkManageUsersPermission("enable guest users");
Dianne Hackborn4428e172012-08-24 17:43:05 -0700358 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700359 if (mGuestEnabled != enable) {
360 mGuestEnabled = enable;
361 // Erase any guest user that currently exists
362 for (int i = 0; i < mUsers.size(); i++) {
363 UserInfo user = mUsers.valueAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700364 if (!user.partial && user.isGuest()) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700365 if (!enable) {
366 removeUser(user.id);
367 }
368 return;
369 }
370 }
371 // No guest was found
372 if (enable) {
373 createUser("Guest", UserInfo.FLAG_GUEST);
374 }
375 }
376 }
377 }
378
379 @Override
380 public boolean isGuestEnabled() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700381 synchronized (mPackagesLock) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700382 return mGuestEnabled;
383 }
384 }
385
386 @Override
387 public void wipeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700388 checkManageUsersPermission("wipe user");
Amith Yamasani258848d2012-08-10 17:06:33 -0700389 // TODO:
390 }
391
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700392 public void makeInitialized(int userId) {
393 checkManageUsersPermission("makeInitialized");
394 synchronized (mPackagesLock) {
395 UserInfo info = mUsers.get(userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700396 if (info == null || info.partial) {
397 Slog.w(LOG_TAG, "makeInitialized: unknown user #" + userId);
398 }
399 if ((info.flags&UserInfo.FLAG_INITIALIZED) == 0) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700400 info.flags |= UserInfo.FLAG_INITIALIZED;
401 writeUserLocked(info);
402 }
403 }
404 }
405
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800406 @Override
407 public Bundle getUserRestrictions(int userId) {
408 // checkManageUsersPermission("getUserRestrictions");
409
410 synchronized (mPackagesLock) {
411 Bundle restrictions = mUserRestrictions.get(userId);
412 return restrictions != null ? restrictions : Bundle.EMPTY;
413 }
414 }
415
416 @Override
417 public void setUserRestrictions(Bundle restrictions, int userId) {
418 checkManageUsersPermission("setUserRestrictions");
Amith Yamasani0343ec32013-07-22 14:52:06 -0700419 if (restrictions == null) return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800420
421 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -0700422 // If the user has restrictions already and call is trying to disallow restrictions,
423 // don't modify the flag.
424 if (hasRestrictionsPinLocked(userId)
425 && restrictions.getBoolean(UserManager.DISALLOW_APP_RESTRICTIONS, false)) {
426 restrictions.putBoolean(UserManager.DISALLOW_APP_RESTRICTIONS, false);
427 }
Amith Yamasani350962c2013-08-06 11:18:53 -0700428 mUserRestrictions.get(userId).clear();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800429 mUserRestrictions.get(userId).putAll(restrictions);
430 writeUserLocked(mUsers.get(userId));
431 }
432 }
433
Amith Yamasani258848d2012-08-10 17:06:33 -0700434 /**
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700435 * Check if we've hit the limit of how many users can be created.
436 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700437 private boolean isUserLimitReachedLocked() {
438 int nUsers = mUsers.size();
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700439 return nUsers >= UserManager.getMaxSupportedUsers();
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700440 }
441
442 /**
Amith Yamasani195263742012-08-21 15:40:12 -0700443 * Enforces that only the system UID or root's UID or apps that have the
444 * {@link android.Manifest.permission.MANAGE_USERS MANAGE_USERS}
445 * permission can make certain calls to the UserManager.
Amith Yamasani258848d2012-08-10 17:06:33 -0700446 *
447 * @param message used as message if SecurityException is thrown
448 * @throws SecurityException if the caller is not system or root
449 */
Amith Yamasani2a003292012-08-14 18:25:45 -0700450 private static final void checkManageUsersPermission(String message) {
Amith Yamasani258848d2012-08-10 17:06:33 -0700451 final int uid = Binder.getCallingUid();
Amith Yamasani2a003292012-08-14 18:25:45 -0700452 if (uid != Process.SYSTEM_UID && uid != 0
453 && ActivityManager.checkComponentPermission(
454 android.Manifest.permission.MANAGE_USERS,
455 uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
456 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
Amith Yamasani258848d2012-08-10 17:06:33 -0700457 }
458 }
459
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700460 private void writeBitmapLocked(UserInfo info, Bitmap bitmap) {
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700461 try {
462 File dir = new File(mUsersDir, Integer.toString(info.id));
463 File file = new File(dir, USER_PHOTO_FILENAME);
464 if (!dir.exists()) {
465 dir.mkdir();
466 FileUtils.setPermissions(
467 dir.getPath(),
468 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
469 -1, -1);
470 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700471 FileOutputStream os;
472 if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, os = new FileOutputStream(file))) {
Amith Yamasani3b49f072012-09-17 10:21:43 -0700473 info.iconPath = file.getAbsolutePath();
474 }
Amith Yamasanie928d7d2012-09-17 21:46:51 -0700475 try {
476 os.close();
477 } catch (IOException ioe) {
478 // What the ... !
479 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700480 } catch (FileNotFoundException e) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700481 Slog.w(LOG_TAG, "Error setting photo for user ", e);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700482 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700483 }
484
Amith Yamasani0b285492011-04-14 17:35:23 -0700485 /**
486 * Returns an array of user ids. This array is cached here for quick access, so do not modify or
487 * cache it elsewhere.
488 * @return the array of user ids.
489 */
Dianne Hackborn1676c852012-09-10 14:52:30 -0700490 public int[] getUserIds() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700491 synchronized (mPackagesLock) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -0700492 return mUserIds;
493 }
Amith Yamasani0b285492011-04-14 17:35:23 -0700494 }
495
Dianne Hackborn4428e172012-08-24 17:43:05 -0700496 int[] getUserIdsLPr() {
497 return mUserIds;
498 }
499
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700500 private void readUserList() {
Dianne Hackborn4428e172012-08-24 17:43:05 -0700501 synchronized (mPackagesLock) {
Amith Yamasani13593602012-03-22 16:16:17 -0700502 readUserListLocked();
503 }
504 }
505
506 private void readUserListLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -0700507 mGuestEnabled = false;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700508 if (!mUserListFile.exists()) {
Amith Yamasani13593602012-03-22 16:16:17 -0700509 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700510 return;
511 }
512 FileInputStream fis = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700513 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700514 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700515 fis = userListFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700516 XmlPullParser parser = Xml.newPullParser();
517 parser.setInput(fis, null);
518 int type;
519 while ((type = parser.next()) != XmlPullParser.START_TAG
520 && type != XmlPullParser.END_DOCUMENT) {
521 ;
522 }
523
524 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700525 Slog.e(LOG_TAG, "Unable to read user list");
Amith Yamasani13593602012-03-22 16:16:17 -0700526 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700527 return;
528 }
529
Amith Yamasani2a003292012-08-14 18:25:45 -0700530 mNextSerialNumber = -1;
531 if (parser.getName().equals(TAG_USERS)) {
532 String lastSerialNumber = parser.getAttributeValue(null, ATTR_NEXT_SERIAL_NO);
533 if (lastSerialNumber != null) {
534 mNextSerialNumber = Integer.parseInt(lastSerialNumber);
535 }
Amith Yamasani6f34b412012-10-22 18:19:27 -0700536 String versionNumber = parser.getAttributeValue(null, ATTR_USER_VERSION);
537 if (versionNumber != null) {
538 mUserVersion = Integer.parseInt(versionNumber);
539 }
Amith Yamasani2a003292012-08-14 18:25:45 -0700540 }
541
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700542 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
543 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
544 String id = parser.getAttributeValue(null, ATTR_ID);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800545 UserInfo user = readUserLocked(Integer.parseInt(id));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700546
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700547 if (user != null) {
548 mUsers.put(user.id, user);
Amith Yamasani2a003292012-08-14 18:25:45 -0700549 if (user.isGuest()) {
550 mGuestEnabled = true;
551 }
552 if (mNextSerialNumber < 0 || mNextSerialNumber <= user.id) {
553 mNextSerialNumber = user.id + 1;
554 }
Amith Yamasani258848d2012-08-10 17:06:33 -0700555 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700556 }
557 }
Amith Yamasani13593602012-03-22 16:16:17 -0700558 updateUserIdsLocked();
Amith Yamasani350962c2013-08-06 11:18:53 -0700559 upgradeIfNecessaryLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700560 } catch (IOException ioe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700561 fallbackToSingleUserLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700562 } catch (XmlPullParserException pe) {
Amith Yamasani13593602012-03-22 16:16:17 -0700563 fallbackToSingleUserLocked();
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800564 } finally {
565 if (fis != null) {
566 try {
567 fis.close();
568 } catch (IOException e) {
569 }
570 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700571 }
572 }
573
Amith Yamasani6f34b412012-10-22 18:19:27 -0700574 /**
Amith Yamasanibc9625052012-11-15 14:39:18 -0800575 * Upgrade steps between versions, either for fixing bugs or changing the data format.
Amith Yamasani6f34b412012-10-22 18:19:27 -0700576 */
Amith Yamasani350962c2013-08-06 11:18:53 -0700577 private void upgradeIfNecessaryLocked() {
Amith Yamasani6f34b412012-10-22 18:19:27 -0700578 int userVersion = mUserVersion;
579 if (userVersion < 1) {
580 // Assign a proper name for the owner, if not initialized correctly before
581 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
582 if ("Primary".equals(user.name)) {
583 user.name = mContext.getResources().getString(com.android.internal.R.string.owner_name);
584 writeUserLocked(user);
585 }
586 userVersion = 1;
587 }
588
Amith Yamasanibc9625052012-11-15 14:39:18 -0800589 if (userVersion < 2) {
590 // Owner should be marked as initialized
591 UserInfo user = mUsers.get(UserHandle.USER_OWNER);
592 if ((user.flags & UserInfo.FLAG_INITIALIZED) == 0) {
593 user.flags |= UserInfo.FLAG_INITIALIZED;
594 writeUserLocked(user);
595 }
596 userVersion = 2;
597 }
598
Amith Yamasani350962c2013-08-06 11:18:53 -0700599 if (userVersion < 3) {
600 // Remove restrictions PIN for all users
601 for (int i = 0; i < mRestrictionsPinStates.size(); i++) {
602 int userId = mRestrictionsPinStates.keyAt(i);
603 RestrictionsPinState state = mRestrictionsPinStates.valueAt(i);
604 if (state.salt != 0 && state.pinHash != null) {
605 removeRestrictionsForUser(userId);
606 }
607 }
608 userVersion = 3;
609 }
610
Amith Yamasani6f34b412012-10-22 18:19:27 -0700611 if (userVersion < USER_VERSION) {
612 Slog.w(LOG_TAG, "User version " + mUserVersion + " didn't upgrade as expected to "
613 + USER_VERSION);
614 } else {
615 mUserVersion = userVersion;
616 writeUserListLocked();
617 }
618 }
619
Amith Yamasani13593602012-03-22 16:16:17 -0700620 private void fallbackToSingleUserLocked() {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700621 // Create the primary user
Amith Yamasani67df64b2012-12-14 12:09:36 -0800622 UserInfo primary = new UserInfo(UserHandle.USER_OWNER,
Amith Yamasani6f34b412012-10-22 18:19:27 -0700623 mContext.getResources().getString(com.android.internal.R.string.owner_name), null,
Amith Yamasani756901d2012-10-12 12:30:07 -0700624 UserInfo.FLAG_ADMIN | UserInfo.FLAG_PRIMARY | UserInfo.FLAG_INITIALIZED);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700625 mUsers.put(0, primary);
Amith Yamasani634cf312012-10-04 17:34:21 -0700626 mNextSerialNumber = MIN_USER_ID;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800627
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500628 Bundle restrictions = new Bundle();
Amith Yamasani67df64b2012-12-14 12:09:36 -0800629 mUserRestrictions.append(UserHandle.USER_OWNER, restrictions);
630
Amith Yamasani13593602012-03-22 16:16:17 -0700631 updateUserIdsLocked();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700632
Amith Yamasani13593602012-03-22 16:16:17 -0700633 writeUserListLocked();
634 writeUserLocked(primary);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700635 }
636
637 /*
638 * Writes the user file in this format:
639 *
640 * <user flags="20039023" id="0">
641 * <name>Primary</name>
642 * </user>
643 */
Amith Yamasani13593602012-03-22 16:16:17 -0700644 private void writeUserLocked(UserInfo userInfo) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700645 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700646 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userInfo.id + ".xml"));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700647 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700648 fos = userFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700649 final BufferedOutputStream bos = new BufferedOutputStream(fos);
650
651 // XmlSerializer serializer = XmlUtils.serializerInstance();
652 final XmlSerializer serializer = new FastXmlSerializer();
653 serializer.setOutput(bos, "utf-8");
654 serializer.startDocument(null, true);
655 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
656
657 serializer.startTag(null, TAG_USER);
658 serializer.attribute(null, ATTR_ID, Integer.toString(userInfo.id));
Amith Yamasani2a003292012-08-14 18:25:45 -0700659 serializer.attribute(null, ATTR_SERIAL_NO, Integer.toString(userInfo.serialNumber));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700660 serializer.attribute(null, ATTR_FLAGS, Integer.toString(userInfo.flags));
Amith Yamasani920ace02012-09-20 22:15:37 -0700661 serializer.attribute(null, ATTR_CREATION_TIME, Long.toString(userInfo.creationTime));
662 serializer.attribute(null, ATTR_LAST_LOGGED_IN_TIME,
663 Long.toString(userInfo.lastLoggedInTime));
Amith Yamasani655d0e22013-06-12 14:19:10 -0700664 RestrictionsPinState pinState = mRestrictionsPinStates.get(userInfo.id);
665 if (pinState != null) {
666 if (pinState.salt != 0) {
667 serializer.attribute(null, ATTR_SALT, Long.toString(pinState.salt));
668 }
669 if (pinState.pinHash != null) {
670 serializer.attribute(null, ATTR_PIN_HASH, pinState.pinHash);
671 }
672 if (pinState.failedAttempts != 0) {
673 serializer.attribute(null, ATTR_FAILED_ATTEMPTS,
674 Integer.toString(pinState.failedAttempts));
675 serializer.attribute(null, ATTR_LAST_RETRY_MS,
676 Long.toString(pinState.lastAttemptTime));
677 }
678 }
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700679 if (userInfo.iconPath != null) {
680 serializer.attribute(null, ATTR_ICON_PATH, userInfo.iconPath);
681 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700682 if (userInfo.partial) {
683 serializer.attribute(null, ATTR_PARTIAL, "true");
684 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700685
686 serializer.startTag(null, TAG_NAME);
687 serializer.text(userInfo.name);
688 serializer.endTag(null, TAG_NAME);
689
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800690 Bundle restrictions = mUserRestrictions.get(userInfo.id);
691 if (restrictions != null) {
692 serializer.startTag(null, TAG_RESTRICTIONS);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700693 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
694 writeBoolean(serializer, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
695 writeBoolean(serializer, restrictions, UserManager.DISALLOW_INSTALL_APPS);
696 writeBoolean(serializer, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
697 writeBoolean(serializer, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400698 writeBoolean(serializer, restrictions,
699 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
700 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
701 writeBoolean(serializer, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400702 writeBoolean(serializer, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
703 writeBoolean(serializer, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani0343ec32013-07-22 14:52:06 -0700704 writeBoolean(serializer, restrictions, UserManager.DISALLOW_APP_RESTRICTIONS);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800705 serializer.endTag(null, TAG_RESTRICTIONS);
706 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700707 serializer.endTag(null, TAG_USER);
708
709 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700710 userFile.finishWrite(fos);
711 } catch (Exception ioe) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700712 Slog.e(LOG_TAG, "Error writing user info " + userInfo.id + "\n" + ioe);
Amith Yamasani2a003292012-08-14 18:25:45 -0700713 userFile.failWrite(fos);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700714 }
715 }
716
717 /*
718 * Writes the user list file in this format:
719 *
Amith Yamasani2a003292012-08-14 18:25:45 -0700720 * <users nextSerialNumber="3">
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700721 * <user id="0"></user>
722 * <user id="2"></user>
723 * </users>
724 */
Amith Yamasani13593602012-03-22 16:16:17 -0700725 private void writeUserListLocked() {
Amith Yamasani742a6712011-05-04 14:49:28 -0700726 FileOutputStream fos = null;
Amith Yamasani2a003292012-08-14 18:25:45 -0700727 AtomicFile userListFile = new AtomicFile(mUserListFile);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700728 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700729 fos = userListFile.startWrite();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700730 final BufferedOutputStream bos = new BufferedOutputStream(fos);
731
732 // XmlSerializer serializer = XmlUtils.serializerInstance();
733 final XmlSerializer serializer = new FastXmlSerializer();
734 serializer.setOutput(bos, "utf-8");
735 serializer.startDocument(null, true);
736 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
737
738 serializer.startTag(null, TAG_USERS);
Amith Yamasani2a003292012-08-14 18:25:45 -0700739 serializer.attribute(null, ATTR_NEXT_SERIAL_NO, Integer.toString(mNextSerialNumber));
Amith Yamasani6f34b412012-10-22 18:19:27 -0700740 serializer.attribute(null, ATTR_USER_VERSION, Integer.toString(mUserVersion));
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700741
742 for (int i = 0; i < mUsers.size(); i++) {
743 UserInfo user = mUsers.valueAt(i);
744 serializer.startTag(null, TAG_USER);
745 serializer.attribute(null, ATTR_ID, Integer.toString(user.id));
746 serializer.endTag(null, TAG_USER);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700747 }
748
749 serializer.endTag(null, TAG_USERS);
750
751 serializer.endDocument();
Amith Yamasani2a003292012-08-14 18:25:45 -0700752 userListFile.finishWrite(fos);
753 } catch (Exception e) {
754 userListFile.failWrite(fos);
Amith Yamasani0b285492011-04-14 17:35:23 -0700755 Slog.e(LOG_TAG, "Error writing user list");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700756 }
757 }
758
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800759 private UserInfo readUserLocked(int id) {
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700760 int flags = 0;
Amith Yamasani2a003292012-08-14 18:25:45 -0700761 int serialNumber = id;
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700762 String name = null;
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700763 String iconPath = null;
Amith Yamasani920ace02012-09-20 22:15:37 -0700764 long creationTime = 0L;
765 long lastLoggedInTime = 0L;
Amith Yamasani655d0e22013-06-12 14:19:10 -0700766 long salt = 0L;
767 String pinHash = null;
768 int failedAttempts = 0;
769 long lastAttemptTime = 0L;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700770 boolean partial = false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800771 Bundle restrictions = new Bundle();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700772
773 FileInputStream fis = null;
774 try {
Amith Yamasani2a003292012-08-14 18:25:45 -0700775 AtomicFile userFile =
776 new AtomicFile(new File(mUsersDir, Integer.toString(id) + ".xml"));
777 fis = userFile.openRead();
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700778 XmlPullParser parser = Xml.newPullParser();
779 parser.setInput(fis, null);
780 int type;
781 while ((type = parser.next()) != XmlPullParser.START_TAG
782 && type != XmlPullParser.END_DOCUMENT) {
783 ;
784 }
785
786 if (type != XmlPullParser.START_TAG) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700787 Slog.e(LOG_TAG, "Unable to read user " + id);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700788 return null;
789 }
790
791 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_USER)) {
Amith Yamasani920ace02012-09-20 22:15:37 -0700792 int storedId = readIntAttribute(parser, ATTR_ID, -1);
793 if (storedId != id) {
Amith Yamasani0b285492011-04-14 17:35:23 -0700794 Slog.e(LOG_TAG, "User id does not match the file name");
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700795 return null;
796 }
Amith Yamasani920ace02012-09-20 22:15:37 -0700797 serialNumber = readIntAttribute(parser, ATTR_SERIAL_NO, id);
798 flags = readIntAttribute(parser, ATTR_FLAGS, 0);
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700799 iconPath = parser.getAttributeValue(null, ATTR_ICON_PATH);
Amith Yamasani920ace02012-09-20 22:15:37 -0700800 creationTime = readLongAttribute(parser, ATTR_CREATION_TIME, 0);
801 lastLoggedInTime = readLongAttribute(parser, ATTR_LAST_LOGGED_IN_TIME, 0);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700802 salt = readLongAttribute(parser, ATTR_SALT, 0L);
803 pinHash = parser.getAttributeValue(null, ATTR_PIN_HASH);
804 failedAttempts = readIntAttribute(parser, ATTR_FAILED_ATTEMPTS, 0);
805 lastAttemptTime = readLongAttribute(parser, ATTR_LAST_RETRY_MS, 0L);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700806 String valueString = parser.getAttributeValue(null, ATTR_PARTIAL);
807 if ("true".equals(valueString)) {
808 partial = true;
809 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700810
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800811 int outerDepth = parser.getDepth();
812 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
813 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
814 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
815 continue;
816 }
817 String tag = parser.getName();
818 if (TAG_NAME.equals(tag)) {
819 type = parser.next();
820 if (type == XmlPullParser.TEXT) {
821 name = parser.getText();
822 }
823 } else if (TAG_RESTRICTIONS.equals(tag)) {
Amith Yamasani71e6c692013-03-24 17:39:28 -0700824 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_WIFI);
825 readBoolean(parser, restrictions, UserManager.DISALLOW_MODIFY_ACCOUNTS);
826 readBoolean(parser, restrictions, UserManager.DISALLOW_INSTALL_APPS);
827 readBoolean(parser, restrictions, UserManager.DISALLOW_UNINSTALL_APPS);
828 readBoolean(parser, restrictions, UserManager.DISALLOW_SHARE_LOCATION);
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400829 readBoolean(parser, restrictions,
830 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
831 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_BLUETOOTH);
832 readBoolean(parser, restrictions, UserManager.DISALLOW_USB_FILE_TRANSFER);
Emily Bernierb223f732013-04-11 15:46:36 -0400833 readBoolean(parser, restrictions, UserManager.DISALLOW_CONFIG_CREDENTIALS);
834 readBoolean(parser, restrictions, UserManager.DISALLOW_REMOVE_USER);
Amith Yamasani0343ec32013-07-22 14:52:06 -0700835 readBoolean(parser, restrictions, UserManager.DISALLOW_APP_RESTRICTIONS);
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700836 }
837 }
838 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700839
Amith Yamasanib8151ec2012-04-18 18:02:48 -0700840 UserInfo userInfo = new UserInfo(id, name, iconPath, flags);
Amith Yamasani2a003292012-08-14 18:25:45 -0700841 userInfo.serialNumber = serialNumber;
Amith Yamasani920ace02012-09-20 22:15:37 -0700842 userInfo.creationTime = creationTime;
843 userInfo.lastLoggedInTime = lastLoggedInTime;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700844 userInfo.partial = partial;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800845 mUserRestrictions.append(id, restrictions);
Amith Yamasani655d0e22013-06-12 14:19:10 -0700846 if (salt != 0L) {
847 RestrictionsPinState pinState = mRestrictionsPinStates.get(id);
848 if (pinState == null) {
849 pinState = new RestrictionsPinState();
850 mRestrictionsPinStates.put(id, pinState);
851 }
852 pinState.salt = salt;
853 pinState.pinHash = pinHash;
854 pinState.failedAttempts = failedAttempts;
855 pinState.lastAttemptTime = lastAttemptTime;
856 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700857 return userInfo;
858
859 } catch (IOException ioe) {
860 } catch (XmlPullParserException pe) {
Dianne Hackbornbfd89b32011-12-15 18:22:54 -0800861 } finally {
862 if (fis != null) {
863 try {
864 fis.close();
865 } catch (IOException e) {
866 }
867 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700868 }
869 return null;
870 }
871
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800872 private void readBoolean(XmlPullParser parser, Bundle restrictions,
873 String restrictionKey) {
874 String value = parser.getAttributeValue(null, restrictionKey);
Amith Yamasani71e6c692013-03-24 17:39:28 -0700875 if (value != null) {
876 restrictions.putBoolean(restrictionKey, Boolean.parseBoolean(value));
877 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800878 }
879
880 private void writeBoolean(XmlSerializer xml, Bundle restrictions, String restrictionKey)
881 throws IOException {
882 if (restrictions.containsKey(restrictionKey)) {
883 xml.attribute(null, restrictionKey,
884 Boolean.toString(restrictions.getBoolean(restrictionKey)));
885 }
886 }
887
Amith Yamasani920ace02012-09-20 22:15:37 -0700888 private int readIntAttribute(XmlPullParser parser, String attr, int defaultValue) {
889 String valueString = parser.getAttributeValue(null, attr);
890 if (valueString == null) return defaultValue;
891 try {
892 return Integer.parseInt(valueString);
893 } catch (NumberFormatException nfe) {
894 return defaultValue;
895 }
896 }
897
898 private long readLongAttribute(XmlPullParser parser, String attr, long defaultValue) {
899 String valueString = parser.getAttributeValue(null, attr);
900 if (valueString == null) return defaultValue;
901 try {
902 return Long.parseLong(valueString);
903 } catch (NumberFormatException nfe) {
904 return defaultValue;
905 }
906 }
907
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700908 private boolean isPackageInstalled(String pkg, int userId) {
909 final ApplicationInfo info = mPm.getApplicationInfo(pkg,
910 PackageManager.GET_UNINSTALLED_PACKAGES,
911 userId);
912 if (info == null || (info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
913 return false;
914 }
915 return true;
916 }
917
Amith Yamasanib82add22013-07-09 11:24:44 -0700918 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700919 * Removes all the restrictions files (res_<packagename>) for a given user, if all is true,
920 * else removes only those packages that have been uninstalled.
Amith Yamasanib82add22013-07-09 11:24:44 -0700921 * Does not do any permissions checking.
922 */
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700923 private void cleanAppRestrictions(int userId, boolean all) {
Amith Yamasanib82add22013-07-09 11:24:44 -0700924 synchronized (mPackagesLock) {
925 File dir = Environment.getUserSystemDirectory(userId);
926 String[] files = dir.list();
927 if (files == null) return;
928 for (String fileName : files) {
929 if (fileName.startsWith(RESTRICTIONS_FILE_PREFIX)) {
930 File resFile = new File(dir, fileName);
931 if (resFile.exists()) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700932 if (all) {
933 resFile.delete();
934 } else {
935 String pkg = fileName.substring(RESTRICTIONS_FILE_PREFIX.length());
936 if (!isPackageInstalled(pkg, userId)) {
937 resFile.delete();
938 }
939 }
Amith Yamasanib82add22013-07-09 11:24:44 -0700940 }
941 }
942 }
943 }
944 }
945
Amith Yamasani1a7472e2013-07-02 11:17:30 -0700946 /**
947 * Removes the app restrictions file for a specific package and user id, if it exists.
948 */
949 private void cleanAppRestrictionsForPackage(String pkg, int userId) {
950 synchronized (mPackagesLock) {
951 File dir = Environment.getUserSystemDirectory(userId);
952 File resFile = new File(dir, RESTRICTIONS_FILE_PREFIX + pkg);
953 if (resFile.exists()) {
954 resFile.delete();
955 }
956 }
957 }
958
Amith Yamasani258848d2012-08-10 17:06:33 -0700959 @Override
Amith Yamasani13593602012-03-22 16:16:17 -0700960 public UserInfo createUser(String name, int flags) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700961 checkManageUsersPermission("Only the system can create users");
Amith Yamasanifaea76f2012-09-11 10:59:48 -0700962
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700963 final long ident = Binder.clearCallingIdentity();
964 final UserInfo userInfo;
965 try {
966 synchronized (mInstallLock) {
967 synchronized (mPackagesLock) {
968 if (isUserLimitReachedLocked()) return null;
969 int userId = getNextAvailableIdLocked();
970 userInfo = new UserInfo(userId, name, null, flags);
971 File userPath = new File(mBaseUserPath, Integer.toString(userId));
972 userInfo.serialNumber = mNextSerialNumber++;
Amith Yamasani920ace02012-09-20 22:15:37 -0700973 long now = System.currentTimeMillis();
974 userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700975 userInfo.partial = true;
Amith Yamasani16389312012-10-17 21:20:14 -0700976 Environment.getUserSystemDirectory(userInfo.id).mkdirs();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700977 mUsers.put(userId, userInfo);
978 writeUserListLocked();
979 writeUserLocked(userInfo);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700980 mPm.createNewUserLILPw(userId, userPath);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700981 userInfo.partial = false;
982 writeUserLocked(userInfo);
983 updateUserIdsLocked();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500984 Bundle restrictions = new Bundle();
Geoffrey Borggaarde45e45e32013-01-24 10:03:20 -0500985 mUserRestrictions.append(userId, restrictions);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700986 }
Dianne Hackborn4428e172012-08-24 17:43:05 -0700987 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700988 if (userInfo != null) {
989 Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
990 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userInfo.id);
991 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
992 android.Manifest.permission.MANAGE_USERS);
993 }
994 } finally {
995 Binder.restoreCallingIdentity(ident);
Amith Yamasani258848d2012-08-10 17:06:33 -0700996 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -0700997 return userInfo;
998 }
999
Amith Yamasani0b285492011-04-14 17:35:23 -07001000 /**
1001 * Removes a user and all data directories created for that user. This method should be called
1002 * after the user's processes have been terminated.
1003 * @param id the user's id
1004 */
Amith Yamasani258848d2012-08-10 17:06:33 -07001005 public boolean removeUser(int userHandle) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001006 checkManageUsersPermission("Only the system can remove users");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001007 final UserInfo user;
1008 synchronized (mPackagesLock) {
1009 user = mUsers.get(userHandle);
1010 if (userHandle == 0 || user == null) {
1011 return false;
1012 }
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001013 mRemovingUserIds.put(userHandle, true);
Amith Yamasani756901d2012-10-12 12:30:07 -07001014 // Set this to a partially created user, so that the user will be purged
1015 // on next startup, in case the runtime stops now before stopping and
1016 // removing the user completely.
1017 user.partial = true;
1018 writeUserLocked(user);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001019 }
Amith Yamasani16389312012-10-17 21:20:14 -07001020 if (DBG) Slog.i(LOG_TAG, "Stopping user " + userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001021 int res;
1022 try {
1023 res = ActivityManagerNative.getDefault().stopUser(userHandle,
1024 new IStopUserCallback.Stub() {
1025 @Override
1026 public void userStopped(int userId) {
1027 finishRemoveUser(userId);
1028 }
1029 @Override
1030 public void userStopAborted(int userId) {
1031 }
1032 });
1033 } catch (RemoteException e) {
1034 return false;
1035 }
1036
1037 return res == ActivityManager.USER_OP_SUCCESS;
1038 }
1039
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001040 void finishRemoveUser(final int userHandle) {
Amith Yamasani16389312012-10-17 21:20:14 -07001041 if (DBG) Slog.i(LOG_TAG, "finishRemoveUser " + userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001042 // Let other services shutdown any activity and clean up their state before completely
1043 // wiping the user's system directory and removing from the user list
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001044 long ident = Binder.clearCallingIdentity();
1045 try {
1046 Intent addedIntent = new Intent(Intent.ACTION_USER_REMOVED);
1047 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
Amith Yamasanidb6a14c2012-10-17 21:16:52 -07001048 mContext.sendOrderedBroadcastAsUser(addedIntent, UserHandle.ALL,
1049 android.Manifest.permission.MANAGE_USERS,
1050
1051 new BroadcastReceiver() {
1052 @Override
1053 public void onReceive(Context context, Intent intent) {
1054 if (DBG) {
1055 Slog.i(LOG_TAG,
1056 "USER_REMOVED broadcast sent, cleaning up user data "
1057 + userHandle);
1058 }
1059 new Thread() {
1060 public void run() {
1061 synchronized (mInstallLock) {
1062 synchronized (mPackagesLock) {
1063 removeUserStateLocked(userHandle);
1064 }
1065 }
1066 }
1067 }.start();
1068 }
1069 },
1070
1071 null, Activity.RESULT_OK, null, null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001072 } finally {
1073 Binder.restoreCallingIdentity(ident);
1074 }
Amith Yamasani2a003292012-08-14 18:25:45 -07001075 }
1076
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001077 private void removeUserStateLocked(final int userHandle) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001078 // Cleanup package manager settings
1079 mPm.cleanUpUserLILPw(userHandle);
1080
1081 // Remove this user from the list
1082 mUsers.remove(userHandle);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001083
1084 // Have user ID linger for several seconds to let external storage VFS
1085 // cache entries expire. This must be greater than the 'entry_valid'
1086 // timeout used by the FUSE daemon.
1087 mHandler.postDelayed(new Runnable() {
1088 @Override
1089 public void run() {
1090 synchronized (mPackagesLock) {
1091 mRemovingUserIds.delete(userHandle);
1092 }
1093 }
1094 }, MINUTE_IN_MILLIS);
1095
Amith Yamasani655d0e22013-06-12 14:19:10 -07001096 mRestrictionsPinStates.remove(userHandle);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001097 // Remove user file
1098 AtomicFile userFile = new AtomicFile(new File(mUsersDir, userHandle + ".xml"));
1099 userFile.delete();
1100 // Update the user list
1101 writeUserListLocked();
1102 updateUserIdsLocked();
1103 removeDirectoryRecursive(Environment.getUserSystemDirectory(userHandle));
1104 }
1105
Amith Yamasani61f57372012-08-31 12:12:28 -07001106 private void removeDirectoryRecursive(File parent) {
1107 if (parent.isDirectory()) {
1108 String[] files = parent.list();
1109 for (String filename : files) {
1110 File child = new File(parent, filename);
1111 removeDirectoryRecursive(child);
1112 }
1113 }
1114 parent.delete();
1115 }
1116
Amith Yamasani2a003292012-08-14 18:25:45 -07001117 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001118 public Bundle getApplicationRestrictions(String packageName) {
1119 return getApplicationRestrictionsForUser(packageName, UserHandle.getCallingUserId());
1120 }
1121
1122 @Override
1123 public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001124 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001125 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001126 checkManageUsersPermission("Only system can get restrictions for other users/apps");
1127 }
1128 synchronized (mPackagesLock) {
1129 // Read the restrictions from XML
1130 return readApplicationRestrictionsLocked(packageName, userId);
1131 }
1132 }
1133
1134 @Override
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001135 public void setApplicationRestrictions(String packageName, Bundle restrictions,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001136 int userId) {
1137 if (UserHandle.getCallingUserId() != userId
Amith Yamasani9429afb2013-04-10 18:40:51 -07001138 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001139 checkManageUsersPermission("Only system can set restrictions for other users/apps");
1140 }
1141 synchronized (mPackagesLock) {
1142 // Write the restrictions to XML
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001143 writeApplicationRestrictionsLocked(packageName, restrictions, userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001144 }
1145 }
1146
Amith Yamasani655d0e22013-06-12 14:19:10 -07001147 @Override
1148 public boolean changeRestrictionsPin(String newPin) {
1149 checkManageUsersPermission("Only system can modify the restrictions pin");
1150 int userId = UserHandle.getCallingUserId();
1151 synchronized (mPackagesLock) {
1152 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1153 if (pinState == null) {
1154 pinState = new RestrictionsPinState();
1155 }
1156 if (newPin == null) {
1157 pinState.salt = 0;
1158 pinState.pinHash = null;
1159 } else {
1160 try {
1161 pinState.salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
1162 } catch (NoSuchAlgorithmException e) {
1163 pinState.salt = (long) (Math.random() * Long.MAX_VALUE);
1164 }
1165 pinState.pinHash = passwordToHash(newPin, pinState.salt);
1166 pinState.failedAttempts = 0;
1167 }
1168 mRestrictionsPinStates.put(userId, pinState);
1169 writeUserLocked(mUsers.get(userId));
1170 }
1171 return true;
1172 }
1173
1174 @Override
1175 public int checkRestrictionsPin(String pin) {
1176 checkManageUsersPermission("Only system can verify the restrictions pin");
1177 int userId = UserHandle.getCallingUserId();
1178 synchronized (mPackagesLock) {
1179 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1180 // If there's no pin set, return error code
1181 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1182 return UserManager.PIN_VERIFICATION_FAILED_NOT_SET;
1183 } else if (pin == null) {
1184 // If just checking if user can be prompted, return remaining time
1185 int waitTime = getRemainingTimeForPinAttempt(pinState);
1186 Slog.d(LOG_TAG, "Remaining waittime peek=" + waitTime);
1187 return waitTime;
1188 } else {
1189 int waitTime = getRemainingTimeForPinAttempt(pinState);
1190 Slog.d(LOG_TAG, "Remaining waittime=" + waitTime);
1191 if (waitTime > 0) {
1192 return waitTime;
1193 }
1194 if (passwordToHash(pin, pinState.salt).equals(pinState.pinHash)) {
1195 pinState.failedAttempts = 0;
1196 writeUserLocked(mUsers.get(userId));
1197 return UserManager.PIN_VERIFICATION_SUCCESS;
1198 } else {
1199 pinState.failedAttempts++;
1200 pinState.lastAttemptTime = System.currentTimeMillis();
1201 writeUserLocked(mUsers.get(userId));
1202 return waitTime;
1203 }
1204 }
1205 }
1206 }
1207
1208 private int getRemainingTimeForPinAttempt(RestrictionsPinState pinState) {
1209 int backoffIndex = Math.min(pinState.failedAttempts / BACKOFF_INC_INTERVAL,
1210 BACKOFF_TIMES.length - 1);
1211 int backoffTime = (pinState.failedAttempts % BACKOFF_INC_INTERVAL) == 0 ?
1212 BACKOFF_TIMES[backoffIndex] : 0;
1213 return (int) Math.max(backoffTime + pinState.lastAttemptTime - System.currentTimeMillis(),
1214 0);
1215 }
1216
1217 @Override
1218 public boolean hasRestrictionsPin() {
1219 int userId = UserHandle.getCallingUserId();
1220 synchronized (mPackagesLock) {
Amith Yamasani0343ec32013-07-22 14:52:06 -07001221 return hasRestrictionsPinLocked(userId);
1222 }
1223 }
1224
1225 private boolean hasRestrictionsPinLocked(int userId) {
1226 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1227 if (pinState == null || pinState.salt == 0 || pinState.pinHash == null) {
1228 return false;
Amith Yamasani655d0e22013-06-12 14:19:10 -07001229 }
1230 return true;
1231 }
1232
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001233 @Override
1234 public void removeRestrictions() {
1235 checkManageUsersPermission("Only system can remove restrictions");
1236 final int userHandle = UserHandle.getCallingUserId();
Amith Yamasani350962c2013-08-06 11:18:53 -07001237 removeRestrictionsForUser(userHandle);
1238 }
1239
1240 private void removeRestrictionsForUser(final int userHandle) {
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001241 synchronized (mPackagesLock) {
1242 // Remove all user restrictions
1243 setUserRestrictions(new Bundle(), userHandle);
1244 // Remove restrictions pin
1245 changeRestrictionsPin(null);
1246 // Remove any app restrictions
1247 cleanAppRestrictions(userHandle, true);
1248 }
1249 mHandler.post(new Runnable() {
1250 @Override
1251 public void run() {
1252 List<ApplicationInfo> apps =
1253 mPm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES,
1254 userHandle).getList();
1255 final long ident = Binder.clearCallingIdentity();
1256 try {
1257 for (ApplicationInfo appInfo : apps) {
1258 if ((appInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0
1259 && (appInfo.flags & ApplicationInfo.FLAG_BLOCKED) != 0) {
1260 mPm.setApplicationBlockedSettingAsUser(appInfo.packageName, false,
1261 userHandle);
1262 }
1263 }
1264 } finally {
1265 Binder.restoreCallingIdentity(ident);
1266 }
1267 }
1268 });
1269 }
1270
Amith Yamasani655d0e22013-06-12 14:19:10 -07001271 /*
1272 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
1273 * Not the most secure, but it is at least a second level of protection. First level is that
1274 * the file is in a location only readable by the system process.
1275 * @param password the password.
1276 * @param salt the randomly generated salt
1277 * @return the hash of the pattern in a String.
1278 */
1279 private String passwordToHash(String password, long salt) {
1280 if (password == null) {
1281 return null;
1282 }
1283 String algo = null;
1284 String hashed = salt + password;
1285 try {
1286 byte[] saltedPassword = (password + salt).getBytes();
1287 byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
1288 byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
1289 hashed = toHex(sha1) + toHex(md5);
1290 } catch (NoSuchAlgorithmException e) {
1291 Log.w(LOG_TAG, "Failed to encode string because of missing algorithm: " + algo);
1292 }
1293 return hashed;
1294 }
1295
1296 private static String toHex(byte[] ary) {
1297 final String hex = "0123456789ABCDEF";
1298 String ret = "";
1299 for (int i = 0; i < ary.length; i++) {
1300 ret += hex.charAt((ary[i] >> 4) & 0xf);
1301 ret += hex.charAt(ary[i] & 0xf);
1302 }
1303 return ret;
1304 }
1305
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001306 private int getUidForPackage(String packageName) {
Amith Yamasani9429afb2013-04-10 18:40:51 -07001307 long ident = Binder.clearCallingIdentity();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001308 try {
1309 return mContext.getPackageManager().getApplicationInfo(packageName,
1310 PackageManager.GET_UNINSTALLED_PACKAGES).uid;
1311 } catch (NameNotFoundException nnfe) {
1312 return -1;
Amith Yamasani9429afb2013-04-10 18:40:51 -07001313 } finally {
1314 Binder.restoreCallingIdentity(ident);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001315 }
1316 }
1317
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001318 private Bundle readApplicationRestrictionsLocked(String packageName,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001319 int userId) {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001320 final Bundle restrictions = new Bundle();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001321 final ArrayList<String> values = new ArrayList<String>();
1322
1323 FileInputStream fis = null;
1324 try {
1325 AtomicFile restrictionsFile =
1326 new AtomicFile(new File(Environment.getUserSystemDirectory(userId),
1327 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1328 fis = restrictionsFile.openRead();
1329 XmlPullParser parser = Xml.newPullParser();
1330 parser.setInput(fis, null);
1331 int type;
1332 while ((type = parser.next()) != XmlPullParser.START_TAG
1333 && type != XmlPullParser.END_DOCUMENT) {
1334 ;
1335 }
1336
1337 if (type != XmlPullParser.START_TAG) {
1338 Slog.e(LOG_TAG, "Unable to read restrictions file "
1339 + restrictionsFile.getBaseFile());
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001340 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001341 }
1342
1343 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1344 if (type == XmlPullParser.START_TAG && parser.getName().equals(TAG_ENTRY)) {
1345 String key = parser.getAttributeValue(null, ATTR_KEY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001346 String valType = parser.getAttributeValue(null, ATTR_VALUE_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001347 String multiple = parser.getAttributeValue(null, ATTR_MULTIPLE);
1348 if (multiple != null) {
1349 int count = Integer.parseInt(multiple);
1350 while (count > 0 && (type = parser.next()) != XmlPullParser.END_DOCUMENT) {
1351 if (type == XmlPullParser.START_TAG
1352 && parser.getName().equals(TAG_VALUE)) {
1353 values.add(parser.nextText().trim());
1354 count--;
1355 }
1356 }
1357 String [] valueStrings = new String[values.size()];
1358 values.toArray(valueStrings);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001359 restrictions.putStringArray(key, valueStrings);
1360 } else if (ATTR_TYPE_BOOLEAN.equals(valType)) {
1361 restrictions.putBoolean(key, Boolean.parseBoolean(
1362 parser.nextText().trim()));
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001363 } else {
1364 String value = parser.nextText().trim();
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001365 restrictions.putString(key, value);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001366 }
1367 }
1368 }
1369
1370 } catch (IOException ioe) {
1371 } catch (XmlPullParserException pe) {
1372 } finally {
1373 if (fis != null) {
1374 try {
1375 fis.close();
1376 } catch (IOException e) {
1377 }
1378 }
1379 }
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001380 return restrictions;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001381 }
1382
1383 private void writeApplicationRestrictionsLocked(String packageName,
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001384 Bundle restrictions, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001385 FileOutputStream fos = null;
1386 AtomicFile restrictionsFile = new AtomicFile(
1387 new File(Environment.getUserSystemDirectory(userId),
1388 RESTRICTIONS_FILE_PREFIX + packageName + ".xml"));
1389 try {
1390 fos = restrictionsFile.startWrite();
1391 final BufferedOutputStream bos = new BufferedOutputStream(fos);
1392
1393 // XmlSerializer serializer = XmlUtils.serializerInstance();
1394 final XmlSerializer serializer = new FastXmlSerializer();
1395 serializer.setOutput(bos, "utf-8");
1396 serializer.startDocument(null, true);
1397 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1398
1399 serializer.startTag(null, TAG_RESTRICTIONS);
1400
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001401 for (String key : restrictions.keySet()) {
1402 Object value = restrictions.get(key);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001403 serializer.startTag(null, TAG_ENTRY);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001404 serializer.attribute(null, ATTR_KEY, key);
1405
1406 if (value instanceof Boolean) {
1407 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_BOOLEAN);
1408 serializer.text(value.toString());
1409 } else if (value == null || value instanceof String) {
1410 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING);
1411 serializer.text(value != null ? (String) value : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001412 } else {
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001413 serializer.attribute(null, ATTR_VALUE_TYPE, ATTR_TYPE_STRING_ARRAY);
1414 String[] values = (String[]) value;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001415 serializer.attribute(null, ATTR_MULTIPLE, Integer.toString(values.length));
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001416 for (String choice : values) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001417 serializer.startTag(null, TAG_VALUE);
Amith Yamasani7e99bc02013-04-16 18:24:51 -07001418 serializer.text(choice != null ? choice : "");
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001419 serializer.endTag(null, TAG_VALUE);
1420 }
1421 }
1422 serializer.endTag(null, TAG_ENTRY);
1423 }
1424
1425 serializer.endTag(null, TAG_RESTRICTIONS);
1426
1427 serializer.endDocument();
1428 restrictionsFile.finishWrite(fos);
1429 } catch (Exception e) {
1430 restrictionsFile.failWrite(fos);
1431 Slog.e(LOG_TAG, "Error writing application restrictions list");
1432 }
1433 }
1434
1435 @Override
Amith Yamasani2a003292012-08-14 18:25:45 -07001436 public int getUserSerialNumber(int userHandle) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001437 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001438 if (!exists(userHandle)) return -1;
Amith Yamasani195263742012-08-21 15:40:12 -07001439 return getUserInfoLocked(userHandle).serialNumber;
Amith Yamasani2a003292012-08-14 18:25:45 -07001440 }
1441 }
1442
1443 @Override
1444 public int getUserHandle(int userSerialNumber) {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001445 synchronized (mPackagesLock) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001446 for (int userId : mUserIds) {
Amith Yamasani195263742012-08-21 15:40:12 -07001447 if (getUserInfoLocked(userId).serialNumber == userSerialNumber) return userId;
Amith Yamasani2a003292012-08-14 18:25:45 -07001448 }
1449 // Not found
1450 return -1;
Amith Yamasani13593602012-03-22 16:16:17 -07001451 }
1452 }
1453
Amith Yamasani0b285492011-04-14 17:35:23 -07001454 /**
1455 * Caches the list of user ids in an array, adjusting the array size when necessary.
1456 */
Amith Yamasani13593602012-03-22 16:16:17 -07001457 private void updateUserIdsLocked() {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001458 int num = 0;
Amith Yamasani0b285492011-04-14 17:35:23 -07001459 for (int i = 0; i < mUsers.size(); i++) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001460 if (!mUsers.valueAt(i).partial) {
1461 num++;
1462 }
1463 }
Amith Yamasani16389312012-10-17 21:20:14 -07001464 final int[] newUsers = new int[num];
1465 int n = 0;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001466 for (int i = 0; i < mUsers.size(); i++) {
1467 if (!mUsers.valueAt(i).partial) {
Amith Yamasani16389312012-10-17 21:20:14 -07001468 newUsers[n++] = mUsers.keyAt(i);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001469 }
Amith Yamasani0b285492011-04-14 17:35:23 -07001470 }
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001471 mUserIds = newUsers;
Amith Yamasani0b285492011-04-14 17:35:23 -07001472 }
1473
1474 /**
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001475 * Make a note of the last started time of a user and do some cleanup.
Amith Yamasani920ace02012-09-20 22:15:37 -07001476 * @param userId the user that was just foregrounded
1477 */
1478 public void userForeground(int userId) {
1479 synchronized (mPackagesLock) {
1480 UserInfo user = mUsers.get(userId);
1481 long now = System.currentTimeMillis();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001482 if (user == null || user.partial) {
1483 Slog.w(LOG_TAG, "userForeground: unknown user #" + userId);
1484 return;
1485 }
1486 if (now > EPOCH_PLUS_30_YEARS) {
Amith Yamasani920ace02012-09-20 22:15:37 -07001487 user.lastLoggedInTime = now;
1488 writeUserLocked(user);
1489 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001490 // If this is not a restricted profile and there is no restrictions pin, clean up
1491 // all restrictions files that might have been left behind, else clean up just the
1492 // ones with uninstalled packages
1493 RestrictionsPinState pinState = mRestrictionsPinStates.get(userId);
1494 final long salt = pinState == null ? 0 : pinState.salt;
1495 cleanAppRestrictions(userId, (!user.isRestricted() && salt == 0));
Amith Yamasani920ace02012-09-20 22:15:37 -07001496 }
1497 }
1498
1499 /**
Amith Yamasani0b285492011-04-14 17:35:23 -07001500 * Returns the next available user id, filling in any holes in the ids.
Amith Yamasani742a6712011-05-04 14:49:28 -07001501 * TODO: May not be a good idea to recycle ids, in case it results in confusion
1502 * for data and battery stats collection, or unexpected cross-talk.
Amith Yamasani0b285492011-04-14 17:35:23 -07001503 * @return
1504 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001505 private int getNextAvailableIdLocked() {
Dianne Hackborn4428e172012-08-24 17:43:05 -07001506 synchronized (mPackagesLock) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001507 int i = MIN_USER_ID;
Amith Yamasani195263742012-08-21 15:40:12 -07001508 while (i < Integer.MAX_VALUE) {
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001509 if (mUsers.indexOfKey(i) < 0 && !mRemovingUserIds.get(i)) {
Amith Yamasani195263742012-08-21 15:40:12 -07001510 break;
1511 }
1512 i++;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001513 }
Amith Yamasani195263742012-08-21 15:40:12 -07001514 return i;
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001515 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001516 }
Amith Yamasani920ace02012-09-20 22:15:37 -07001517
1518 @Override
1519 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1520 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1521 != PackageManager.PERMISSION_GRANTED) {
1522 pw.println("Permission Denial: can't dump UserManager from from pid="
1523 + Binder.getCallingPid()
1524 + ", uid=" + Binder.getCallingUid()
1525 + " without permission "
1526 + android.Manifest.permission.DUMP);
1527 return;
1528 }
1529
1530 long now = System.currentTimeMillis();
1531 StringBuilder sb = new StringBuilder();
1532 synchronized (mPackagesLock) {
1533 pw.println("Users:");
1534 for (int i = 0; i < mUsers.size(); i++) {
1535 UserInfo user = mUsers.valueAt(i);
1536 if (user == null) continue;
Amith Yamasani634cf312012-10-04 17:34:21 -07001537 pw.print(" "); pw.print(user); pw.print(" serialNo="); pw.print(user.serialNumber);
Jeff Sharkeyffe0cb42012-11-05 17:24:43 -08001538 if (mRemovingUserIds.get(mUsers.keyAt(i))) pw.print(" <removing> ");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001539 if (user.partial) pw.print(" <partial>");
1540 pw.println();
Amith Yamasani920ace02012-09-20 22:15:37 -07001541 pw.print(" Created: ");
1542 if (user.creationTime == 0) {
1543 pw.println("<unknown>");
1544 } else {
1545 sb.setLength(0);
1546 TimeUtils.formatDuration(now - user.creationTime, sb);
1547 sb.append(" ago");
1548 pw.println(sb);
1549 }
1550 pw.print(" Last logged in: ");
1551 if (user.lastLoggedInTime == 0) {
1552 pw.println("<unknown>");
1553 } else {
1554 sb.setLength(0);
1555 TimeUtils.formatDuration(now - user.lastLoggedInTime, sb);
1556 sb.append(" ago");
1557 pw.println(sb);
1558 }
1559 }
1560 }
1561 }
Amith Yamasani1a7472e2013-07-02 11:17:30 -07001562
1563 private PackageMonitor mUserPackageMonitor = new PackageMonitor() {
1564 @Override
1565 public void onPackageRemoved(String pkg, int uid) {
1566 final int userId = this.getChangingUserId();
1567 // Package could be disappearing because it is being blocked, so also check if
1568 // it has been uninstalled.
1569 final boolean uninstalled = isPackageDisappearing(pkg) == PACKAGE_PERMANENT_CHANGE;
1570 if (uninstalled && userId >= 0 && !isPackageInstalled(pkg, userId)) {
1571 cleanAppRestrictionsForPackage(pkg, userId);
1572 }
1573 }
1574 };
Amith Yamasani4b2e9342011-03-31 12:38:53 -07001575}