DevicePolicyManagerService.java revision 0c606812c5102fd19eda4b3e1ffbc9e61fec6430
1/*
2 * Copyright (C) 2010 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.devicepolicy;
18
19import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
20import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24
25import android.accessibilityservice.AccessibilityServiceInfo;
26import android.accounts.AccountManager;
27import android.app.Activity;
28import android.app.ActivityManagerNative;
29import android.app.AlarmManager;
30import android.app.AppGlobals;
31import android.app.IActivityManager;
32import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
35import android.app.admin.DeviceAdminInfo;
36import android.app.admin.DeviceAdminReceiver;
37import android.app.admin.DevicePolicyManager;
38import android.app.admin.DevicePolicyManagerInternal;
39import android.app.admin.IDevicePolicyManager;
40import android.app.backup.IBackupManager;
41import android.content.BroadcastReceiver;
42import android.content.ComponentName;
43import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
46import android.content.IntentFilter;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.IPackageManager;
49import android.content.pm.PackageManager;
50import android.content.pm.PackageManager.NameNotFoundException;
51import android.content.pm.ResolveInfo;
52import android.content.pm.ServiceInfo;
53import android.content.pm.UserInfo;
54import android.database.ContentObserver;
55import android.graphics.Bitmap;
56import android.hardware.usb.UsbManager;
57import android.media.AudioManager;
58import android.media.IAudioService;
59import android.net.ConnectivityManager;
60import android.net.ProxyInfo;
61import android.net.Uri;
62import android.os.AsyncTask;
63import android.os.Binder;
64import android.os.Bundle;
65import android.os.Environment;
66import android.os.FileUtils;
67import android.os.Handler;
68import android.os.IBinder;
69import android.os.PersistableBundle;
70import android.os.PowerManager;
71import android.os.PowerManagerInternal;
72import android.os.Process;
73import android.os.RecoverySystem;
74import android.os.RemoteCallback;
75import android.os.RemoteException;
76import android.os.ServiceManager;
77import android.os.SystemClock;
78import android.os.SystemProperties;
79import android.os.UserHandle;
80import android.os.UserManager;
81import android.provider.ContactsContract.QuickContact;
82import android.provider.ContactsInternal;
83import android.provider.Settings;
84import android.security.Credentials;
85import android.security.IKeyChainAliasCallback;
86import android.security.IKeyChainService;
87import android.security.KeyChain;
88import android.security.KeyChain.KeyChainConnection;
89import android.text.TextUtils;
90import android.service.persistentdata.PersistentDataBlockManager;
91import android.util.Log;
92import android.util.PrintWriterPrinter;
93import android.util.Printer;
94import android.util.Slog;
95import android.util.SparseArray;
96import android.util.Xml;
97import android.view.accessibility.AccessibilityManager;
98import android.view.accessibility.IAccessibilityManager;
99import android.view.inputmethod.InputMethodInfo;
100import android.view.inputmethod.InputMethodManager;
101import android.view.IWindowManager;
102
103import com.android.internal.R;
104import com.android.internal.os.storage.ExternalStorageFormatter;
105import com.android.internal.util.FastXmlSerializer;
106import com.android.internal.util.JournaledFile;
107import com.android.internal.util.Preconditions;
108import com.android.internal.util.XmlUtils;
109import com.android.internal.widget.LockPatternUtils;
110import com.android.server.LocalServices;
111import com.android.server.SystemService;
112import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
113
114import org.xmlpull.v1.XmlPullParser;
115
116import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
117import static org.xmlpull.v1.XmlPullParser.END_TAG;
118import static org.xmlpull.v1.XmlPullParser.TEXT;
119
120import org.xmlpull.v1.XmlPullParserException;
121import org.xmlpull.v1.XmlSerializer;
122
123import java.io.ByteArrayInputStream;
124import java.io.File;
125import java.io.FileDescriptor;
126import java.io.FileInputStream;
127import java.io.FileNotFoundException;
128import java.io.FileOutputStream;
129import java.io.IOException;
130import java.io.PrintWriter;
131import java.security.cert.CertificateException;
132import java.security.cert.CertificateFactory;
133import java.security.cert.X509Certificate;
134import java.text.DateFormat;
135import java.util.ArrayList;
136import java.util.Collections;
137import java.util.Date;
138import java.util.HashMap;
139import java.util.HashSet;
140import java.util.List;
141import java.util.Map.Entry;
142import java.util.Set;
143
144/**
145 * Implementation of the device policy APIs.
146 */
147public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
148
149    private static final String LOG_TAG = "DevicePolicyManagerService";
150
151    private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
152
153    private static final String DEVICE_POLICIES_XML = "device_policies.xml";
154
155    private static final String LOCK_TASK_COMPONENTS_XML = "lock-task-component";
156
157    private static final int REQUEST_EXPIRE_PASSWORD = 5571;
158
159    private static final long MS_PER_DAY = 86400 * 1000;
160
161    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
162
163    protected static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
164            = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
165
166    private static final int MONITORING_CERT_NOTIFICATION_ID = R.string.ssl_ca_cert_warning;
167
168    private static final boolean DBG = false;
169
170    private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
171    private static final String ATTR_SETUP_COMPLETE = "setup-complete";
172
173    private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
174
175    private static final Set<String> DEVICE_OWNER_USER_RESTRICTIONS;
176    static {
177        DEVICE_OWNER_USER_RESTRICTIONS = new HashSet();
178        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_USB_FILE_TRANSFER);
179        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_TETHERING);
180        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_FACTORY_RESET);
181        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADD_USER);
182        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS);
183        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
184        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA);
185        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_UNMUTE_MICROPHONE);
186        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_ADJUST_VOLUME);
187        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SMS);
188        DEVICE_OWNER_USER_RESTRICTIONS.add(UserManager.DISALLOW_SAFE_BOOT);
189    }
190
191    // The following user restrictions cannot be changed by any active admin, including device
192    // owner and profile owner.
193    private static final Set<String> IMMUTABLE_USER_RESTRICTIONS;
194    static {
195        IMMUTABLE_USER_RESTRICTIONS = new HashSet();
196        IMMUTABLE_USER_RESTRICTIONS.add(UserManager.DISALLOW_WALLPAPER);
197    }
198
199    private static final Set<String> SECURE_SETTINGS_WHITELIST;
200    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
201    private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
202    static {
203        SECURE_SETTINGS_WHITELIST = new HashSet();
204        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
205        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
206        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
207
208        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new HashSet();
209        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
210        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
211
212        GLOBAL_SETTINGS_WHITELIST = new HashSet();
213        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
214        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
215        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
216        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
217        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
218        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.MODE_RINGER);
219        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.NETWORK_PREFERENCE);
220        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
221        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
222        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
223    }
224
225    final Context mContext;
226    final UserManager mUserManager;
227    final PowerManager.WakeLock mWakeLock;
228
229    final LocalService mLocalService;
230
231    final PowerManager mPowerManager;
232    final PowerManagerInternal mPowerManagerInternal;
233
234    IWindowManager mIWindowManager;
235    NotificationManager mNotificationManager;
236
237    // Stores and loads state on device and profile owners.
238    private DeviceOwner mDeviceOwner;
239
240    /**
241     * Whether or not device admin feature is supported. If it isn't return defaults for all
242     * public methods.
243     */
244    private boolean mHasFeature;
245
246    public static final class Lifecycle extends SystemService {
247        private DevicePolicyManagerService mService;
248
249        public Lifecycle(Context context) {
250            super(context);
251            mService = new DevicePolicyManagerService(context);
252        }
253
254        @Override
255        public void onStart() {
256            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
257        }
258
259        @Override
260        public void onBootPhase(int phase) {
261            if (phase == PHASE_LOCK_SETTINGS_READY) {
262                mService.systemReady();
263            }
264        }
265    }
266
267    public static class DevicePolicyData {
268        int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
269        int mActivePasswordLength = 0;
270        int mActivePasswordUpperCase = 0;
271        int mActivePasswordLowerCase = 0;
272        int mActivePasswordLetters = 0;
273        int mActivePasswordNumeric = 0;
274        int mActivePasswordSymbols = 0;
275        int mActivePasswordNonLetter = 0;
276        int mFailedPasswordAttempts = 0;
277
278        int mUserHandle;
279        int mPasswordOwner = -1;
280        long mLastMaximumTimeToLock = -1;
281        boolean mUserSetupComplete = false;
282
283        final HashMap<ComponentName, ActiveAdmin> mAdminMap = new HashMap<>();
284        final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
285        final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
286
287        // This is the list of component allowed to start lock task mode.
288        final List<String> mLockTaskPackages = new ArrayList<>();
289
290        ComponentName mRestrictionsProvider;
291
292        String mDelegatedCertInstallerPackage;
293
294        public DevicePolicyData(int userHandle) {
295            mUserHandle = userHandle;
296        }
297    }
298
299    final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
300
301    Handler mHandler = new Handler();
302
303    BroadcastReceiver mReceiver = new BroadcastReceiver() {
304        @Override
305        public void onReceive(Context context, Intent intent) {
306            final String action = intent.getAction();
307            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
308                    getSendingUserId());
309            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
310                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
311                if (DBG) Slog.v(LOG_TAG, "Sending password expiration notifications for action "
312                        + action + " for user " + userHandle);
313                mHandler.post(new Runnable() {
314                    public void run() {
315                        handlePasswordExpirationNotification(userHandle);
316                    }
317                });
318            }
319            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
320                    || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
321                new MonitoringCertNotificationTask().execute(intent);
322            }
323            if (Intent.ACTION_USER_REMOVED.equals(action)) {
324                removeUserData(userHandle);
325            } else if (Intent.ACTION_USER_STARTED.equals(action)
326                    || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
327
328                if (Intent.ACTION_USER_STARTED.equals(action)) {
329                    // Reset the policy data
330                    synchronized (DevicePolicyManagerService.this) {
331                        mUserData.remove(userHandle);
332                    }
333                }
334                handlePackagesChanged(null /* check all admins */, userHandle);
335            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
336                    || (Intent.ACTION_PACKAGE_ADDED.equals(action)
337                            && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
338                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
339            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
340                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
341                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
342            }
343        }
344    };
345
346    static class ActiveAdmin {
347        private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
348        private static final String TAG_DISABLE_CAMERA = "disable-camera";
349        private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
350        private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
351                = "disable-bt-contacts-sharing";
352        private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
353        private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
354        private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
355        private static final String TAG_ACCOUNT_TYPE = "account-type";
356        private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
357                = "permitted-accessiblity-services";
358        private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
359        private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
360        private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
361        private static final String TAG_TRUST_AGENT_COMPONENT = "component";
362        private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
363        private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
364        private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
365        private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
366        private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
367        private static final String TAG_PERMITTED_IMES = "permitted-imes";
368        private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
369        private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
370        private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
371        private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
372        private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
373        private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
374        private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
375        private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
376        private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
377        private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
378        private static final String ATTR_VALUE = "value";
379        private static final String TAG_PASSWORD_QUALITY = "password-quality";
380        private static final String TAG_POLICIES = "policies";
381        private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
382                "cross-profile-widget-providers";
383        private static final String TAG_PROVIDER = "provider";
384        private static final String TAG_PACKAGE_LIST_ITEM  = "item";
385
386        final DeviceAdminInfo info;
387
388        int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
389
390        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
391        int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
392
393        static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
394        int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
395
396        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
397        int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
398
399        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
400        int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
401
402        static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
403        int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
404
405        static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
406        int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
407
408        static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
409        int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
410
411        static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
412        int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
413
414        static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
415        long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
416
417        static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
418        int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
419
420        static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
421        long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
422
423        static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
424        long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
425
426        static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
427
428        int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
429
430        boolean encryptionRequested = false;
431        boolean disableCamera = false;
432        boolean disableCallerId = false;
433        boolean disableBluetoothContactSharing = true;
434        boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
435        boolean requireAutoTime = false; // Can only be set by a device owner.
436
437        static class TrustAgentInfo {
438            public PersistableBundle options;
439            TrustAgentInfo(PersistableBundle bundle) {
440                options = bundle;
441            }
442        }
443
444        Set<String> accountTypesWithManagementDisabled = new HashSet<String>();
445
446        // The list of permitted accessibility services package namesas set by a profile
447        // or device owner. Null means all accessibility services are allowed, empty means
448        // none except system services are allowed.
449        List<String> permittedAccessiblityServices;
450
451        // The list of permitted input methods package names as set by a profile or device owner.
452        // Null means all input methods are allowed, empty means none except system imes are
453        // allowed.
454        List<String> permittedInputMethods;
455
456        // TODO: review implementation decisions with frameworks team
457        boolean specifiesGlobalProxy = false;
458        String globalProxySpec = null;
459        String globalProxyExclusionList = null;
460
461        HashMap<String, TrustAgentInfo> trustAgentInfos = new HashMap<String, TrustAgentInfo>();
462
463        List<String> crossProfileWidgetProviders;
464
465        ActiveAdmin(DeviceAdminInfo _info) {
466            info = _info;
467        }
468
469        int getUid() { return info.getActivityInfo().applicationInfo.uid; }
470
471        public UserHandle getUserHandle() {
472            return new UserHandle(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
473        }
474
475        void writeToXml(XmlSerializer out)
476                throws IllegalArgumentException, IllegalStateException, IOException {
477            out.startTag(null, TAG_POLICIES);
478            info.writePoliciesToXml(out);
479            out.endTag(null, TAG_POLICIES);
480            if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
481                out.startTag(null, TAG_PASSWORD_QUALITY);
482                out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
483                out.endTag(null, TAG_PASSWORD_QUALITY);
484                if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
485                    out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
486                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
487                    out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
488                }
489                if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
490                    out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
491                    out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
492                    out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
493                }
494                if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
495                    out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
496                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
497                    out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
498                }
499                if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
500                    out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
501                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
502                    out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
503                }
504                if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
505                    out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
506                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
507                    out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
508                }
509                if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
510                    out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
511                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
512                    out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
513                }
514                if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
515                    out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
516                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
517                    out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
518                }
519                if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
520                    out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
521                    out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
522                    out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
523                }
524            }
525            if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
526                out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
527                out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
528                out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
529            }
530            if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
531                out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
532                out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
533                out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
534            }
535            if (specifiesGlobalProxy) {
536                out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
537                out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
538                out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
539                if (globalProxySpec != null) {
540                    out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
541                    out.attribute(null, ATTR_VALUE, globalProxySpec);
542                    out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
543                }
544                if (globalProxyExclusionList != null) {
545                    out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
546                    out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
547                    out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
548                }
549            }
550            if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
551                out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
552                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
553                out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
554            }
555            if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
556                out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
557                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
558                out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
559            }
560            if (encryptionRequested) {
561                out.startTag(null, TAG_ENCRYPTION_REQUESTED);
562                out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
563                out.endTag(null, TAG_ENCRYPTION_REQUESTED);
564            }
565            if (disableCamera) {
566                out.startTag(null, TAG_DISABLE_CAMERA);
567                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
568                out.endTag(null, TAG_DISABLE_CAMERA);
569            }
570            if (disableCallerId) {
571                out.startTag(null, TAG_DISABLE_CALLER_ID);
572                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
573                out.endTag(null, TAG_DISABLE_CALLER_ID);
574            }
575            if (disableBluetoothContactSharing) {
576                out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
577                out.attribute(null, ATTR_VALUE,
578                        Boolean.toString(disableBluetoothContactSharing));
579                out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
580            }
581            if (disableScreenCapture) {
582                out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
583                out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
584                out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
585            }
586            if (requireAutoTime) {
587                out.startTag(null, TAG_REQUIRE_AUTO_TIME);
588                out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
589                out.endTag(null, TAG_REQUIRE_AUTO_TIME);
590            }
591            if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
592                out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
593                out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
594                out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
595            }
596            if (!accountTypesWithManagementDisabled.isEmpty()) {
597                out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
598                for (String ac : accountTypesWithManagementDisabled) {
599                    out.startTag(null, TAG_ACCOUNT_TYPE);
600                    out.attribute(null, ATTR_VALUE, ac);
601                    out.endTag(null, TAG_ACCOUNT_TYPE);
602                }
603                out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
604            }
605            if (!trustAgentInfos.isEmpty()) {
606                Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
607                out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
608                for (Entry<String, TrustAgentInfo> entry : set) {
609                    TrustAgentInfo trustAgentInfo = entry.getValue();
610                    out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
611                    out.attribute(null, ATTR_VALUE, entry.getKey());
612                    if (trustAgentInfo.options != null) {
613                        out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
614                        try {
615                            trustAgentInfo.options.saveToXml(out);
616                        } catch (XmlPullParserException e) {
617                            Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
618                        }
619                        out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
620                    }
621                    out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
622                }
623                out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
624            }
625            if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
626                out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
627                final int providerCount = crossProfileWidgetProviders.size();
628                for (int i = 0; i < providerCount; i++) {
629                    String provider = crossProfileWidgetProviders.get(i);
630                    out.startTag(null, TAG_PROVIDER);
631                    out.attribute(null, ATTR_VALUE, provider);
632                    out.endTag(null, TAG_PROVIDER);
633                }
634                out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
635            }
636            writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
637                    permittedAccessiblityServices);
638            writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
639        }
640
641        void writePackageListToXml(XmlSerializer out, String outerTag,
642                List<String> packageList)
643                throws IllegalArgumentException, IllegalStateException, IOException {
644            if (packageList == null) {
645                return;
646            }
647
648            out.startTag(null, outerTag);
649            for (String packageName : packageList) {
650                out.startTag(null, TAG_PACKAGE_LIST_ITEM);
651                out.attribute(null, ATTR_VALUE, packageName);
652                out.endTag(null, TAG_PACKAGE_LIST_ITEM);
653            }
654            out.endTag(null, outerTag);
655        }
656
657        void readFromXml(XmlPullParser parser)
658                throws XmlPullParserException, IOException {
659            int outerDepth = parser.getDepth();
660            int type;
661            while ((type=parser.next()) != END_DOCUMENT
662                   && (type != END_TAG || parser.getDepth() > outerDepth)) {
663                if (type == END_TAG || type == TEXT) {
664                    continue;
665                }
666                String tag = parser.getName();
667                if (TAG_POLICIES.equals(tag)) {
668                    info.readPoliciesFromXml(parser);
669                } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
670                    passwordQuality = Integer.parseInt(
671                            parser.getAttributeValue(null, ATTR_VALUE));
672                } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
673                    minimumPasswordLength = Integer.parseInt(
674                            parser.getAttributeValue(null, ATTR_VALUE));
675                } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
676                    passwordHistoryLength = Integer.parseInt(
677                            parser.getAttributeValue(null, ATTR_VALUE));
678                } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
679                    minimumPasswordUpperCase = Integer.parseInt(
680                            parser.getAttributeValue(null, ATTR_VALUE));
681                } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
682                    minimumPasswordLowerCase = Integer.parseInt(
683                            parser.getAttributeValue(null, ATTR_VALUE));
684                } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
685                    minimumPasswordLetters = Integer.parseInt(
686                            parser.getAttributeValue(null, ATTR_VALUE));
687                } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
688                    minimumPasswordNumeric = Integer.parseInt(
689                            parser.getAttributeValue(null, ATTR_VALUE));
690                } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
691                    minimumPasswordSymbols = Integer.parseInt(
692                            parser.getAttributeValue(null, ATTR_VALUE));
693                } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
694                    minimumPasswordNonLetter = Integer.parseInt(
695                            parser.getAttributeValue(null, ATTR_VALUE));
696                } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
697                    maximumTimeToUnlock = Long.parseLong(
698                            parser.getAttributeValue(null, ATTR_VALUE));
699                } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
700                    maximumFailedPasswordsForWipe = Integer.parseInt(
701                            parser.getAttributeValue(null, ATTR_VALUE));
702                } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
703                    specifiesGlobalProxy = Boolean.parseBoolean(
704                            parser.getAttributeValue(null, ATTR_VALUE));
705                } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
706                    globalProxySpec =
707                        parser.getAttributeValue(null, ATTR_VALUE);
708                } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
709                    globalProxyExclusionList =
710                        parser.getAttributeValue(null, ATTR_VALUE);
711                } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
712                    passwordExpirationTimeout = Long.parseLong(
713                            parser.getAttributeValue(null, ATTR_VALUE));
714                } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
715                    passwordExpirationDate = Long.parseLong(
716                            parser.getAttributeValue(null, ATTR_VALUE));
717                } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
718                    encryptionRequested = Boolean.parseBoolean(
719                            parser.getAttributeValue(null, ATTR_VALUE));
720                } else if (TAG_DISABLE_CAMERA.equals(tag)) {
721                    disableCamera = Boolean.parseBoolean(
722                            parser.getAttributeValue(null, ATTR_VALUE));
723                } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
724                    disableCallerId = Boolean.parseBoolean(
725                            parser.getAttributeValue(null, ATTR_VALUE));
726                } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
727                    disableBluetoothContactSharing = Boolean.parseBoolean(parser
728                            .getAttributeValue(null, ATTR_VALUE));
729                } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
730                    disableScreenCapture = Boolean.parseBoolean(
731                            parser.getAttributeValue(null, ATTR_VALUE));
732                } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
733                    requireAutoTime= Boolean.parseBoolean(
734                            parser.getAttributeValue(null, ATTR_VALUE));
735                } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
736                    disabledKeyguardFeatures = Integer.parseInt(
737                            parser.getAttributeValue(null, ATTR_VALUE));
738                } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
739                    accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
740                } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
741                    trustAgentInfos = getAllTrustAgentInfos(parser, tag);
742                } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
743                    crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
744                } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
745                    permittedAccessiblityServices = readPackageList(parser, tag);
746                } else if (TAG_PERMITTED_IMES.equals(tag)) {
747                    permittedInputMethods = readPackageList(parser, tag);
748                } else {
749                    Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
750                }
751                XmlUtils.skipCurrentTag(parser);
752            }
753        }
754
755        private List<String> readPackageList(XmlPullParser parser,
756                String tag) throws XmlPullParserException, IOException {
757            List<String> result = new ArrayList<String>();
758            int outerDepth = parser.getDepth();
759            int outerType;
760            while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
761                    && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
762                if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
763                    continue;
764                }
765                String outerTag = parser.getName();
766                if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
767                    String packageName = parser.getAttributeValue(null, ATTR_VALUE);
768                    if (packageName != null) {
769                        result.add(packageName);
770                    } else {
771                        Slog.w(LOG_TAG, "Package name missing under " + outerTag);
772                    }
773                } else {
774                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
775                }
776            }
777            return result;
778        }
779
780        private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
781                throws XmlPullParserException, IOException {
782            int outerDepthDAM = parser.getDepth();
783            int typeDAM;
784            Set<String> result = new HashSet<String>();
785            while ((typeDAM=parser.next()) != END_DOCUMENT
786                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
787                if (typeDAM == END_TAG || typeDAM == TEXT) {
788                    continue;
789                }
790                String tagDAM = parser.getName();
791                if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
792                    result.add(parser.getAttributeValue(null, ATTR_VALUE));
793                } else {
794                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
795                }
796            }
797            return result;
798        }
799
800        private HashMap<String, TrustAgentInfo> getAllTrustAgentInfos(
801                XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
802            int outerDepthDAM = parser.getDepth();
803            int typeDAM;
804            HashMap<String, TrustAgentInfo> result = new HashMap<String, TrustAgentInfo>();
805            while ((typeDAM=parser.next()) != END_DOCUMENT
806                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
807                if (typeDAM == END_TAG || typeDAM == TEXT) {
808                    continue;
809                }
810                String tagDAM = parser.getName();
811                if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
812                    final String component = parser.getAttributeValue(null, ATTR_VALUE);
813                    final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
814                    result.put(component, trustAgentInfo);
815                } else {
816                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
817                }
818            }
819            return result;
820        }
821
822        private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
823                throws XmlPullParserException, IOException  {
824            int outerDepthDAM = parser.getDepth();
825            int typeDAM;
826            TrustAgentInfo result = new TrustAgentInfo(null);
827            while ((typeDAM=parser.next()) != END_DOCUMENT
828                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
829                if (typeDAM == END_TAG || typeDAM == TEXT) {
830                    continue;
831                }
832                String tagDAM = parser.getName();
833                if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
834                    PersistableBundle bundle = new PersistableBundle();
835                    bundle.restoreFromXml(parser);
836                    result.options = bundle;
837                } else {
838                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
839                }
840            }
841            return result;
842        }
843
844        private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
845                throws XmlPullParserException, IOException  {
846            int outerDepthDAM = parser.getDepth();
847            int typeDAM;
848            ArrayList<String> result = null;
849            while ((typeDAM=parser.next()) != END_DOCUMENT
850                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
851                if (typeDAM == END_TAG || typeDAM == TEXT) {
852                    continue;
853                }
854                String tagDAM = parser.getName();
855                if (TAG_PROVIDER.equals(tagDAM)) {
856                    final String provider = parser.getAttributeValue(null, ATTR_VALUE);
857                    if (result == null) {
858                        result = new ArrayList<>();
859                    }
860                    result.add(provider);
861                } else {
862                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
863                }
864            }
865            return result;
866        }
867
868        void dump(String prefix, PrintWriter pw) {
869            pw.print(prefix); pw.print("uid="); pw.println(getUid());
870            pw.print(prefix); pw.println("policies:");
871            ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
872            if (pols != null) {
873                for (int i=0; i<pols.size(); i++) {
874                    pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
875                }
876            }
877            pw.print(prefix); pw.print("passwordQuality=0x");
878                    pw.println(Integer.toHexString(passwordQuality));
879            pw.print(prefix); pw.print("minimumPasswordLength=");
880                    pw.println(minimumPasswordLength);
881            pw.print(prefix); pw.print("passwordHistoryLength=");
882                    pw.println(passwordHistoryLength);
883            pw.print(prefix); pw.print("minimumPasswordUpperCase=");
884                    pw.println(minimumPasswordUpperCase);
885            pw.print(prefix); pw.print("minimumPasswordLowerCase=");
886                    pw.println(minimumPasswordLowerCase);
887            pw.print(prefix); pw.print("minimumPasswordLetters=");
888                    pw.println(minimumPasswordLetters);
889            pw.print(prefix); pw.print("minimumPasswordNumeric=");
890                    pw.println(minimumPasswordNumeric);
891            pw.print(prefix); pw.print("minimumPasswordSymbols=");
892                    pw.println(minimumPasswordSymbols);
893            pw.print(prefix); pw.print("minimumPasswordNonLetter=");
894                    pw.println(minimumPasswordNonLetter);
895            pw.print(prefix); pw.print("maximumTimeToUnlock=");
896                    pw.println(maximumTimeToUnlock);
897            pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
898                    pw.println(maximumFailedPasswordsForWipe);
899            pw.print(prefix); pw.print("specifiesGlobalProxy=");
900                    pw.println(specifiesGlobalProxy);
901            pw.print(prefix); pw.print("passwordExpirationTimeout=");
902                    pw.println(passwordExpirationTimeout);
903            pw.print(prefix); pw.print("passwordExpirationDate=");
904                    pw.println(passwordExpirationDate);
905            if (globalProxySpec != null) {
906                pw.print(prefix); pw.print("globalProxySpec=");
907                        pw.println(globalProxySpec);
908            }
909            if (globalProxyExclusionList != null) {
910                pw.print(prefix); pw.print("globalProxyEclusionList=");
911                        pw.println(globalProxyExclusionList);
912            }
913            pw.print(prefix); pw.print("encryptionRequested=");
914                    pw.println(encryptionRequested);
915            pw.print(prefix); pw.print("disableCamera=");
916                    pw.println(disableCamera);
917            pw.print(prefix); pw.print("disableCallerId=");
918                    pw.println(disableCallerId);
919            pw.print(prefix); pw.print("disableBluetoothContactSharing=");
920                    pw.println(disableBluetoothContactSharing);
921            pw.print(prefix); pw.print("disableScreenCapture=");
922                    pw.println(disableScreenCapture);
923            pw.print(prefix); pw.print("requireAutoTime=");
924                    pw.println(requireAutoTime);
925            pw.print(prefix); pw.print("disabledKeyguardFeatures=");
926                    pw.println(disabledKeyguardFeatures);
927            pw.print(prefix); pw.print("crossProfileWidgetProviders=");
928                    pw.println(crossProfileWidgetProviders);
929            if (!(permittedAccessiblityServices == null)) {
930                pw.print(prefix); pw.print("permittedAccessibilityServices=");
931                        pw.println(permittedAccessiblityServices.toString());
932            }
933            if (!(permittedInputMethods == null)) {
934                pw.print(prefix); pw.print("permittedInputMethods=");
935                        pw.println(permittedInputMethods.toString());
936            }
937        }
938    }
939
940    private void handlePackagesChanged(String packageName, int userHandle) {
941        boolean removed = false;
942        if (DBG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
943        DevicePolicyData policy = getUserData(userHandle);
944        IPackageManager pm = AppGlobals.getPackageManager();
945        synchronized (this) {
946            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
947                ActiveAdmin aa = policy.mAdminList.get(i);
948                try {
949                    // If we're checking all packages or if the specific one we're checking matches,
950                    // then check if the package and receiver still exist.
951                    final String adminPackage = aa.info.getPackageName();
952                    if (packageName == null || packageName.equals(adminPackage)) {
953                        if (pm.getPackageInfo(adminPackage, 0, userHandle) == null
954                                || pm.getReceiverInfo(aa.info.getComponent(), 0, userHandle)
955                                    == null) {
956                            removed = true;
957                            policy.mAdminList.remove(i);
958                            policy.mAdminMap.remove(aa.info.getComponent());
959                        }
960                    }
961                } catch (RemoteException re) {
962                    // Shouldn't happen
963                }
964            }
965            if (removed) {
966                validatePasswordOwnerLocked(policy);
967                syncDeviceCapabilitiesLocked(policy);
968                saveSettingsLocked(policy.mUserHandle);
969            }
970
971            if (policy.mDelegatedCertInstallerPackage != null &&
972                    (packageName == null
973                    || packageName.equals(policy.mDelegatedCertInstallerPackage))) {
974                try {
975                    // Check if delegated cert installer package is removed.
976                    if (pm.getPackageInfo(
977                            policy.mDelegatedCertInstallerPackage, 0, userHandle) == null) {
978                        policy.mDelegatedCertInstallerPackage = null;
979                        saveSettingsLocked(policy.mUserHandle);
980                    }
981                } catch (RemoteException e) {
982                    // Shouldn't happen
983                }
984            }
985        }
986    }
987
988    /**
989     * Instantiates the service.
990     */
991    public DevicePolicyManagerService(Context context) {
992        mContext = context;
993        mUserManager = UserManager.get(mContext);
994        mHasFeature = context.getPackageManager().hasSystemFeature(
995                PackageManager.FEATURE_DEVICE_ADMIN);
996        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
997        mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
998        mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPM");
999        mLocalService = new LocalService();
1000        if (!mHasFeature) {
1001            // Skip the rest of the initialization
1002            return;
1003        }
1004        IntentFilter filter = new IntentFilter();
1005        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1006        filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1007        filter.addAction(Intent.ACTION_USER_REMOVED);
1008        filter.addAction(Intent.ACTION_USER_STARTED);
1009        filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1010        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1011        context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1012        filter = new IntentFilter();
1013        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1014        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1015        filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1016        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1017        filter.addDataScheme("package");
1018        context.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1019
1020        LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1021    }
1022
1023    /**
1024     * Creates and loads the policy data from xml.
1025     * @param userHandle the user for whom to load the policy data
1026     * @return
1027     */
1028    DevicePolicyData getUserData(int userHandle) {
1029        synchronized (this) {
1030            DevicePolicyData policy = mUserData.get(userHandle);
1031            if (policy == null) {
1032                policy = new DevicePolicyData(userHandle);
1033                mUserData.append(userHandle, policy);
1034                loadSettingsLocked(policy, userHandle);
1035            }
1036            return policy;
1037        }
1038    }
1039
1040    /**
1041     * Creates and loads the policy data from xml for data that is shared between
1042     * various profiles of a user. In contrast to {@link #getUserData(int)}
1043     * it allows access to data of users other than the calling user.
1044     *
1045     * This function should only be used for shared data, e.g. everything regarding
1046     * passwords and should be removed once multiple screen locks are present.
1047     * @param userHandle the user for whom to load the policy data
1048     * @return
1049     */
1050    DevicePolicyData getUserDataUnchecked(int userHandle) {
1051        long ident = Binder.clearCallingIdentity();
1052        try {
1053            return getUserData(userHandle);
1054        } finally {
1055            Binder.restoreCallingIdentity(ident);
1056        }
1057    }
1058
1059    void removeUserData(int userHandle) {
1060        synchronized (this) {
1061            if (userHandle == UserHandle.USER_OWNER) {
1062                Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1063                return;
1064            }
1065            if (mDeviceOwner != null) {
1066                mDeviceOwner.removeProfileOwner(userHandle);
1067                mDeviceOwner.writeOwnerFile();
1068            }
1069
1070            DevicePolicyData policy = mUserData.get(userHandle);
1071            if (policy != null) {
1072                mUserData.remove(userHandle);
1073            }
1074            File policyFile = new File(Environment.getUserSystemDirectory(userHandle),
1075                    DEVICE_POLICIES_XML);
1076            policyFile.delete();
1077            Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1078        }
1079        updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1080    }
1081
1082    void loadDeviceOwner() {
1083        synchronized (this) {
1084            mDeviceOwner = DeviceOwner.load();
1085        }
1086    }
1087
1088    /**
1089     * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1090     * reminders.  Clears alarm if no expirations are configured.
1091     */
1092    protected void setExpirationAlarmCheckLocked(Context context, DevicePolicyData policy) {
1093        final long expiration = getPasswordExpirationLocked(null, policy.mUserHandle);
1094        final long now = System.currentTimeMillis();
1095        final long timeToExpire = expiration - now;
1096        final long alarmTime;
1097        if (expiration == 0) {
1098            // No expirations are currently configured:  Cancel alarm.
1099            alarmTime = 0;
1100        } else if (timeToExpire <= 0) {
1101            // The password has already expired:  Repeat every 24 hours.
1102            alarmTime = now + MS_PER_DAY;
1103        } else {
1104            // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
1105            // the expiration time.
1106            long alarmInterval = timeToExpire % MS_PER_DAY;
1107            if (alarmInterval == 0) {
1108                alarmInterval = MS_PER_DAY;
1109            }
1110            alarmTime = now + alarmInterval;
1111        }
1112
1113        long token = Binder.clearCallingIdentity();
1114        try {
1115            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1116            PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1117                    new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1118                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1119                    new UserHandle(policy.mUserHandle));
1120            am.cancel(pi);
1121            if (alarmTime != 0) {
1122                am.set(AlarmManager.RTC, alarmTime, pi);
1123            }
1124        } finally {
1125            Binder.restoreCallingIdentity(token);
1126        }
1127    }
1128
1129    private IWindowManager getWindowManager() {
1130        if (mIWindowManager == null) {
1131            IBinder b = ServiceManager.getService(Context.WINDOW_SERVICE);
1132            mIWindowManager = IWindowManager.Stub.asInterface(b);
1133        }
1134        return mIWindowManager;
1135    }
1136
1137    private NotificationManager getNotificationManager() {
1138        if (mNotificationManager == null) {
1139            mNotificationManager =
1140                    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
1141        }
1142        return mNotificationManager;
1143    }
1144
1145    ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1146        ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1147        if (admin != null
1148                && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1149                && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1150            return admin;
1151        }
1152        return null;
1153    }
1154
1155    ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1156            throws SecurityException {
1157        final int callingUid = Binder.getCallingUid();
1158
1159        ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1160        if (result != null) {
1161            return result;
1162        }
1163
1164        if (who != null) {
1165            final int userId = UserHandle.getUserId(callingUid);
1166            final DevicePolicyData policy = getUserData(userId);
1167            ActiveAdmin admin = policy.mAdminMap.get(who);
1168            if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1169                throw new SecurityException("Admin " + admin.info.getComponent()
1170                         + " does not own the device");
1171            }
1172            if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1173                throw new SecurityException("Admin " + admin.info.getComponent()
1174                        + " does not own the profile");
1175            }
1176            throw new SecurityException("Admin " + admin.info.getComponent()
1177                    + " did not specify uses-policy for: "
1178                    + admin.info.getTagForPolicy(reqPolicy));
1179        } else {
1180            throw new SecurityException("No active admin owned by uid "
1181                    + Binder.getCallingUid() + " for policy #" + reqPolicy);
1182        }
1183    }
1184
1185    private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
1186            int uid) {
1187        // Try to find an admin which can use reqPolicy
1188        final int userId = UserHandle.getUserId(uid);
1189        final DevicePolicyData policy = getUserData(userId);
1190        if (who != null) {
1191            ActiveAdmin admin = policy.mAdminMap.get(who);
1192            if (admin == null) {
1193                throw new SecurityException("No active admin " + who);
1194            }
1195            if (admin.getUid() != uid) {
1196                throw new SecurityException("Admin " + who + " is not owned by uid "
1197                        + Binder.getCallingUid());
1198            }
1199            if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
1200                return admin;
1201            }
1202        } else {
1203            for (ActiveAdmin admin : policy.mAdminList) {
1204                if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
1205                        userId)) {
1206                    return admin;
1207                }
1208            }
1209        }
1210
1211        return null;
1212    }
1213
1214    private boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
1215            int userId) {
1216        boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
1217        boolean ownsProfile = (getProfileOwner(userId) != null
1218                && getProfileOwner(userId).getPackageName()
1219                    .equals(admin.info.getPackageName()));
1220        boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
1221                && !hasUserSetupCompleted(userId);
1222
1223        if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1224            if (ownsDevice || (userId == UserHandle.USER_OWNER && ownsInitialization)) {
1225                return true;
1226            }
1227        } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1228            if (ownsDevice || ownsProfile || ownsInitialization) {
1229                return true;
1230            }
1231        } else {
1232            if (admin.info.usesPolicy(reqPolicy)) {
1233                return true;
1234            }
1235        }
1236        return false;
1237    }
1238
1239    void sendAdminCommandLocked(ActiveAdmin admin, String action) {
1240        sendAdminCommandLocked(admin, action, null);
1241    }
1242
1243    void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
1244        sendAdminCommandLocked(admin, action, null, result);
1245    }
1246
1247    /**
1248     * Send an update to one specific admin, get notified when that admin returns a result.
1249     */
1250    void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
1251            BroadcastReceiver result) {
1252        Intent intent = new Intent(action);
1253        intent.setComponent(admin.info.getComponent());
1254        if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
1255            intent.putExtra("expiration", admin.passwordExpirationDate);
1256        }
1257        if (adminExtras != null) {
1258            intent.putExtras(adminExtras);
1259        }
1260        if (result != null) {
1261            mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
1262                    null, result, mHandler, Activity.RESULT_OK, null, null);
1263        } else {
1264            mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
1265        }
1266    }
1267
1268    /**
1269     * Send an update to all admins of a user that enforce a specified policy.
1270     */
1271    void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
1272        final DevicePolicyData policy = getUserData(userHandle);
1273        final int count = policy.mAdminList.size();
1274        if (count > 0) {
1275            for (int i = 0; i < count; i++) {
1276                final ActiveAdmin admin = policy.mAdminList.get(i);
1277                if (admin.info.usesPolicy(reqPolicy)) {
1278                    sendAdminCommandLocked(admin, action);
1279                }
1280            }
1281        }
1282    }
1283
1284    /**
1285     * Send an update intent to all admins of a user and its profiles. Only send to admins that
1286     * enforce a specified policy.
1287     */
1288    private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
1289            int userHandle) {
1290        List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1291        for (UserInfo ui : profiles) {
1292            int id = ui.id;
1293            sendAdminCommandLocked(action, reqPolicy, id);
1294        }
1295    }
1296
1297    void removeActiveAdminLocked(final ComponentName adminReceiver, int userHandle) {
1298        final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1299        if (admin != null) {
1300            synchronized (this) {
1301                getUserData(userHandle).mRemovingAdmins.add(adminReceiver);
1302            }
1303            sendAdminCommandLocked(admin,
1304                    DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
1305                    new BroadcastReceiver() {
1306                        @Override
1307                        public void onReceive(Context context, Intent intent) {
1308                            synchronized (DevicePolicyManagerService.this) {
1309                                int userHandle = admin.getUserHandle().getIdentifier();
1310                                DevicePolicyData policy = getUserData(userHandle);
1311                                boolean doProxyCleanup = admin.info.usesPolicy(
1312                                        DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
1313                                policy.mAdminList.remove(admin);
1314                                policy.mAdminMap.remove(adminReceiver);
1315                                validatePasswordOwnerLocked(policy);
1316                                syncDeviceCapabilitiesLocked(policy);
1317                                if (doProxyCleanup) {
1318                                    resetGlobalProxyLocked(getUserData(userHandle));
1319                                }
1320                                saveSettingsLocked(userHandle);
1321                                updateMaximumTimeToLockLocked(policy);
1322                                policy.mRemovingAdmins.remove(adminReceiver);
1323                            }
1324                        }
1325                    });
1326        }
1327    }
1328
1329    public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle) {
1330        if (!mHasFeature) {
1331            return null;
1332        }
1333        enforceCrossUserPermission(userHandle);
1334        Intent resolveIntent = new Intent();
1335        resolveIntent.setComponent(adminName);
1336        List<ResolveInfo> infos = mContext.getPackageManager().queryBroadcastReceivers(
1337                resolveIntent,
1338                PackageManager.GET_META_DATA | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
1339                userHandle);
1340        if (infos == null || infos.size() <= 0) {
1341            throw new IllegalArgumentException("Unknown admin: " + adminName);
1342        }
1343
1344        try {
1345            return new DeviceAdminInfo(mContext, infos.get(0));
1346        } catch (XmlPullParserException e) {
1347            Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1348                    e);
1349            return null;
1350        } catch (IOException e) {
1351            Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
1352                    e);
1353            return null;
1354        }
1355    }
1356
1357    private static JournaledFile makeJournaledFile(int userHandle) {
1358        final String base = userHandle == 0
1359                ? "/data/system/" + DEVICE_POLICIES_XML
1360                : new File(Environment.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML)
1361                        .getAbsolutePath();
1362        return new JournaledFile(new File(base), new File(base + ".tmp"));
1363    }
1364
1365    private void saveSettingsLocked(int userHandle) {
1366        DevicePolicyData policy = getUserData(userHandle);
1367        JournaledFile journal = makeJournaledFile(userHandle);
1368        FileOutputStream stream = null;
1369        try {
1370            stream = new FileOutputStream(journal.chooseForWrite(), false);
1371            XmlSerializer out = new FastXmlSerializer();
1372            out.setOutput(stream, "utf-8");
1373            out.startDocument(null, true);
1374
1375            out.startTag(null, "policies");
1376            if (policy.mRestrictionsProvider != null) {
1377                out.attribute(null, ATTR_PERMISSION_PROVIDER,
1378                        policy.mRestrictionsProvider.flattenToString());
1379            }
1380            if (policy.mUserSetupComplete) {
1381                out.attribute(null, ATTR_SETUP_COMPLETE,
1382                        Boolean.toString(true));
1383            }
1384            if (policy.mDelegatedCertInstallerPackage != null) {
1385                out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
1386                        policy.mDelegatedCertInstallerPackage);
1387            }
1388
1389
1390            final int N = policy.mAdminList.size();
1391            for (int i=0; i<N; i++) {
1392                ActiveAdmin ap = policy.mAdminList.get(i);
1393                if (ap != null) {
1394                    out.startTag(null, "admin");
1395                    out.attribute(null, "name", ap.info.getComponent().flattenToString());
1396                    ap.writeToXml(out);
1397                    out.endTag(null, "admin");
1398                }
1399            }
1400
1401            if (policy.mPasswordOwner >= 0) {
1402                out.startTag(null, "password-owner");
1403                out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
1404                out.endTag(null, "password-owner");
1405            }
1406
1407            if (policy.mFailedPasswordAttempts != 0) {
1408                out.startTag(null, "failed-password-attempts");
1409                out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
1410                out.endTag(null, "failed-password-attempts");
1411            }
1412
1413            if (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
1414                    || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
1415                    || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
1416                    || policy.mActivePasswordSymbols != 0 || policy.mActivePasswordNonLetter != 0) {
1417                out.startTag(null, "active-password");
1418                out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
1419                out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
1420                out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
1421                out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
1422                out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
1423                out.attribute(null, "numeric", Integer
1424                        .toString(policy.mActivePasswordNumeric));
1425                out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
1426                out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
1427                out.endTag(null, "active-password");
1428            }
1429
1430            for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
1431                String component = policy.mLockTaskPackages.get(i);
1432                out.startTag(null, LOCK_TASK_COMPONENTS_XML);
1433                out.attribute(null, "name", component);
1434                out.endTag(null, LOCK_TASK_COMPONENTS_XML);
1435            }
1436
1437            out.endTag(null, "policies");
1438
1439            out.endDocument();
1440            stream.flush();
1441            FileUtils.sync(stream);
1442            stream.close();
1443            journal.commit();
1444            sendChangedNotification(userHandle);
1445        } catch (IOException e) {
1446            try {
1447                if (stream != null) {
1448                    stream.close();
1449                }
1450            } catch (IOException ex) {
1451                // Ignore
1452            }
1453            journal.rollback();
1454        }
1455    }
1456
1457    private void sendChangedNotification(int userHandle) {
1458        Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
1459        intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1460        long ident = Binder.clearCallingIdentity();
1461        try {
1462            mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
1463        } finally {
1464            Binder.restoreCallingIdentity(ident);
1465        }
1466    }
1467
1468    private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
1469        JournaledFile journal = makeJournaledFile(userHandle);
1470        FileInputStream stream = null;
1471        File file = journal.chooseForRead();
1472        try {
1473            stream = new FileInputStream(file);
1474            XmlPullParser parser = Xml.newPullParser();
1475            parser.setInput(stream, null);
1476
1477            int type;
1478            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1479                    && type != XmlPullParser.START_TAG) {
1480            }
1481            String tag = parser.getName();
1482            if (!"policies".equals(tag)) {
1483                throw new XmlPullParserException(
1484                        "Settings do not start with policies tag: found " + tag);
1485            }
1486
1487            // Extract the permission provider component name if available
1488            String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
1489            if (permissionProvider != null) {
1490                policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
1491            }
1492            String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
1493            if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
1494                policy.mUserSetupComplete = true;
1495            }
1496            policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
1497                    ATTR_DELEGATED_CERT_INSTALLER);
1498
1499            type = parser.next();
1500            int outerDepth = parser.getDepth();
1501            policy.mLockTaskPackages.clear();
1502            policy.mAdminList.clear();
1503            policy.mAdminMap.clear();
1504            while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1505                   && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1506                if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1507                    continue;
1508                }
1509                tag = parser.getName();
1510                if ("admin".equals(tag)) {
1511                    String name = parser.getAttributeValue(null, "name");
1512                    try {
1513                        DeviceAdminInfo dai = findAdmin(
1514                                ComponentName.unflattenFromString(name), userHandle);
1515                        if (DBG && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
1516                                != userHandle)) {
1517                            Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
1518                                    + dai.getActivityInfo().applicationInfo.uid + " for user "
1519                                    + userHandle);
1520                        }
1521                        if (dai != null) {
1522                            ActiveAdmin ap = new ActiveAdmin(dai);
1523                            ap.readFromXml(parser);
1524                            policy.mAdminMap.put(ap.info.getComponent(), ap);
1525                        }
1526                    } catch (RuntimeException e) {
1527                        Slog.w(LOG_TAG, "Failed loading admin " + name, e);
1528                    }
1529                } else if ("failed-password-attempts".equals(tag)) {
1530                    policy.mFailedPasswordAttempts = Integer.parseInt(
1531                            parser.getAttributeValue(null, "value"));
1532                    XmlUtils.skipCurrentTag(parser);
1533                } else if ("password-owner".equals(tag)) {
1534                    policy.mPasswordOwner = Integer.parseInt(
1535                            parser.getAttributeValue(null, "value"));
1536                    XmlUtils.skipCurrentTag(parser);
1537                } else if ("active-password".equals(tag)) {
1538                    policy.mActivePasswordQuality = Integer.parseInt(
1539                            parser.getAttributeValue(null, "quality"));
1540                    policy.mActivePasswordLength = Integer.parseInt(
1541                            parser.getAttributeValue(null, "length"));
1542                    policy.mActivePasswordUpperCase = Integer.parseInt(
1543                            parser.getAttributeValue(null, "uppercase"));
1544                    policy.mActivePasswordLowerCase = Integer.parseInt(
1545                            parser.getAttributeValue(null, "lowercase"));
1546                    policy.mActivePasswordLetters = Integer.parseInt(
1547                            parser.getAttributeValue(null, "letters"));
1548                    policy.mActivePasswordNumeric = Integer.parseInt(
1549                            parser.getAttributeValue(null, "numeric"));
1550                    policy.mActivePasswordSymbols = Integer.parseInt(
1551                            parser.getAttributeValue(null, "symbols"));
1552                    policy.mActivePasswordNonLetter = Integer.parseInt(
1553                            parser.getAttributeValue(null, "nonletter"));
1554                    XmlUtils.skipCurrentTag(parser);
1555                } else if (LOCK_TASK_COMPONENTS_XML.equals(tag)) {
1556                    policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
1557                    XmlUtils.skipCurrentTag(parser);
1558                } else {
1559                    Slog.w(LOG_TAG, "Unknown tag: " + tag);
1560                    XmlUtils.skipCurrentTag(parser);
1561                }
1562            }
1563        } catch (NullPointerException e) {
1564            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1565        } catch (NumberFormatException e) {
1566            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1567        } catch (XmlPullParserException e) {
1568            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1569        } catch (FileNotFoundException e) {
1570            // Don't be noisy, this is normal if we haven't defined any policies.
1571        } catch (IOException e) {
1572            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1573        } catch (IndexOutOfBoundsException e) {
1574            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1575        }
1576        try {
1577            if (stream != null) {
1578                stream.close();
1579            }
1580        } catch (IOException e) {
1581            // Ignore
1582        }
1583
1584        // Generate a list of admins from the admin map
1585        policy.mAdminList.addAll(policy.mAdminMap.values());
1586
1587        // Validate that what we stored for the password quality matches
1588        // sufficiently what is currently set.  Note that this is only
1589        // a sanity check in case the two get out of sync; this should
1590        // never normally happen.
1591        LockPatternUtils utils = new LockPatternUtils(mContext);
1592        if (utils.getActivePasswordQuality(userHandle) < policy.mActivePasswordQuality) {
1593            Slog.w(LOG_TAG, "Active password quality 0x"
1594                    + Integer.toHexString(policy.mActivePasswordQuality)
1595                    + " does not match actual quality 0x"
1596                    + Integer.toHexString(utils.getActivePasswordQuality(userHandle)));
1597            policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1598            policy.mActivePasswordLength = 0;
1599            policy.mActivePasswordUpperCase = 0;
1600            policy.mActivePasswordLowerCase = 0;
1601            policy.mActivePasswordLetters = 0;
1602            policy.mActivePasswordNumeric = 0;
1603            policy.mActivePasswordSymbols = 0;
1604            policy.mActivePasswordNonLetter = 0;
1605        }
1606
1607        validatePasswordOwnerLocked(policy);
1608        syncDeviceCapabilitiesLocked(policy);
1609        updateMaximumTimeToLockLocked(policy);
1610        updateLockTaskPackagesLocked(policy, userHandle);
1611    }
1612
1613    private void updateLockTaskPackagesLocked(DevicePolicyData policy, int userId) {
1614        IActivityManager am = ActivityManagerNative.getDefault();
1615        try {
1616            am.updateLockTaskPackages(userId, policy.mLockTaskPackages.toArray(new String[0]));
1617        } catch (RemoteException e) {
1618            // Not gonna happen.
1619        }
1620    }
1621
1622    static void validateQualityConstant(int quality) {
1623        switch (quality) {
1624            case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1625            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1626            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1627            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1628            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1629            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1630            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1631            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1632                return;
1633        }
1634        throw new IllegalArgumentException("Invalid quality constant: 0x"
1635                + Integer.toHexString(quality));
1636    }
1637
1638    void validatePasswordOwnerLocked(DevicePolicyData policy) {
1639        if (policy.mPasswordOwner >= 0) {
1640            boolean haveOwner = false;
1641            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1642                if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1643                    haveOwner = true;
1644                    break;
1645                }
1646            }
1647            if (!haveOwner) {
1648                Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1649                        + " no longer active; disabling");
1650                policy.mPasswordOwner = -1;
1651            }
1652        }
1653    }
1654
1655    /**
1656     * Pushes down policy information to the system for any policies related to general device
1657     * capabilities that need to be enforced by lower level services (e.g. Camera services).
1658     */
1659    void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1660        // Ensure the status of the camera is synced down to the system. Interested native services
1661        // should monitor this value and act accordingly.
1662        String cameraPropertyForUser = SYSTEM_PROP_DISABLE_CAMERA_PREFIX + policy.mUserHandle;
1663        boolean systemState = SystemProperties.getBoolean(cameraPropertyForUser, false);
1664        boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1665        if (cameraDisabled != systemState) {
1666            long token = Binder.clearCallingIdentity();
1667            try {
1668                String value = cameraDisabled ? "1" : "0";
1669                if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1670                        + cameraPropertyForUser + "] = " + value);
1671                SystemProperties.set(cameraPropertyForUser, value);
1672            } finally {
1673                Binder.restoreCallingIdentity(token);
1674            }
1675        }
1676    }
1677
1678    public void systemReady() {
1679        if (!mHasFeature) {
1680            return;
1681        }
1682        getUserData(UserHandle.USER_OWNER);
1683        loadDeviceOwner();
1684        cleanUpOldUsers();
1685        // Register an observer for watching for user setup complete.
1686        new SetupContentObserver(mHandler).register(mContext.getContentResolver());
1687        // Initialize the user setup state, to handle the upgrade case.
1688        updateUserSetupComplete();
1689
1690        // Update the screen capture disabled cache in the window manager
1691        List<UserInfo> users = mUserManager.getUsers(true);
1692        final int N = users.size();
1693        for (int i = 0; i < N; i++) {
1694            int userHandle = users.get(i).id;
1695            updateScreenCaptureDisabledInWindowManager(userHandle,
1696                    getScreenCaptureDisabled(null, userHandle));
1697        }
1698
1699    }
1700
1701    private void cleanUpOldUsers() {
1702        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1703        // before reboot
1704        Set<Integer> usersWithProfileOwners;
1705        Set<Integer> usersWithData;
1706        synchronized(this) {
1707            usersWithProfileOwners = mDeviceOwner != null
1708                    ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1709            usersWithData = new HashSet<Integer>();
1710            for (int i = 0; i < mUserData.size(); i++) {
1711                usersWithData.add(mUserData.keyAt(i));
1712            }
1713        }
1714        List<UserInfo> allUsers = mUserManager.getUsers();
1715
1716        Set<Integer> deletedUsers = new HashSet<Integer>();
1717        deletedUsers.addAll(usersWithProfileOwners);
1718        deletedUsers.addAll(usersWithData);
1719        for (UserInfo userInfo : allUsers) {
1720            deletedUsers.remove(userInfo.id);
1721        }
1722        for (Integer userId : deletedUsers) {
1723            removeUserData(userId);
1724        }
1725    }
1726
1727    private void handlePasswordExpirationNotification(int userHandle) {
1728        synchronized (this) {
1729            final long now = System.currentTimeMillis();
1730
1731            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1732            for (UserInfo ui : profiles) {
1733                int profileUserHandle = ui.id;
1734                final DevicePolicyData policy = getUserData(profileUserHandle);
1735                final int count = policy.mAdminList.size();
1736                if (count > 0) {
1737                    for (int i = 0; i < count; i++) {
1738                        final ActiveAdmin admin = policy.mAdminList.get(i);
1739                        if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1740                                && admin.passwordExpirationTimeout > 0L
1741                                && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1742                                && admin.passwordExpirationDate > 0L) {
1743                            sendAdminCommandLocked(admin,
1744                                    DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1745                        }
1746                    }
1747                }
1748            }
1749            setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1750        }
1751    }
1752
1753    private class MonitoringCertNotificationTask extends AsyncTask<Intent, Void, Void> {
1754        @Override
1755        protected Void doInBackground(Intent... params) {
1756            int userHandle = params[0].getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
1757
1758            if (userHandle == UserHandle.USER_ALL) {
1759                for (UserInfo userInfo : mUserManager.getUsers()) {
1760                    manageNotification(userInfo.getUserHandle());
1761                }
1762            } else {
1763                manageNotification(new UserHandle(userHandle));
1764            }
1765            return null;
1766        }
1767
1768        private void manageNotification(UserHandle userHandle) {
1769            if (!mUserManager.isUserRunning(userHandle)) {
1770                return;
1771            }
1772
1773            // Call out to KeyChain to check for user-added CAs
1774            boolean hasCert = false;
1775            try {
1776                KeyChainConnection kcs = KeyChain.bindAsUser(mContext, userHandle);
1777                try {
1778                    if (!kcs.getService().getUserCaAliases().getList().isEmpty()) {
1779                        hasCert = true;
1780                    }
1781                } catch (RemoteException e) {
1782                    Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1783                } finally {
1784                    kcs.close();
1785                }
1786            } catch (InterruptedException e) {
1787                Thread.currentThread().interrupt();
1788            } catch (RuntimeException e) {
1789                Log.e(LOG_TAG, "Could not connect to KeyChain service", e);
1790            }
1791            if (!hasCert) {
1792                getNotificationManager().cancelAsUser(
1793                        null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
1794                return;
1795            }
1796
1797            // Build and show a warning notification
1798            int smallIconId;
1799            String contentText;
1800            final String ownerName = getDeviceOwnerName();
1801            if (isManagedProfile(userHandle.getIdentifier())) {
1802                contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_administrator);
1803                smallIconId = R.drawable.stat_sys_certificate_info;
1804            } else if (ownerName != null) {
1805                contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, ownerName);
1806                smallIconId = R.drawable.stat_sys_certificate_info;
1807            } else {
1808                contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1809                smallIconId = android.R.drawable.stat_sys_warning;
1810            }
1811
1812            Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1813            dialogIntent.setFlags(
1814                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1815            dialogIntent.setPackage("com.android.settings");
1816            PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
1817                    dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, userHandle);
1818
1819            final Context userContext;
1820            try {
1821                userContext = mContext.createPackageContextAsUser("android", 0, userHandle);
1822            } catch (PackageManager.NameNotFoundException e) {
1823                Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
1824                return;
1825            }
1826            final Notification noti = new Notification.Builder(userContext)
1827                .setSmallIcon(smallIconId)
1828                .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1829                .setContentText(contentText)
1830                .setContentIntent(notifyIntent)
1831                .setPriority(Notification.PRIORITY_HIGH)
1832                .setShowWhen(false)
1833                .setColor(mContext.getColor(
1834                        com.android.internal.R.color.system_notification_accent_color))
1835                .build();
1836
1837            getNotificationManager().notifyAsUser(
1838                    null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
1839        }
1840    }
1841
1842    /**
1843     * @param adminReceiver The admin to add
1844     * @param refreshing true = update an active admin, no error
1845     */
1846    public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1847        if (!mHasFeature) {
1848            return;
1849        }
1850        setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1851    }
1852
1853    private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1854            Bundle onEnableData) {
1855        mContext.enforceCallingOrSelfPermission(
1856                android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1857        enforceCrossUserPermission(userHandle);
1858
1859        DevicePolicyData policy = getUserData(userHandle);
1860        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1861        if (info == null) {
1862            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1863        }
1864        synchronized (this) {
1865            long ident = Binder.clearCallingIdentity();
1866            try {
1867                if (!refreshing
1868                        && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1869                    throw new IllegalArgumentException("Admin is already added");
1870                }
1871                ActiveAdmin newAdmin = new ActiveAdmin(info);
1872                policy.mAdminMap.put(adminReceiver, newAdmin);
1873                int replaceIndex = -1;
1874                final int N = policy.mAdminList.size();
1875                for (int i=0; i < N; i++) {
1876                    ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1877                    if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1878                        replaceIndex = i;
1879                        break;
1880                    }
1881                }
1882                if (replaceIndex == -1) {
1883                    policy.mAdminList.add(newAdmin);
1884                    enableIfNecessary(info.getPackageName(), userHandle);
1885                } else {
1886                    policy.mAdminList.set(replaceIndex, newAdmin);
1887                }
1888                saveSettingsLocked(userHandle);
1889                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1890                        onEnableData, null);
1891            } finally {
1892                Binder.restoreCallingIdentity(ident);
1893            }
1894        }
1895    }
1896
1897    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
1898        if (!mHasFeature) {
1899            return false;
1900        }
1901        enforceCrossUserPermission(userHandle);
1902        synchronized (this) {
1903            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
1904        }
1905    }
1906
1907    @Override
1908    public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
1909        if (!mHasFeature) {
1910            return false;
1911        }
1912        enforceCrossUserPermission(userHandle);
1913        synchronized (this) {
1914            DevicePolicyData policyData = getUserData(userHandle);
1915            return policyData.mRemovingAdmins.contains(adminReceiver);
1916        }
1917    }
1918
1919    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
1920        if (!mHasFeature) {
1921            return false;
1922        }
1923        enforceCrossUserPermission(userHandle);
1924        synchronized (this) {
1925            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1926            if (administrator == null) {
1927                throw new SecurityException("No active admin " + adminReceiver);
1928            }
1929            return administrator.info.usesPolicy(policyId);
1930        }
1931    }
1932
1933    @SuppressWarnings("unchecked")
1934    public List<ComponentName> getActiveAdmins(int userHandle) {
1935        if (!mHasFeature) {
1936            return Collections.EMPTY_LIST;
1937        }
1938
1939        enforceCrossUserPermission(userHandle);
1940        synchronized (this) {
1941            DevicePolicyData policy = getUserData(userHandle);
1942            final int N = policy.mAdminList.size();
1943            if (N <= 0) {
1944                return null;
1945            }
1946            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
1947            for (int i=0; i<N; i++) {
1948                res.add(policy.mAdminList.get(i).info.getComponent());
1949            }
1950            return res;
1951        }
1952    }
1953
1954    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
1955        if (!mHasFeature) {
1956            return false;
1957        }
1958        enforceCrossUserPermission(userHandle);
1959        synchronized (this) {
1960            DevicePolicyData policy = getUserData(userHandle);
1961            final int N = policy.mAdminList.size();
1962            for (int i=0; i<N; i++) {
1963                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
1964                    return true;
1965                }
1966            }
1967            return false;
1968        }
1969    }
1970
1971    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
1972        if (!mHasFeature) {
1973            return;
1974        }
1975        enforceCrossUserPermission(userHandle);
1976        synchronized (this) {
1977            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1978            if (admin == null) {
1979                return;
1980            }
1981            if (admin.getUid() != Binder.getCallingUid()) {
1982                // Active device owners must remain active admins.
1983                if (isDeviceOwner(adminReceiver.getPackageName())) {
1984                    return;
1985                }
1986                mContext.enforceCallingOrSelfPermission(
1987                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1988            }
1989            long ident = Binder.clearCallingIdentity();
1990            try {
1991                removeActiveAdminLocked(adminReceiver, userHandle);
1992            } finally {
1993                Binder.restoreCallingIdentity(ident);
1994            }
1995        }
1996    }
1997
1998    public void setPasswordQuality(ComponentName who, int quality) {
1999        if (!mHasFeature) {
2000            return;
2001        }
2002        Preconditions.checkNotNull(who, "ComponentName is null");
2003        final int userHandle = UserHandle.getCallingUserId();
2004        validateQualityConstant(quality);
2005
2006        synchronized (this) {
2007            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2008                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2009            if (ap.passwordQuality != quality) {
2010                ap.passwordQuality = quality;
2011                saveSettingsLocked(userHandle);
2012            }
2013        }
2014    }
2015
2016    public int getPasswordQuality(ComponentName who, int userHandle) {
2017        if (!mHasFeature) {
2018            return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2019        }
2020        enforceCrossUserPermission(userHandle);
2021        synchronized (this) {
2022            int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
2023
2024            if (who != null) {
2025                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2026                return admin != null ? admin.passwordQuality : mode;
2027            }
2028
2029            // Return strictest policy for this user and profiles that are visible from this user.
2030            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2031            for (UserInfo userInfo : profiles) {
2032                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2033                final int N = policy.mAdminList.size();
2034                for (int i=0; i<N; i++) {
2035                    ActiveAdmin admin = policy.mAdminList.get(i);
2036                    if (mode < admin.passwordQuality) {
2037                        mode = admin.passwordQuality;
2038                    }
2039                }
2040            }
2041            return mode;
2042        }
2043    }
2044
2045    public void setPasswordMinimumLength(ComponentName who, int length) {
2046        if (!mHasFeature) {
2047            return;
2048        }
2049        Preconditions.checkNotNull(who, "ComponentName is null");
2050        final int userHandle = UserHandle.getCallingUserId();
2051        synchronized (this) {
2052            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2053                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2054            if (ap.minimumPasswordLength != length) {
2055                ap.minimumPasswordLength = length;
2056                saveSettingsLocked(userHandle);
2057            }
2058        }
2059    }
2060
2061    public int getPasswordMinimumLength(ComponentName who, int userHandle) {
2062        if (!mHasFeature) {
2063            return 0;
2064        }
2065        enforceCrossUserPermission(userHandle);
2066        synchronized (this) {
2067            int length = 0;
2068
2069            if (who != null) {
2070                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2071                return admin != null ? admin.minimumPasswordLength : length;
2072            }
2073
2074            // Return strictest policy for this user and profiles that are visible from this user.
2075            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2076            for (UserInfo userInfo : profiles) {
2077                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2078                final int N = policy.mAdminList.size();
2079                for (int i=0; i<N; i++) {
2080                    ActiveAdmin admin = policy.mAdminList.get(i);
2081                    if (length < admin.minimumPasswordLength) {
2082                        length = admin.minimumPasswordLength;
2083                    }
2084                }
2085            }
2086            return length;
2087        }
2088    }
2089
2090    public void setPasswordHistoryLength(ComponentName who, int length) {
2091        if (!mHasFeature) {
2092            return;
2093        }
2094        Preconditions.checkNotNull(who, "ComponentName is null");
2095        final int userHandle = UserHandle.getCallingUserId();
2096        synchronized (this) {
2097            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2098                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2099            if (ap.passwordHistoryLength != length) {
2100                ap.passwordHistoryLength = length;
2101                saveSettingsLocked(userHandle);
2102            }
2103        }
2104    }
2105
2106    public int getPasswordHistoryLength(ComponentName who, int userHandle) {
2107        if (!mHasFeature) {
2108            return 0;
2109        }
2110        enforceCrossUserPermission(userHandle);
2111        synchronized (this) {
2112            int length = 0;
2113
2114            if (who != null) {
2115                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2116                return admin != null ? admin.passwordHistoryLength : length;
2117            }
2118
2119            // Return strictest policy for this user and profiles that are visible from this user.
2120            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2121            for (UserInfo userInfo : profiles) {
2122                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2123                final int N = policy.mAdminList.size();
2124                for (int i = 0; i < N; i++) {
2125                    ActiveAdmin admin = policy.mAdminList.get(i);
2126                    if (length < admin.passwordHistoryLength) {
2127                        length = admin.passwordHistoryLength;
2128                    }
2129                }
2130            }
2131            return length;
2132        }
2133    }
2134
2135    public void setPasswordExpirationTimeout(ComponentName who, long timeout) {
2136        if (!mHasFeature) {
2137            return;
2138        }
2139        Preconditions.checkNotNull(who, "ComponentName is null");
2140        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
2141        final int userHandle = UserHandle.getCallingUserId();
2142        synchronized (this) {
2143            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2144                    DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
2145            // Calling this API automatically bumps the expiration date
2146            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2147            ap.passwordExpirationDate = expiration;
2148            ap.passwordExpirationTimeout = timeout;
2149            if (timeout > 0L) {
2150                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
2151                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
2152                        .format(new Date(expiration)));
2153            }
2154            saveSettingsLocked(userHandle);
2155            // in case this is the first one
2156            setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
2157        }
2158    }
2159
2160    /**
2161     * Return a single admin's expiration cycle time, or the min of all cycle times.
2162     * Returns 0 if not configured.
2163     */
2164    public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
2165        if (!mHasFeature) {
2166            return 0L;
2167        }
2168        enforceCrossUserPermission(userHandle);
2169        synchronized (this) {
2170            long timeout = 0L;
2171
2172            if (who != null) {
2173                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2174                return admin != null ? admin.passwordExpirationTimeout : timeout;
2175            }
2176
2177            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2178            for (UserInfo userInfo : profiles) {
2179                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2180                final int N = policy.mAdminList.size();
2181                for (int i = 0; i < N; i++) {
2182                    ActiveAdmin admin = policy.mAdminList.get(i);
2183                    if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
2184                            && timeout > admin.passwordExpirationTimeout)) {
2185                        timeout = admin.passwordExpirationTimeout;
2186                    }
2187                }
2188            }
2189            return timeout;
2190        }
2191    }
2192
2193    @Override
2194    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2195        final int userId = UserHandle.getCallingUserId();
2196        List<String> changedProviders = null;
2197
2198        synchronized (this) {
2199            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2200                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2201            if (activeAdmin.crossProfileWidgetProviders == null) {
2202                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
2203            }
2204            List<String> providers = activeAdmin.crossProfileWidgetProviders;
2205            if (!providers.contains(packageName)) {
2206                providers.add(packageName);
2207                changedProviders = new ArrayList<>(providers);
2208                saveSettingsLocked(userId);
2209            }
2210        }
2211
2212        if (changedProviders != null) {
2213            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2214            return true;
2215        }
2216
2217        return false;
2218    }
2219
2220    @Override
2221    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
2222        final int userId = UserHandle.getCallingUserId();
2223        List<String> changedProviders = null;
2224
2225        synchronized (this) {
2226            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2227                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2228            if (activeAdmin.crossProfileWidgetProviders == null) {
2229                return false;
2230            }
2231            List<String> providers = activeAdmin.crossProfileWidgetProviders;
2232            if (providers.remove(packageName)) {
2233                changedProviders = new ArrayList<>(providers);
2234                saveSettingsLocked(userId);
2235            }
2236        }
2237
2238        if (changedProviders != null) {
2239            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
2240            return true;
2241        }
2242
2243        return false;
2244    }
2245
2246    @Override
2247    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
2248        synchronized (this) {
2249            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
2250                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2251            if (activeAdmin.crossProfileWidgetProviders == null
2252                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
2253                return null;
2254            }
2255            if (Binder.getCallingUid() == Process.myUid()) {
2256                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
2257            } else {
2258                return activeAdmin.crossProfileWidgetProviders;
2259            }
2260        }
2261    }
2262
2263    /**
2264     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
2265     * Returns 0 if not configured.
2266     */
2267    private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
2268        long timeout = 0L;
2269
2270        if (who != null) {
2271            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2272            return admin != null ? admin.passwordExpirationDate : timeout;
2273        }
2274
2275        List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2276        for (UserInfo userInfo : profiles) {
2277            DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2278            final int N = policy.mAdminList.size();
2279            for (int i = 0; i < N; i++) {
2280                ActiveAdmin admin = policy.mAdminList.get(i);
2281                if (timeout == 0L || (admin.passwordExpirationDate != 0
2282                        && timeout > admin.passwordExpirationDate)) {
2283                    timeout = admin.passwordExpirationDate;
2284                }
2285            }
2286        }
2287        return timeout;
2288    }
2289
2290    public long getPasswordExpiration(ComponentName who, int userHandle) {
2291        if (!mHasFeature) {
2292            return 0L;
2293        }
2294        enforceCrossUserPermission(userHandle);
2295        synchronized (this) {
2296            return getPasswordExpirationLocked(who, userHandle);
2297        }
2298    }
2299
2300    public void setPasswordMinimumUpperCase(ComponentName who, int length) {
2301        if (!mHasFeature) {
2302            return;
2303        }
2304        Preconditions.checkNotNull(who, "ComponentName is null");
2305        final int userHandle = UserHandle.getCallingUserId();
2306        synchronized (this) {
2307            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2308                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2309            if (ap.minimumPasswordUpperCase != length) {
2310                ap.minimumPasswordUpperCase = length;
2311                saveSettingsLocked(userHandle);
2312            }
2313        }
2314    }
2315
2316    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
2317        if (!mHasFeature) {
2318            return 0;
2319        }
2320        enforceCrossUserPermission(userHandle);
2321        synchronized (this) {
2322            int length = 0;
2323
2324            if (who != null) {
2325                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2326                return admin != null ? admin.minimumPasswordUpperCase : length;
2327            }
2328
2329            // Return strictest policy for this user and profiles that are visible from this user.
2330            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2331            for (UserInfo userInfo : profiles) {
2332                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2333                final int N = policy.mAdminList.size();
2334                for (int i=0; i<N; i++) {
2335                    ActiveAdmin admin = policy.mAdminList.get(i);
2336                    if (length < admin.minimumPasswordUpperCase) {
2337                        length = admin.minimumPasswordUpperCase;
2338                    }
2339                }
2340            }
2341            return length;
2342        }
2343    }
2344
2345    public void setPasswordMinimumLowerCase(ComponentName who, int length) {
2346        Preconditions.checkNotNull(who, "ComponentName is null");
2347        final int userHandle = UserHandle.getCallingUserId();
2348        synchronized (this) {
2349            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2350                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2351            if (ap.minimumPasswordLowerCase != length) {
2352                ap.minimumPasswordLowerCase = length;
2353                saveSettingsLocked(userHandle);
2354            }
2355        }
2356    }
2357
2358    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
2359        if (!mHasFeature) {
2360            return 0;
2361        }
2362        enforceCrossUserPermission(userHandle);
2363        synchronized (this) {
2364            int length = 0;
2365
2366            if (who != null) {
2367                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2368                return admin != null ? admin.minimumPasswordLowerCase : length;
2369            }
2370
2371            // Return strictest policy for this user and profiles that are visible from this user.
2372            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2373            for (UserInfo userInfo : profiles) {
2374                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2375                final int N = policy.mAdminList.size();
2376                for (int i=0; i<N; i++) {
2377                    ActiveAdmin admin = policy.mAdminList.get(i);
2378                    if (length < admin.minimumPasswordLowerCase) {
2379                        length = admin.minimumPasswordLowerCase;
2380                    }
2381                }
2382            }
2383            return length;
2384        }
2385    }
2386
2387    public void setPasswordMinimumLetters(ComponentName who, int length) {
2388        if (!mHasFeature) {
2389            return;
2390        }
2391        Preconditions.checkNotNull(who, "ComponentName is null");
2392        final int userHandle = UserHandle.getCallingUserId();
2393        synchronized (this) {
2394            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2395                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2396            if (ap.minimumPasswordLetters != length) {
2397                ap.minimumPasswordLetters = length;
2398                saveSettingsLocked(userHandle);
2399            }
2400        }
2401    }
2402
2403    public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
2404        if (!mHasFeature) {
2405            return 0;
2406        }
2407        enforceCrossUserPermission(userHandle);
2408        synchronized (this) {
2409            int length = 0;
2410
2411            if (who != null) {
2412                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2413                return admin != null ? admin.minimumPasswordLetters : length;
2414            }
2415
2416            // Return strictest policy for this user and profiles that are visible from this user.
2417            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2418            for (UserInfo userInfo : profiles) {
2419                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2420                final int N = policy.mAdminList.size();
2421                for (int i=0; i<N; i++) {
2422                    ActiveAdmin admin = policy.mAdminList.get(i);
2423                    if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2424                        continue;
2425                    }
2426                    if (length < admin.minimumPasswordLetters) {
2427                        length = admin.minimumPasswordLetters;
2428                    }
2429                }
2430            }
2431            return length;
2432        }
2433    }
2434
2435    public void setPasswordMinimumNumeric(ComponentName who, int length) {
2436        if (!mHasFeature) {
2437            return;
2438        }
2439        Preconditions.checkNotNull(who, "ComponentName is null");
2440        final int userHandle = UserHandle.getCallingUserId();
2441        synchronized (this) {
2442            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2443                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2444            if (ap.minimumPasswordNumeric != length) {
2445                ap.minimumPasswordNumeric = length;
2446                saveSettingsLocked(userHandle);
2447            }
2448        }
2449    }
2450
2451    public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
2452        if (!mHasFeature) {
2453            return 0;
2454        }
2455        enforceCrossUserPermission(userHandle);
2456        synchronized (this) {
2457            int length = 0;
2458
2459            if (who != null) {
2460                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2461                return admin != null ? admin.minimumPasswordNumeric : length;
2462            }
2463
2464            // Return strictest policy for this user and profiles that are visible from this user.
2465            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2466            for (UserInfo userInfo : profiles) {
2467                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2468                final int N = policy.mAdminList.size();
2469                for (int i = 0; i < N; i++) {
2470                    ActiveAdmin admin = policy.mAdminList.get(i);
2471                    if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2472                        continue;
2473                    }
2474                    if (length < admin.minimumPasswordNumeric) {
2475                        length = admin.minimumPasswordNumeric;
2476                    }
2477                }
2478            }
2479            return length;
2480        }
2481    }
2482
2483    public void setPasswordMinimumSymbols(ComponentName who, int length) {
2484        if (!mHasFeature) {
2485            return;
2486        }
2487        Preconditions.checkNotNull(who, "ComponentName is null");
2488        final int userHandle = UserHandle.getCallingUserId();
2489        synchronized (this) {
2490            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2491                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2492            if (ap.minimumPasswordSymbols != length) {
2493                ap.minimumPasswordSymbols = length;
2494                saveSettingsLocked(userHandle);
2495            }
2496        }
2497    }
2498
2499    public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
2500        if (!mHasFeature) {
2501            return 0;
2502        }
2503        enforceCrossUserPermission(userHandle);
2504        synchronized (this) {
2505            int length = 0;
2506
2507            if (who != null) {
2508                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2509                return admin != null ? admin.minimumPasswordSymbols : length;
2510            }
2511
2512            // Return strictest policy for this user and profiles that are visible from this user.
2513            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2514            for (UserInfo userInfo : profiles) {
2515                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2516                final int N = policy.mAdminList.size();
2517                for (int i=0; i<N; i++) {
2518                    ActiveAdmin admin = policy.mAdminList.get(i);
2519                    if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2520                        continue;
2521                    }
2522                    if (length < admin.minimumPasswordSymbols) {
2523                        length = admin.minimumPasswordSymbols;
2524                    }
2525                }
2526            }
2527            return length;
2528        }
2529    }
2530
2531    public void setPasswordMinimumNonLetter(ComponentName who, int length) {
2532        if (!mHasFeature) {
2533            return;
2534        }
2535        Preconditions.checkNotNull(who, "ComponentName is null");
2536        final int userHandle = UserHandle.getCallingUserId();
2537        synchronized (this) {
2538            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2539                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2540            if (ap.minimumPasswordNonLetter != length) {
2541                ap.minimumPasswordNonLetter = length;
2542                saveSettingsLocked(userHandle);
2543            }
2544        }
2545    }
2546
2547    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2548        if (!mHasFeature) {
2549            return 0;
2550        }
2551        enforceCrossUserPermission(userHandle);
2552        synchronized (this) {
2553            int length = 0;
2554
2555            if (who != null) {
2556                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2557                return admin != null ? admin.minimumPasswordNonLetter : length;
2558            }
2559
2560            // Return strictest policy for this user and profiles that are visible from this user.
2561            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2562            for (UserInfo userInfo : profiles) {
2563                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2564                final int N = policy.mAdminList.size();
2565                for (int i=0; i<N; i++) {
2566                    ActiveAdmin admin = policy.mAdminList.get(i);
2567                    if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
2568                        continue;
2569                    }
2570                    if (length < admin.minimumPasswordNonLetter) {
2571                        length = admin.minimumPasswordNonLetter;
2572                    }
2573                }
2574            }
2575            return length;
2576        }
2577    }
2578
2579    public boolean isActivePasswordSufficient(int userHandle) {
2580        if (!mHasFeature) {
2581            return true;
2582        }
2583        enforceCrossUserPermission(userHandle);
2584
2585        synchronized (this) {
2586
2587            // The active password is stored in the user that runs the launcher
2588            // If the user this is called from is part of a profile group, that is the parent
2589            // of the group.
2590            UserInfo parent = getProfileParent(userHandle);
2591            int id = (parent == null) ? userHandle : parent.id;
2592            DevicePolicyData policy = getUserDataUnchecked(id);
2593
2594            // This API can only be called by an active device admin,
2595            // so try to retrieve it to check that the caller is one.
2596            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2597            if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2598                    || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2599                return false;
2600            }
2601            if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2602                return true;
2603            }
2604            return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2605                && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2606                && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2607                && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2608                && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2609                && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2610        }
2611    }
2612
2613    public int getCurrentFailedPasswordAttempts(int userHandle) {
2614        synchronized (this) {
2615            // This API can only be called by an active device admin,
2616            // so try to retrieve it to check that the caller is one.
2617            getActiveAdminForCallerLocked(null,
2618                    DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2619
2620            // The active password is stored in the parent.
2621            UserInfo parent = getProfileParent(userHandle);
2622            int id = (parent == null) ? userHandle : parent.id;
2623            DevicePolicyData policy = getUserDataUnchecked(id);
2624
2625            return policy.mFailedPasswordAttempts;
2626        }
2627    }
2628
2629    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num) {
2630        if (!mHasFeature) {
2631            return;
2632        }
2633        Preconditions.checkNotNull(who, "ComponentName is null");
2634        final int userHandle = UserHandle.getCallingUserId();
2635        synchronized (this) {
2636            // This API can only be called by an active device admin,
2637            // so try to retrieve it to check that the caller is one.
2638            getActiveAdminForCallerLocked(who,
2639                    DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2640            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2641                    DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2642            if (ap.maximumFailedPasswordsForWipe != num) {
2643                ap.maximumFailedPasswordsForWipe = num;
2644                saveSettingsLocked(userHandle);
2645            }
2646        }
2647    }
2648
2649    @Override
2650    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2651        if (!mHasFeature) {
2652            return 0;
2653        }
2654        enforceCrossUserPermission(userHandle);
2655        synchronized (this) {
2656            ActiveAdmin admin = (who != null) ? getActiveAdminUncheckedLocked(who, userHandle)
2657                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2658            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
2659        }
2660    }
2661
2662    @Override
2663    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle) {
2664        if (!mHasFeature) {
2665            return UserHandle.USER_NULL;
2666        }
2667        enforceCrossUserPermission(userHandle);
2668        synchronized (this) {
2669            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
2670            return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
2671        }
2672    }
2673
2674    /**
2675     * Returns the admin with the strictest policy on maximum failed passwords for this user and all
2676     * profiles that are visible from this user. If the policy for the primary and any other profile
2677     * are equal, it returns the admin for the primary profile.
2678     * Returns {@code null} if none of them have that policy set.
2679     */
2680    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(int userHandle) {
2681        int count = 0;
2682        ActiveAdmin strictestAdmin = null;
2683        for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
2684            DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2685            for (ActiveAdmin admin : policy.mAdminList) {
2686                if (admin.maximumFailedPasswordsForWipe ==
2687                        ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2688                    continue;  // No max number of failed passwords policy set for this profile.
2689                }
2690
2691                // We always favor the primary profile if several profiles have the same value set.
2692                if (count == 0 ||
2693                        count > admin.maximumFailedPasswordsForWipe ||
2694                        (userInfo.isPrimary() && count >= admin.maximumFailedPasswordsForWipe)) {
2695                    count = admin.maximumFailedPasswordsForWipe;
2696                    strictestAdmin = admin;
2697                }
2698            }
2699        }
2700        return strictestAdmin;
2701    }
2702
2703    public boolean resetPassword(String passwordOrNull, int flags) {
2704        if (!mHasFeature) {
2705            return false;
2706        }
2707        final int userHandle = UserHandle.getCallingUserId();
2708        enforceNotManagedProfile(userHandle, "reset the password");
2709
2710        String password = passwordOrNull != null ? passwordOrNull : "";
2711
2712        int quality;
2713        synchronized (this) {
2714            // This api can only be called by an active device admin,
2715            // so try to retrieve it to check that the caller is one.
2716            getActiveAdminForCallerLocked(null,
2717                    DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2718            quality = getPasswordQuality(null, userHandle);
2719            if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2720                int realQuality = LockPatternUtils.computePasswordQuality(password);
2721                if (realQuality < quality
2722                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2723                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2724                            + Integer.toHexString(realQuality)
2725                            + " does not meet required quality 0x"
2726                            + Integer.toHexString(quality));
2727                    return false;
2728                }
2729                quality = Math.max(realQuality, quality);
2730            }
2731            int length = getPasswordMinimumLength(null, userHandle);
2732            if (password.length() < length) {
2733                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2734                        + " does not meet required length " + length);
2735                return false;
2736            }
2737            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2738                int letters = 0;
2739                int uppercase = 0;
2740                int lowercase = 0;
2741                int numbers = 0;
2742                int symbols = 0;
2743                int nonletter = 0;
2744                for (int i = 0; i < password.length(); i++) {
2745                    char c = password.charAt(i);
2746                    if (c >= 'A' && c <= 'Z') {
2747                        letters++;
2748                        uppercase++;
2749                    } else if (c >= 'a' && c <= 'z') {
2750                        letters++;
2751                        lowercase++;
2752                    } else if (c >= '0' && c <= '9') {
2753                        numbers++;
2754                        nonletter++;
2755                    } else {
2756                        symbols++;
2757                        nonletter++;
2758                    }
2759                }
2760                int neededLetters = getPasswordMinimumLetters(null, userHandle);
2761                if(letters < neededLetters) {
2762                    Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2763                            + " does not meet required number of letters " + neededLetters);
2764                    return false;
2765                }
2766                int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2767                if (numbers < neededNumbers) {
2768                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2769                            + " does not meet required number of numerical digits "
2770                            + neededNumbers);
2771                    return false;
2772                }
2773                int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2774                if (lowercase < neededLowerCase) {
2775                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2776                            + " does not meet required number of lowercase letters "
2777                            + neededLowerCase);
2778                    return false;
2779                }
2780                int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2781                if (uppercase < neededUpperCase) {
2782                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2783                            + " does not meet required number of uppercase letters "
2784                            + neededUpperCase);
2785                    return false;
2786                }
2787                int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2788                if (symbols < neededSymbols) {
2789                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2790                            + " does not meet required number of special symbols " + neededSymbols);
2791                    return false;
2792                }
2793                int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2794                if (nonletter < neededNonLetter) {
2795                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2796                            + " does not meet required number of non-letter characters "
2797                            + neededNonLetter);
2798                    return false;
2799                }
2800            }
2801        }
2802
2803        int callingUid = Binder.getCallingUid();
2804        DevicePolicyData policy = getUserData(userHandle);
2805        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2806            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2807            return false;
2808        }
2809
2810        // Don't do this with the lock held, because it is going to call
2811        // back in to the service.
2812        long ident = Binder.clearCallingIdentity();
2813        try {
2814            LockPatternUtils utils = new LockPatternUtils(mContext);
2815            if (!TextUtils.isEmpty(password)) {
2816                utils.saveLockPassword(password, quality, userHandle);
2817            } else {
2818                utils.clearLock(userHandle);
2819            }
2820            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
2821            if (requireEntry) {
2822                utils.requireCredentialEntry(UserHandle.USER_ALL);
2823            }
2824            synchronized (this) {
2825                int newOwner = requireEntry ? callingUid : -1;
2826                if (policy.mPasswordOwner != newOwner) {
2827                    policy.mPasswordOwner = newOwner;
2828                    saveSettingsLocked(userHandle);
2829                }
2830            }
2831        } finally {
2832            Binder.restoreCallingIdentity(ident);
2833        }
2834
2835        return true;
2836    }
2837
2838    public void setMaximumTimeToLock(ComponentName who, long timeMs) {
2839        if (!mHasFeature) {
2840            return;
2841        }
2842        Preconditions.checkNotNull(who, "ComponentName is null");
2843        final int userHandle = UserHandle.getCallingUserId();
2844        synchronized (this) {
2845            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2846                    DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2847            if (ap.maximumTimeToUnlock != timeMs) {
2848                ap.maximumTimeToUnlock = timeMs;
2849                saveSettingsLocked(userHandle);
2850                updateMaximumTimeToLockLocked(getUserData(userHandle));
2851            }
2852        }
2853    }
2854
2855    void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
2856        long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
2857        if (policy.mLastMaximumTimeToLock == timeMs) {
2858            return;
2859        }
2860
2861        long ident = Binder.clearCallingIdentity();
2862        try {
2863            if (timeMs <= 0) {
2864                timeMs = Integer.MAX_VALUE;
2865            } else {
2866                // Make sure KEEP_SCREEN_ON is disabled, since that
2867                // would allow bypassing of the maximum time to lock.
2868                Settings.Global.putInt(mContext.getContentResolver(),
2869                        Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
2870            }
2871
2872            policy.mLastMaximumTimeToLock = timeMs;
2873            mPowerManagerInternal.setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
2874        } finally {
2875            Binder.restoreCallingIdentity(ident);
2876        }
2877    }
2878
2879    public long getMaximumTimeToLock(ComponentName who, int userHandle) {
2880        if (!mHasFeature) {
2881            return 0;
2882        }
2883        enforceCrossUserPermission(userHandle);
2884        synchronized (this) {
2885            long time = 0;
2886
2887            if (who != null) {
2888                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2889                return admin != null ? admin.maximumTimeToUnlock : time;
2890            }
2891
2892            // Return strictest policy for this user and profiles that are visible from this user.
2893            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2894            for (UserInfo userInfo : profiles) {
2895                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
2896                final int N = policy.mAdminList.size();
2897                for (int i=0; i<N; i++) {
2898                    ActiveAdmin admin = policy.mAdminList.get(i);
2899                    if (time == 0) {
2900                        time = admin.maximumTimeToUnlock;
2901                    } else if (admin.maximumTimeToUnlock != 0
2902                            && time > admin.maximumTimeToUnlock) {
2903                        time = admin.maximumTimeToUnlock;
2904                    }
2905                }
2906            }
2907            return time;
2908        }
2909    }
2910
2911    public void lockNow() {
2912        if (!mHasFeature) {
2913            return;
2914        }
2915        synchronized (this) {
2916            // This API can only be called by an active device admin,
2917            // so try to retrieve it to check that the caller is one.
2918            getActiveAdminForCallerLocked(null,
2919                    DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2920            lockNowUnchecked();
2921        }
2922    }
2923
2924    private void lockNowUnchecked() {
2925        long ident = Binder.clearCallingIdentity();
2926        try {
2927            // Power off the display
2928            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
2929                    PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
2930            // Ensure the device is locked
2931            new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL);
2932            getWindowManager().lockNow(null);
2933        } catch (RemoteException e) {
2934        } finally {
2935            Binder.restoreCallingIdentity(ident);
2936        }
2937    }
2938
2939    private boolean isExtStorageEncrypted() {
2940        String state = SystemProperties.get("vold.decrypt");
2941        return !"".equals(state);
2942    }
2943
2944    @Override
2945    public void enforceCanManageCaCerts(ComponentName who) {
2946        if (who == null) {
2947            if (!isCallerDelegatedCertInstaller()) {
2948                mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
2949            }
2950        } else {
2951            synchronized (this) {
2952                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
2953            }
2954        }
2955    }
2956
2957    private boolean isCallerDelegatedCertInstaller() {
2958        final int callingUid = Binder.getCallingUid();
2959        final int userHandle = UserHandle.getUserId(callingUid);
2960        synchronized (this) {
2961            final DevicePolicyData policy = getUserData(userHandle);
2962            if (policy.mDelegatedCertInstallerPackage == null) {
2963                return false;
2964            }
2965
2966            try {
2967                int uid = mContext.getPackageManager().getPackageUid(
2968                        policy.mDelegatedCertInstallerPackage, userHandle);
2969                return uid == callingUid;
2970            } catch (NameNotFoundException e) {
2971                return false;
2972            }
2973        }
2974    }
2975
2976    @Override
2977    public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
2978        enforceCanManageCaCerts(admin);
2979
2980        byte[] pemCert;
2981        try {
2982            X509Certificate cert = parseCert(certBuffer);
2983            pemCert = Credentials.convertToPem(cert);
2984        } catch (CertificateException ce) {
2985            Log.e(LOG_TAG, "Problem converting cert", ce);
2986            return false;
2987        } catch (IOException ioe) {
2988            Log.e(LOG_TAG, "Problem reading cert", ioe);
2989            return false;
2990        }
2991
2992        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
2993        final long id = Binder.clearCallingIdentity();
2994        try {
2995            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
2996            try {
2997                keyChainConnection.getService().installCaCertificate(pemCert);
2998                return true;
2999            } catch (RemoteException e) {
3000                Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
3001            } finally {
3002                keyChainConnection.close();
3003            }
3004        } catch (InterruptedException e1) {
3005            Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
3006            Thread.currentThread().interrupt();
3007        } finally {
3008            Binder.restoreCallingIdentity(id);
3009        }
3010        return false;
3011    }
3012
3013    private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
3014        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
3015        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
3016                certBuffer));
3017    }
3018
3019    @Override
3020    public void uninstallCaCert(ComponentName admin, String alias) {
3021        enforceCanManageCaCerts(admin);
3022
3023        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3024        final long id = Binder.clearCallingIdentity();
3025        try {
3026            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3027            try {
3028                keyChainConnection.getService().deleteCaCertificate(alias);
3029            } catch (RemoteException e) {
3030                Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
3031            } finally {
3032                keyChainConnection.close();
3033            }
3034        } catch (InterruptedException ie) {
3035            Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
3036            Thread.currentThread().interrupt();
3037        } finally {
3038            Binder.restoreCallingIdentity(id);
3039        }
3040    }
3041
3042    @Override
3043    public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, String alias) {
3044        if (who == null) {
3045            if (!isCallerDelegatedCertInstaller()) {
3046                throw new SecurityException("who == null, but caller is not cert installer");
3047            }
3048        } else {
3049            synchronized (this) {
3050                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3051            }
3052        }
3053        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3054        final long id = Binder.clearCallingIdentity();
3055        try {
3056          final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
3057          try {
3058              IKeyChainService keyChain = keyChainConnection.getService();
3059              return keyChain.installKeyPair(privKey, cert, alias);
3060          } catch (RemoteException e) {
3061              Log.e(LOG_TAG, "Installing certificate", e);
3062          } finally {
3063              keyChainConnection.close();
3064          }
3065        } catch (InterruptedException e) {
3066            Log.w(LOG_TAG, "Interrupted while installing certificate", e);
3067            Thread.currentThread().interrupt();
3068        } finally {
3069            Binder.restoreCallingIdentity(id);
3070        }
3071        return false;
3072    }
3073
3074    @Override
3075    public void choosePrivateKeyAlias(final int uid, final String host, int port, final String url,
3076            final String alias, final IBinder response) {
3077        // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
3078        if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
3079            return;
3080        }
3081
3082        final UserHandle caller = Binder.getCallingUserHandle();
3083        final ComponentName profileOwner = getProfileOwner(caller.getIdentifier());
3084
3085        if (profileOwner == null) {
3086            sendPrivateKeyAliasResponse(null, response);
3087            return;
3088        }
3089
3090        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
3091        intent.setComponent(profileOwner);
3092        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
3093        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_HOST, host);
3094        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_PORT, port);
3095        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URL, url);
3096        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
3097        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
3098
3099        final long id = Binder.clearCallingIdentity();
3100        try {
3101            mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
3102                @Override
3103                public void onReceive(Context context, Intent intent) {
3104                    final String chosenAlias = getResultData();
3105                    sendPrivateKeyAliasResponse(chosenAlias, response);
3106                }
3107            }, null, Activity.RESULT_OK, null, null);
3108        } finally {
3109            Binder.restoreCallingIdentity(id);
3110        }
3111    }
3112
3113    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
3114        final IKeyChainAliasCallback keyChainAliasResponse =
3115                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
3116        new AsyncTask<Void, Void, Void>() {
3117            @Override
3118            protected Void doInBackground(Void... unused) {
3119                try {
3120                    keyChainAliasResponse.alias(alias);
3121                } catch (Exception e) {
3122                    // Catch everything (not just RemoteException): caller could throw a
3123                    // RuntimeException back across processes.
3124                    Log.e(LOG_TAG, "error while responding to callback", e);
3125                }
3126                return null;
3127            }
3128        }.execute();
3129    }
3130
3131    @Override
3132    public void setCertInstallerPackage(ComponentName who, String installerPackage)
3133            throws SecurityException {
3134        int userHandle = UserHandle.getCallingUserId();
3135        synchronized (this) {
3136            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3137            DevicePolicyData policy = getUserData(userHandle);
3138            policy.mDelegatedCertInstallerPackage = installerPackage;
3139            saveSettingsLocked(userHandle);
3140        }
3141    }
3142
3143    @Override
3144    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
3145        int userHandle = UserHandle.getCallingUserId();
3146        synchronized (this) {
3147            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3148            DevicePolicyData policy = getUserData(userHandle);
3149            return policy.mDelegatedCertInstallerPackage;
3150        }
3151    }
3152
3153    private void wipeDataLocked(boolean wipeExtRequested, String reason) {
3154        // TODO: wipe all public volumes on device
3155
3156        // If the SD card is encrypted and non-removable, we have to force a wipe.
3157        boolean forceExtWipe = !Environment.isExternalStorageRemovable() && isExtStorageEncrypted();
3158
3159        // Note: we can only do the wipe via ExternalStorageFormatter if the volume is not emulated.
3160        if ((forceExtWipe || wipeExtRequested) && !Environment.isExternalStorageEmulated()) {
3161            Intent intent = new Intent(ExternalStorageFormatter.FORMAT_AND_FACTORY_RESET);
3162            intent.putExtra(ExternalStorageFormatter.EXTRA_ALWAYS_RESET, true);
3163            intent.putExtra(Intent.EXTRA_REASON, reason);
3164            intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME);
3165            mWakeLock.acquire(10000);
3166            mContext.startService(intent);
3167        } else {
3168            try {
3169                RecoverySystem.rebootWipeUserData(mContext, reason);
3170            } catch (IOException | SecurityException e) {
3171                Slog.w(LOG_TAG, "Failed requesting data wipe", e);
3172            }
3173        }
3174    }
3175
3176    @Override
3177    public void wipeData(int flags, final int userHandle) {
3178        if (!mHasFeature) {
3179            return;
3180        }
3181        enforceCrossUserPermission(userHandle);
3182        synchronized (this) {
3183            // This API can only be called by an active device admin,
3184            // so try to retrieve it to check that the caller is one.
3185            final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
3186                    DeviceAdminInfo.USES_POLICY_WIPE_DATA);
3187
3188            final String source;
3189            final ComponentName cname = admin.info.getComponent();
3190            if (cname != null) {
3191                source = cname.flattenToShortString();
3192            } else {
3193                source = admin.info.getPackageName();
3194            }
3195
3196            long ident = Binder.clearCallingIdentity();
3197            try {
3198                if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
3199                    boolean ownsInitialization = isDeviceInitializer(admin.info.getPackageName())
3200                            && !hasUserSetupCompleted(userHandle);
3201                    if (userHandle != UserHandle.USER_OWNER
3202                            || !(isDeviceOwner(admin.info.getPackageName())
3203                                    || ownsInitialization)) {
3204                        throw new SecurityException(
3205                               "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
3206                    }
3207                    PersistentDataBlockManager manager = (PersistentDataBlockManager)
3208                            mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
3209                    if (manager != null) {
3210                        manager.wipe();
3211                    }
3212                }
3213                boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
3214                wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
3215                        "DevicePolicyManager.wipeData() from " + source);
3216            } finally {
3217                Binder.restoreCallingIdentity(ident);
3218            }
3219        }
3220    }
3221
3222    private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle, String reason) {
3223        if (userHandle == UserHandle.USER_OWNER) {
3224            wipeDataLocked(wipeExtRequested, reason);
3225        } else {
3226            mHandler.post(new Runnable() {
3227                public void run() {
3228                    try {
3229                        IActivityManager am = ActivityManagerNative.getDefault();
3230                        if (am.getCurrentUser().id == userHandle) {
3231                            am.switchUser(UserHandle.USER_OWNER);
3232                        }
3233                        if (!mUserManager.removeUser(userHandle)) {
3234                            Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
3235                        }
3236                    } catch (RemoteException re) {
3237                        // Shouldn't happen
3238                    }
3239                }
3240            });
3241        }
3242    }
3243
3244    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
3245        if (!mHasFeature) {
3246            return;
3247        }
3248        enforceCrossUserPermission(userHandle);
3249        mContext.enforceCallingOrSelfPermission(
3250                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3251
3252        synchronized (this) {
3253            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
3254            if (admin == null) {
3255                try {
3256                    result.sendResult(null);
3257                } catch (RemoteException e) {
3258                }
3259                return;
3260            }
3261            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
3262            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3263            intent.setComponent(admin.info.getComponent());
3264            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
3265                    null, new BroadcastReceiver() {
3266                @Override
3267                public void onReceive(Context context, Intent intent) {
3268                    try {
3269                        result.sendResult(getResultExtras(false));
3270                    } catch (RemoteException e) {
3271                    }
3272                }
3273            }, null, Activity.RESULT_OK, null, null);
3274        }
3275    }
3276
3277    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
3278            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
3279        if (!mHasFeature) {
3280            return;
3281        }
3282        enforceCrossUserPermission(userHandle);
3283        enforceNotManagedProfile(userHandle, "set the active password");
3284
3285        mContext.enforceCallingOrSelfPermission(
3286                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3287        DevicePolicyData p = getUserData(userHandle);
3288
3289        validateQualityConstant(quality);
3290
3291        synchronized (this) {
3292            if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
3293                    || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
3294                    || p.mActivePasswordUpperCase != uppercase
3295                    || p.mActivePasswordLowerCase != lowercase
3296                    || p.mActivePasswordNumeric != numbers
3297                    || p.mActivePasswordSymbols != symbols
3298                    || p.mActivePasswordNonLetter != nonletter) {
3299                long ident = Binder.clearCallingIdentity();
3300                try {
3301                    p.mActivePasswordQuality = quality;
3302                    p.mActivePasswordLength = length;
3303                    p.mActivePasswordLetters = letters;
3304                    p.mActivePasswordLowerCase = lowercase;
3305                    p.mActivePasswordUpperCase = uppercase;
3306                    p.mActivePasswordNumeric = numbers;
3307                    p.mActivePasswordSymbols = symbols;
3308                    p.mActivePasswordNonLetter = nonletter;
3309                    p.mFailedPasswordAttempts = 0;
3310                    saveSettingsLocked(userHandle);
3311                    updatePasswordExpirationsLocked(userHandle);
3312                    setExpirationAlarmCheckLocked(mContext, p);
3313                    sendAdminCommandToSelfAndProfilesLocked(
3314                            DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
3315                            DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
3316                } finally {
3317                    Binder.restoreCallingIdentity(ident);
3318                }
3319            }
3320        }
3321    }
3322
3323    /**
3324     * Called any time the device password is updated. Resets all password expiration clocks.
3325     */
3326    private void updatePasswordExpirationsLocked(int userHandle) {
3327            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
3328            for (UserInfo userInfo : profiles) {
3329                int profileId = userInfo.id;
3330                DevicePolicyData policy = getUserDataUnchecked(profileId);
3331                final int N = policy.mAdminList.size();
3332                if (N > 0) {
3333                    for (int i=0; i<N; i++) {
3334                        ActiveAdmin admin = policy.mAdminList.get(i);
3335                        if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
3336                            long timeout = admin.passwordExpirationTimeout;
3337                            long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3338                            admin.passwordExpirationDate = expiration;
3339                        }
3340                    }
3341                }
3342                saveSettingsLocked(profileId);
3343            }
3344    }
3345
3346    public void reportFailedPasswordAttempt(int userHandle) {
3347        enforceCrossUserPermission(userHandle);
3348        enforceNotManagedProfile(userHandle, "report failed password attempt");
3349        mContext.enforceCallingOrSelfPermission(
3350                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3351
3352        long ident = Binder.clearCallingIdentity();
3353        try {
3354            boolean wipeData = false;
3355            int identifier = 0;
3356            synchronized (this) {
3357                DevicePolicyData policy = getUserData(userHandle);
3358                policy.mFailedPasswordAttempts++;
3359                saveSettingsLocked(userHandle);
3360                if (mHasFeature) {
3361                    ActiveAdmin strictestAdmin =
3362                            getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle);
3363                    int max = strictestAdmin != null
3364                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
3365                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
3366                        // Wipe the user/profile associated with the policy that was violated. This
3367                        // is not necessarily calling user: if the policy that fired was from a
3368                        // managed profile rather than the main user profile, we wipe former only.
3369                        wipeData = true;
3370                        identifier = strictestAdmin.getUserHandle().getIdentifier();
3371                    }
3372                    sendAdminCommandToSelfAndProfilesLocked(
3373                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
3374                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3375                }
3376            }
3377            if (wipeData) {
3378                // Call without holding lock.
3379                wipeDeviceOrUserLocked(false, identifier,
3380                        "reportFailedPasswordAttempt()");
3381            }
3382        } finally {
3383            Binder.restoreCallingIdentity(ident);
3384        }
3385    }
3386
3387    public void reportSuccessfulPasswordAttempt(int userHandle) {
3388        enforceCrossUserPermission(userHandle);
3389        mContext.enforceCallingOrSelfPermission(
3390                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
3391
3392        synchronized (this) {
3393            DevicePolicyData policy = getUserData(userHandle);
3394            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
3395                long ident = Binder.clearCallingIdentity();
3396                try {
3397                    policy.mFailedPasswordAttempts = 0;
3398                    policy.mPasswordOwner = -1;
3399                    saveSettingsLocked(userHandle);
3400                    if (mHasFeature) {
3401                        sendAdminCommandToSelfAndProfilesLocked(
3402                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
3403                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
3404                    }
3405                } finally {
3406                    Binder.restoreCallingIdentity(ident);
3407                }
3408            }
3409        }
3410    }
3411
3412    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
3413            String exclusionList) {
3414        if (!mHasFeature) {
3415            return null;
3416        }
3417        synchronized(this) {
3418            Preconditions.checkNotNull(who, "ComponentName is null");
3419
3420            // Only check if owner has set global proxy. We don't allow other users to set it.
3421            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3422            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3423                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
3424
3425            // Scan through active admins and find if anyone has already
3426            // set the global proxy.
3427            Set<ComponentName> compSet = policy.mAdminMap.keySet();
3428            for (ComponentName component : compSet) {
3429                ActiveAdmin ap = policy.mAdminMap.get(component);
3430                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
3431                    // Another admin already sets the global proxy
3432                    // Return it to the caller.
3433                    return component;
3434                }
3435            }
3436
3437            // If the user is not the owner, don't set the global proxy. Fail silently.
3438            if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3439                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
3440                        + UserHandle.getCallingUserId() + " is not permitted.");
3441                return null;
3442            }
3443            if (proxySpec == null) {
3444                admin.specifiesGlobalProxy = false;
3445                admin.globalProxySpec = null;
3446                admin.globalProxyExclusionList = null;
3447            } else {
3448
3449                admin.specifiesGlobalProxy = true;
3450                admin.globalProxySpec = proxySpec;
3451                admin.globalProxyExclusionList = exclusionList;
3452            }
3453
3454            // Reset the global proxy accordingly
3455            // Do this using system permissions, as apps cannot write to secure settings
3456            long origId = Binder.clearCallingIdentity();
3457            try {
3458                resetGlobalProxyLocked(policy);
3459            } finally {
3460                Binder.restoreCallingIdentity(origId);
3461            }
3462            return null;
3463        }
3464    }
3465
3466    public ComponentName getGlobalProxyAdmin(int userHandle) {
3467        if (!mHasFeature) {
3468            return null;
3469        }
3470        enforceCrossUserPermission(userHandle);
3471        synchronized(this) {
3472            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3473            // Scan through active admins and find if anyone has already
3474            // set the global proxy.
3475            final int N = policy.mAdminList.size();
3476            for (int i = 0; i < N; i++) {
3477                ActiveAdmin ap = policy.mAdminList.get(i);
3478                if (ap.specifiesGlobalProxy) {
3479                    // Device admin sets the global proxy
3480                    // Return it to the caller.
3481                    return ap.info.getComponent();
3482                }
3483            }
3484        }
3485        // No device admin sets the global proxy.
3486        return null;
3487    }
3488
3489    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
3490        synchronized (this) {
3491            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3492        }
3493        long token = Binder.clearCallingIdentity();
3494        try {
3495            ConnectivityManager connectivityManager = (ConnectivityManager)
3496                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3497            connectivityManager.setGlobalProxy(proxyInfo);
3498        } finally {
3499            Binder.restoreCallingIdentity(token);
3500        }
3501    }
3502
3503    private void resetGlobalProxyLocked(DevicePolicyData policy) {
3504        final int N = policy.mAdminList.size();
3505        for (int i = 0; i < N; i++) {
3506            ActiveAdmin ap = policy.mAdminList.get(i);
3507            if (ap.specifiesGlobalProxy) {
3508                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
3509                return;
3510            }
3511        }
3512        // No device admins defining global proxies - reset global proxy settings to none
3513        saveGlobalProxyLocked(null, null);
3514    }
3515
3516    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
3517        if (exclusionList == null) {
3518            exclusionList = "";
3519        }
3520        if (proxySpec == null) {
3521            proxySpec = "";
3522        }
3523        // Remove white spaces
3524        proxySpec = proxySpec.trim();
3525        String data[] = proxySpec.split(":");
3526        int proxyPort = 8080;
3527        if (data.length > 1) {
3528            try {
3529                proxyPort = Integer.parseInt(data[1]);
3530            } catch (NumberFormatException e) {}
3531        }
3532        exclusionList = exclusionList.trim();
3533        ContentResolver res = mContext.getContentResolver();
3534
3535        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
3536        if (!proxyProperties.isValid()) {
3537            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
3538            return;
3539        }
3540        Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
3541        Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
3542        Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3543                exclusionList);
3544    }
3545
3546    /**
3547     * Set the storage encryption request for a single admin.  Returns the new total request
3548     * status (for all admins).
3549     */
3550    public int setStorageEncryption(ComponentName who, boolean encrypt) {
3551        if (!mHasFeature) {
3552            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3553        }
3554        Preconditions.checkNotNull(who, "ComponentName is null");
3555        final int userHandle = UserHandle.getCallingUserId();
3556        synchronized (this) {
3557            // Check for permissions
3558            // Only owner can set storage encryption
3559            if (userHandle != UserHandle.USER_OWNER
3560                    || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
3561                Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
3562                        + UserHandle.getCallingUserId() + " is not permitted.");
3563                return 0;
3564            }
3565
3566            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3567                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
3568
3569            // Quick exit:  If the filesystem does not support encryption, we can exit early.
3570            if (!isEncryptionSupported()) {
3571                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3572            }
3573
3574            // (1) Record the value for the admin so it's sticky
3575            if (ap.encryptionRequested != encrypt) {
3576                ap.encryptionRequested = encrypt;
3577                saveSettingsLocked(userHandle);
3578            }
3579
3580            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3581            // (2) Compute "max" for all admins
3582            boolean newRequested = false;
3583            final int N = policy.mAdminList.size();
3584            for (int i = 0; i < N; i++) {
3585                newRequested |= policy.mAdminList.get(i).encryptionRequested;
3586            }
3587
3588            // Notify OS of new request
3589            setEncryptionRequested(newRequested);
3590
3591            // Return the new global request status
3592            return newRequested
3593                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3594                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3595        }
3596    }
3597
3598    /**
3599     * Get the current storage encryption request status for a given admin, or aggregate of all
3600     * active admins.
3601     */
3602    public boolean getStorageEncryption(ComponentName who, int userHandle) {
3603        if (!mHasFeature) {
3604            return false;
3605        }
3606        enforceCrossUserPermission(userHandle);
3607        synchronized (this) {
3608            // Check for permissions if a particular caller is specified
3609            if (who != null) {
3610                // When checking for a single caller, status is based on caller's request
3611                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
3612                return ap != null ? ap.encryptionRequested : false;
3613            }
3614
3615            // If no particular caller is specified, return the aggregate set of requests.
3616            // This is short circuited by returning true on the first hit.
3617            DevicePolicyData policy = getUserData(userHandle);
3618            final int N = policy.mAdminList.size();
3619            for (int i = 0; i < N; i++) {
3620                if (policy.mAdminList.get(i).encryptionRequested) {
3621                    return true;
3622                }
3623            }
3624            return false;
3625        }
3626    }
3627
3628    /**
3629     * Get the current encryption status of the device.
3630     */
3631    public int getStorageEncryptionStatus(int userHandle) {
3632        if (!mHasFeature) {
3633            // Ok to return current status.
3634        }
3635        enforceCrossUserPermission(userHandle);
3636        return getEncryptionStatus();
3637    }
3638
3639    /**
3640     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
3641     */
3642    private boolean isEncryptionSupported() {
3643        // Note, this can be implemented as
3644        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3645        // But is provided as a separate internal method if there's a faster way to do a
3646        // simple check for supported-or-not.
3647        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3648    }
3649
3650    /**
3651     * Hook to low-levels:  Reporting the current status of encryption.
3652     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
3653     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
3654     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, or
3655     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
3656     */
3657    private int getEncryptionStatus() {
3658        String status = SystemProperties.get("ro.crypto.state", "unsupported");
3659        if ("encrypted".equalsIgnoreCase(status)) {
3660            final long token = Binder.clearCallingIdentity();
3661            try {
3662                return LockPatternUtils.isDeviceEncrypted()
3663                        ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
3664                        : DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
3665            } finally {
3666                Binder.restoreCallingIdentity(token);
3667            }
3668        } else if ("unencrypted".equalsIgnoreCase(status)) {
3669            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
3670        } else {
3671            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
3672        }
3673    }
3674
3675    /**
3676     * Hook to low-levels:  If needed, record the new admin setting for encryption.
3677     */
3678    private void setEncryptionRequested(boolean encrypt) {
3679    }
3680
3681
3682    /**
3683     * Set whether the screen capture is disabled for the user managed by the specified admin.
3684     */
3685    public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
3686        if (!mHasFeature) {
3687            return;
3688        }
3689        Preconditions.checkNotNull(who, "ComponentName is null");
3690        final int userHandle = UserHandle.getCallingUserId();
3691        synchronized (this) {
3692            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3693                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3694            if (ap.disableScreenCapture != disabled) {
3695                ap.disableScreenCapture = disabled;
3696                saveSettingsLocked(userHandle);
3697                updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
3698            }
3699        }
3700    }
3701
3702    /**
3703     * Returns whether or not screen capture is disabled for a given admin, or disabled for any
3704     * active admin (if given admin is null).
3705     */
3706    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
3707        if (!mHasFeature) {
3708            return false;
3709        }
3710        synchronized (this) {
3711            if (who != null) {
3712                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3713                return (admin != null) ? admin.disableScreenCapture : false;
3714            }
3715
3716            DevicePolicyData policy = getUserData(userHandle);
3717            final int N = policy.mAdminList.size();
3718            for (int i = 0; i < N; i++) {
3719                ActiveAdmin admin = policy.mAdminList.get(i);
3720                if (admin.disableScreenCapture) {
3721                    return true;
3722                }
3723            }
3724            return false;
3725        }
3726    }
3727
3728    private void updateScreenCaptureDisabledInWindowManager(int userHandle, boolean disabled) {
3729        long ident = Binder.clearCallingIdentity();
3730        try {
3731            getWindowManager().setScreenCaptureDisabled(userHandle, disabled);
3732        } catch (RemoteException e) {
3733            Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
3734        } finally {
3735            Binder.restoreCallingIdentity(ident);
3736        }
3737    }
3738
3739    /**
3740     * Set whether auto time is required by the specified admin (must be device owner).
3741     */
3742    public void setAutoTimeRequired(ComponentName who, boolean required) {
3743        if (!mHasFeature) {
3744            return;
3745        }
3746        Preconditions.checkNotNull(who, "ComponentName is null");
3747        final int userHandle = UserHandle.getCallingUserId();
3748        synchronized (this) {
3749            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
3750                    DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3751            if (admin.requireAutoTime != required) {
3752                admin.requireAutoTime = required;
3753                saveSettingsLocked(userHandle);
3754            }
3755        }
3756
3757        // Turn AUTO_TIME on in settings if it is required
3758        if (required) {
3759            long ident = Binder.clearCallingIdentity();
3760            try {
3761                Settings.Global.putInt(mContext.getContentResolver(),
3762                        Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
3763            } finally {
3764                Binder.restoreCallingIdentity(ident);
3765            }
3766        }
3767    }
3768
3769    /**
3770     * Returns whether or not auto time is required by the device owner.
3771     */
3772    public boolean getAutoTimeRequired() {
3773        if (!mHasFeature) {
3774            return false;
3775        }
3776        synchronized (this) {
3777            ActiveAdmin deviceOwner = getDeviceOwnerAdmin();
3778            return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
3779        }
3780    }
3781
3782    /**
3783     * The system property used to share the state of the camera. The native camera service
3784     * is expected to read this property and act accordingly. The userId should be appended
3785     * to this key.
3786     */
3787    public static final String SYSTEM_PROP_DISABLE_CAMERA_PREFIX = "sys.secpolicy.camera.off_";
3788
3789    /**
3790     * Disables all device cameras according to the specified admin.
3791     */
3792    public void setCameraDisabled(ComponentName who, boolean disabled) {
3793        if (!mHasFeature) {
3794            return;
3795        }
3796        Preconditions.checkNotNull(who, "ComponentName is null");
3797        final int userHandle = UserHandle.getCallingUserId();
3798        synchronized (this) {
3799            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3800                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
3801            if (ap.disableCamera != disabled) {
3802                ap.disableCamera = disabled;
3803                saveSettingsLocked(userHandle);
3804            }
3805            syncDeviceCapabilitiesLocked(getUserData(userHandle));
3806        }
3807    }
3808
3809    /**
3810     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
3811     * active admins.
3812     */
3813    public boolean getCameraDisabled(ComponentName who, int userHandle) {
3814        if (!mHasFeature) {
3815            return false;
3816        }
3817        synchronized (this) {
3818            if (who != null) {
3819                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3820                return (admin != null) ? admin.disableCamera : false;
3821            }
3822
3823            DevicePolicyData policy = getUserData(userHandle);
3824            // Determine whether or not the device camera is disabled for any active admins.
3825            final int N = policy.mAdminList.size();
3826            for (int i = 0; i < N; i++) {
3827                ActiveAdmin admin = policy.mAdminList.get(i);
3828                if (admin.disableCamera) {
3829                    return true;
3830                }
3831            }
3832            return false;
3833        }
3834    }
3835
3836    /**
3837     * Selectively disable keyguard features.
3838     */
3839    public void setKeyguardDisabledFeatures(ComponentName who, int which) {
3840        if (!mHasFeature) {
3841            return;
3842        }
3843        Preconditions.checkNotNull(who, "ComponentName is null");
3844        final int userHandle = UserHandle.getCallingUserId();
3845        enforceNotManagedProfile(userHandle, "disable keyguard features");
3846        synchronized (this) {
3847            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3848                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
3849            if (ap.disabledKeyguardFeatures != which) {
3850                ap.disabledKeyguardFeatures = which;
3851                saveSettingsLocked(userHandle);
3852            }
3853            syncDeviceCapabilitiesLocked(getUserData(userHandle));
3854        }
3855    }
3856
3857    /**
3858     * Gets the disabled state for features in keyguard for the given admin,
3859     * or the aggregate of all active admins if who is null.
3860     */
3861    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
3862        if (!mHasFeature) {
3863            return 0;
3864        }
3865        enforceCrossUserPermission(userHandle);
3866        synchronized (this) {
3867            if (who != null) {
3868                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3869                return (admin != null) ? admin.disabledKeyguardFeatures : 0;
3870            }
3871
3872            // Determine which keyguard features are disabled for any active admins.
3873            DevicePolicyData policy = getUserData(userHandle);
3874            final int N = policy.mAdminList.size();
3875            int which = 0;
3876            for (int i = 0; i < N; i++) {
3877                ActiveAdmin admin = policy.mAdminList.get(i);
3878                which |= admin.disabledKeyguardFeatures;
3879            }
3880            return which;
3881        }
3882    }
3883
3884    @Override
3885    public boolean setDeviceOwner(String packageName, String ownerName) {
3886        if (!mHasFeature) {
3887            return false;
3888        }
3889        if (packageName == null
3890                || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
3891            throw new IllegalArgumentException("Invalid package name " + packageName
3892                    + " for device owner");
3893        }
3894        synchronized (this) {
3895            if (!allowedToSetDeviceOwnerOnDevice()) {
3896                throw new IllegalStateException(
3897                        "Trying to set device owner but device is already provisioned.");
3898            }
3899
3900            if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3901                throw new IllegalStateException(
3902                        "Trying to set device owner but device owner is already set.");
3903            }
3904
3905            // Shutting down backup manager service permanently.
3906            long ident = Binder.clearCallingIdentity();
3907            try {
3908                IBackupManager ibm = IBackupManager.Stub.asInterface(
3909                        ServiceManager.getService(Context.BACKUP_SERVICE));
3910                ibm.setBackupServiceActive(UserHandle.USER_OWNER, false);
3911            } catch (RemoteException e) {
3912                throw new IllegalStateException("Failed deactivating backup service.", e);
3913            } finally {
3914                Binder.restoreCallingIdentity(ident);
3915            }
3916
3917            if (mDeviceOwner == null) {
3918                // Device owner is not set and does not exist, set it.
3919                mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
3920                mDeviceOwner.writeOwnerFile();
3921                return true;
3922            } else {
3923                // Device owner is not set but a profile owner exists, update Device owner state.
3924                mDeviceOwner.setDeviceOwner(packageName, ownerName);
3925                mDeviceOwner.writeOwnerFile();
3926                return true;
3927            }
3928        }
3929    }
3930
3931    @Override
3932    public boolean isDeviceOwner(String packageName) {
3933        if (!mHasFeature) {
3934            return false;
3935        }
3936        synchronized (this) {
3937            return mDeviceOwner != null
3938                    && mDeviceOwner.hasDeviceOwner()
3939                    && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
3940        }
3941    }
3942
3943    @Override
3944    public String getDeviceOwner() {
3945        if (!mHasFeature) {
3946            return null;
3947        }
3948        synchronized (this) {
3949            if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3950                return mDeviceOwner.getDeviceOwnerPackageName();
3951            }
3952        }
3953        return null;
3954    }
3955
3956    @Override
3957    public String getDeviceOwnerName() {
3958        if (!mHasFeature) {
3959            return null;
3960        }
3961        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3962        synchronized (this) {
3963            if (mDeviceOwner != null) {
3964                return mDeviceOwner.getDeviceOwnerName();
3965            }
3966        }
3967        return null;
3968    }
3969
3970    // Returns the active device owner or null if there is no device owner.
3971    private ActiveAdmin getDeviceOwnerAdmin() {
3972        String deviceOwnerPackageName = getDeviceOwner();
3973        if (deviceOwnerPackageName == null) {
3974            return null;
3975        }
3976
3977        DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
3978        final int n = policy.mAdminList.size();
3979        for (int i = 0; i < n; i++) {
3980            ActiveAdmin admin = policy.mAdminList.get(i);
3981            if (deviceOwnerPackageName.equals(admin.info.getPackageName())) {
3982                return admin;
3983            }
3984        }
3985        return null;
3986    }
3987
3988    @Override
3989    public void clearDeviceOwner(String packageName) {
3990        Preconditions.checkNotNull(packageName, "packageName is null");
3991        try {
3992            int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
3993            if (uid != Binder.getCallingUid()) {
3994                throw new SecurityException("Invalid packageName");
3995            }
3996        } catch (NameNotFoundException e) {
3997            throw new SecurityException(e);
3998        }
3999        if (!isDeviceOwner(packageName)) {
4000            throw new SecurityException("clearDeviceOwner can only be called by the device owner");
4001        }
4002        synchronized (this) {
4003            long ident = Binder.clearCallingIdentity();
4004            try {
4005                clearUserRestrictions(new UserHandle(UserHandle.USER_OWNER));
4006                if (mDeviceOwner != null) {
4007                    mDeviceOwner.clearDeviceOwner();
4008                    mDeviceOwner.writeOwnerFile();
4009                }
4010            } finally {
4011                Binder.restoreCallingIdentity(ident);
4012            }
4013        }
4014    }
4015
4016    @Override
4017    public boolean setDeviceInitializer(ComponentName who, ComponentName initializer,
4018            String ownerName) {
4019        if (!mHasFeature) {
4020            return false;
4021        }
4022        if (initializer == null || !DeviceOwner.isInstalled(
4023                initializer.getPackageName(), mContext.getPackageManager())) {
4024            throw new IllegalArgumentException("Invalid component name " + initializer
4025                    + " for device initializer");
4026        }
4027        synchronized (this) {
4028            enforceCanSetDeviceInitializer(who);
4029
4030            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4031                throw new IllegalStateException(
4032                        "Trying to set device initializer but device initializer is already set.");
4033            }
4034
4035            if (mDeviceOwner == null) {
4036                // Device owner state does not exist, create it.
4037                mDeviceOwner = DeviceOwner.createWithDeviceInitializer(
4038                        initializer, ownerName);
4039                mDeviceOwner.writeOwnerFile();
4040                return true;
4041            } else {
4042                // Device owner already exists, update it.
4043                mDeviceOwner.setDeviceInitializer(initializer, ownerName);
4044                mDeviceOwner.writeOwnerFile();
4045                return true;
4046            }
4047        }
4048    }
4049
4050    private void enforceCanSetDeviceInitializer(ComponentName who) {
4051        if (who == null) {
4052            mContext.enforceCallingOrSelfPermission(
4053                    android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4054            if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4055                throw new IllegalStateException(
4056                        "Trying to set device initializer but device is already provisioned.");
4057            }
4058        } else {
4059            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4060        }
4061    }
4062
4063    @Override
4064    public boolean isDeviceInitializer(String packageName) {
4065        if (!mHasFeature) {
4066            return false;
4067        }
4068        synchronized (this) {
4069            return mDeviceOwner != null
4070                    && mDeviceOwner.hasDeviceInitializer()
4071                    && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
4072        }
4073    }
4074
4075    @Override
4076    public String getDeviceInitializer() {
4077        if (!mHasFeature) {
4078            return null;
4079        }
4080        synchronized (this) {
4081            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4082                return mDeviceOwner.getDeviceInitializerPackageName();
4083            }
4084        }
4085        return null;
4086    }
4087
4088    @Override
4089    public ComponentName getDeviceInitializerComponent() {
4090        if (!mHasFeature) {
4091            return null;
4092        }
4093        synchronized (this) {
4094            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4095                return mDeviceOwner.getDeviceInitializerComponent();
4096            }
4097        }
4098        return null;
4099    }
4100
4101    @Override
4102    public void clearDeviceInitializer(ComponentName who) {
4103        if (!mHasFeature) {
4104            return;
4105        }
4106        Preconditions.checkNotNull(who, "ComponentName is null");
4107
4108        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
4109
4110        if (admin.getUid() != Binder.getCallingUid()) {
4111            throw new SecurityException("Admin " + who + " is not owned by uid "
4112                    + Binder.getCallingUid());
4113        }
4114
4115        if (!isDeviceInitializer(admin.info.getPackageName())
4116                && !isDeviceOwner(admin.info.getPackageName())) {
4117            throw new SecurityException(
4118                    "clearDeviceInitializer can only be called by the device initializer/owner");
4119        }
4120        synchronized (this) {
4121            long ident = Binder.clearCallingIdentity();
4122            try {
4123                if (mDeviceOwner != null) {
4124                    mDeviceOwner.clearDeviceInitializer();
4125                    mDeviceOwner.writeOwnerFile();
4126                }
4127            } finally {
4128                Binder.restoreCallingIdentity(ident);
4129            }
4130        }
4131    }
4132
4133    @Override
4134    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
4135        if (!mHasFeature) {
4136            return false;
4137        }
4138        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4139
4140        UserInfo info = mUserManager.getUserInfo(userHandle);
4141        if (info == null) {
4142            // User doesn't exist.
4143            throw new IllegalArgumentException(
4144                    "Attempted to set profile owner for invalid userId: " + userHandle);
4145        }
4146        if (info.isGuest()) {
4147            throw new IllegalStateException("Cannot set a profile owner on a guest");
4148        }
4149
4150        if (who == null
4151                || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
4152            throw new IllegalArgumentException("Component " + who
4153                    + " not installed for userId:" + userHandle);
4154        }
4155        synchronized (this) {
4156            // Only SYSTEM_UID can override the userSetupComplete
4157            if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID
4158                    && hasUserSetupCompleted(userHandle)) {
4159                throw new IllegalStateException(
4160                        "Trying to set profile owner but user is already set-up.");
4161            }
4162
4163            if (mDeviceOwner == null) {
4164                // Device owner state does not exist, create it.
4165                mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
4166                        userHandle);
4167                mDeviceOwner.writeOwnerFile();
4168                return true;
4169            } else {
4170                // Device owner already exists, update it.
4171                mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
4172                mDeviceOwner.writeOwnerFile();
4173                return true;
4174            }
4175        }
4176    }
4177
4178    @Override
4179    public void clearProfileOwner(ComponentName who) {
4180        if (!mHasFeature) {
4181            return;
4182        }
4183        UserHandle callingUser = Binder.getCallingUserHandle();
4184        // Check if this is the profile owner who is calling
4185        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4186        synchronized (this) {
4187            long ident = Binder.clearCallingIdentity();
4188            try {
4189                clearUserRestrictions(callingUser);
4190                if (mDeviceOwner != null) {
4191                    mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
4192                    mDeviceOwner.writeOwnerFile();
4193                }
4194            } finally {
4195                Binder.restoreCallingIdentity(ident);
4196            }
4197        }
4198    }
4199
4200    private void clearUserRestrictions(UserHandle userHandle) {
4201        AudioManager audioManager =
4202                (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
4203        Bundle userRestrictions = mUserManager.getUserRestrictions();
4204        mUserManager.setUserRestrictions(new Bundle(), userHandle);
4205        if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
4206            audioManager.setMasterMute(false, 0);
4207        }
4208        if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
4209            audioManager.setMicrophoneMute(false);
4210        }
4211    }
4212
4213    @Override
4214    public boolean hasUserSetupCompleted() {
4215        return hasUserSetupCompleted(UserHandle.getCallingUserId());
4216    }
4217
4218    private boolean hasUserSetupCompleted(int userHandle) {
4219        if (!mHasFeature) {
4220            return true;
4221        }
4222        DevicePolicyData policy = getUserData(userHandle);
4223        // If policy is null, return true, else check if the setup has completed.
4224        return policy == null || policy.mUserSetupComplete;
4225    }
4226
4227    @Override
4228    public boolean setUserEnabled(ComponentName who) {
4229        if (!mHasFeature) {
4230            return false;
4231        }
4232        synchronized (this) {
4233            if (who == null) {
4234                throw new NullPointerException("ComponentName is null");
4235            }
4236            int userId = UserHandle.getCallingUserId();
4237
4238            ActiveAdmin activeAdmin =
4239                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4240            if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
4241                throw new SecurityException(
4242                        "This method can only be called by device initializers");
4243            }
4244
4245            long id = Binder.clearCallingIdentity();
4246            try {
4247                if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
4248                    IPackageManager ipm = AppGlobals.getPackageManager();
4249                    ipm.setComponentEnabledSetting(who,
4250                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
4251                            PackageManager.DONT_KILL_APP, userId);
4252
4253                    removeActiveAdmin(who, userId);
4254                }
4255
4256                if (userId == UserHandle.USER_OWNER) {
4257                    Settings.Global.putInt(mContext.getContentResolver(),
4258                            Settings.Global.DEVICE_PROVISIONED, 1);
4259                }
4260                Settings.Secure.putIntForUser(mContext.getContentResolver(),
4261                        Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
4262            } catch (RemoteException e) {
4263                Log.i(LOG_TAG, "Can't talk to package manager", e);
4264                return false;
4265            } finally {
4266                restoreCallingIdentity(id);
4267            }
4268            return true;
4269        }
4270    }
4271
4272    @Override
4273    public void setProfileEnabled(ComponentName who) {
4274        if (!mHasFeature) {
4275            return;
4276        }
4277        Preconditions.checkNotNull(who, "ComponentName is null");
4278        final int userHandle = UserHandle.getCallingUserId();
4279        synchronized (this) {
4280            // Check if this is the profile owner who is calling
4281            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4282            int userId = UserHandle.getCallingUserId();
4283
4284            long id = Binder.clearCallingIdentity();
4285            try {
4286                mUserManager.setUserEnabled(userId);
4287                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
4288                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
4289                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
4290                        Intent.FLAG_RECEIVER_FOREGROUND);
4291                // TODO This should send to parent of profile (which is always owner at the moment).
4292                mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4293            } finally {
4294                restoreCallingIdentity(id);
4295            }
4296        }
4297    }
4298
4299    @Override
4300    public void setProfileName(ComponentName who, String profileName) {
4301        Preconditions.checkNotNull(who, "ComponentName is null");
4302        int userId = UserHandle.getCallingUserId();
4303        // Check if this is the profile owner (includes device owner).
4304        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4305
4306        long id = Binder.clearCallingIdentity();
4307        try {
4308            mUserManager.setUserName(userId, profileName);
4309        } finally {
4310            restoreCallingIdentity(id);
4311        }
4312    }
4313
4314    @Override
4315    public ComponentName getProfileOwner(int userHandle) {
4316        if (!mHasFeature) {
4317            return null;
4318        }
4319
4320        synchronized (this) {
4321            if (mDeviceOwner != null) {
4322                return mDeviceOwner.getProfileOwnerComponent(userHandle);
4323            }
4324        }
4325        return null;
4326    }
4327
4328    // Returns the active profile owner for this user or null if the current user has no
4329    // profile owner.
4330    private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4331        ComponentName profileOwner =
4332                mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4333        if (profileOwner == null) {
4334            return null;
4335        }
4336
4337        DevicePolicyData policy = getUserData(userHandle);
4338        final int n = policy.mAdminList.size();
4339        for (int i = 0; i < n; i++) {
4340            ActiveAdmin admin = policy.mAdminList.get(i);
4341            if (profileOwner.equals(admin.info.getComponent())) {
4342                return admin;
4343            }
4344        }
4345        return null;
4346    }
4347
4348    @Override
4349    public String getProfileOwnerName(int userHandle) {
4350        if (!mHasFeature) {
4351            return null;
4352        }
4353        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4354
4355        synchronized (this) {
4356            if (mDeviceOwner != null) {
4357                return mDeviceOwner.getProfileOwnerName(userHandle);
4358            }
4359        }
4360        return null;
4361    }
4362
4363    /**
4364     * Device owner can only be set on an unprovisioned device. However, if initiated via "adb",
4365     * we also allow it if no accounts or additional users are present on the device.
4366     */
4367    private boolean allowedToSetDeviceOwnerOnDevice() {
4368        if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4369            return true;
4370        }
4371
4372        int callingId = Binder.getCallingUid();
4373        return (callingId == Process.SHELL_UID || callingId == Process.ROOT_UID)
4374                && mUserManager.getUserCount() == 1
4375                && AccountManager.get(mContext).getAccounts().length == 0;
4376    }
4377
4378    private void enforceCrossUserPermission(int userHandle) {
4379        if (userHandle < 0) {
4380            throw new IllegalArgumentException("Invalid userId " + userHandle);
4381        }
4382        final int callingUid = Binder.getCallingUid();
4383        if (userHandle == UserHandle.getUserId(callingUid)) return;
4384        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4385            mContext.enforceCallingOrSelfPermission(
4386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4387                    + " INTERACT_ACROSS_USERS_FULL permission");
4388        }
4389    }
4390
4391    private void enforceSystemProcess(String message) {
4392        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4393            throw new SecurityException(message);
4394        }
4395    }
4396
4397    private void enforceNotManagedProfile(int userHandle, String message) {
4398        if(isManagedProfile(userHandle)) {
4399            throw new SecurityException("You can not " + message + " for a managed profile. ");
4400        }
4401    }
4402
4403    private UserInfo getProfileParent(int userHandle) {
4404        long ident = Binder.clearCallingIdentity();
4405        try {
4406            return mUserManager.getProfileParent(userHandle);
4407        } finally {
4408            Binder.restoreCallingIdentity(ident);
4409        }
4410    }
4411
4412    private boolean isManagedProfile(int userHandle) {
4413        long ident = Binder.clearCallingIdentity();
4414        try {
4415            return mUserManager.getUserInfo(userHandle).isManagedProfile();
4416        } finally {
4417            Binder.restoreCallingIdentity(ident);
4418        }
4419    }
4420
4421    private void enableIfNecessary(String packageName, int userId) {
4422        try {
4423            IPackageManager ipm = AppGlobals.getPackageManager();
4424            ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4425                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4426                    userId);
4427            if (ai.enabledSetting
4428                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4429                ipm.setApplicationEnabledSetting(packageName,
4430                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4431                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4432            }
4433        } catch (RemoteException e) {
4434        }
4435    }
4436
4437    @Override
4438    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4439        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4440                != PackageManager.PERMISSION_GRANTED) {
4441
4442            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4443                    + Binder.getCallingPid()
4444                    + ", uid=" + Binder.getCallingUid());
4445            return;
4446        }
4447
4448        final Printer p = new PrintWriterPrinter(pw);
4449
4450        synchronized (this) {
4451            p.println("Current Device Policy Manager state:");
4452            if (mDeviceOwner != null) {
4453                mDeviceOwner.dump("  ", pw);
4454            }
4455            int userCount = mUserData.size();
4456            for (int u = 0; u < userCount; u++) {
4457                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4458                p.println("  Enabled Device Admins (User " + policy.mUserHandle + "):");
4459                final int N = policy.mAdminList.size();
4460                for (int i=0; i<N; i++) {
4461                    ActiveAdmin ap = policy.mAdminList.get(i);
4462                    if (ap != null) {
4463                        pw.print("  "); pw.print(ap.info.getComponent().flattenToShortString());
4464                                pw.println(":");
4465                        ap.dump("    ", pw);
4466                    }
4467                }
4468                if (!policy.mRemovingAdmins.isEmpty()) {
4469                    p.println("  Removing Device Admins (User " + policy.mUserHandle + "): "
4470                            + policy.mRemovingAdmins);
4471                }
4472
4473                pw.println(" ");
4474                pw.print("  mPasswordOwner="); pw.println(policy.mPasswordOwner);
4475            }
4476        }
4477    }
4478
4479    @Override
4480    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4481            ComponentName activity) {
4482        Preconditions.checkNotNull(who, "ComponentName is null");
4483        final int userHandle = UserHandle.getCallingUserId();
4484        synchronized (this) {
4485            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4486
4487            IPackageManager pm = AppGlobals.getPackageManager();
4488            long id = Binder.clearCallingIdentity();
4489            try {
4490                pm.addPersistentPreferredActivity(filter, activity, userHandle);
4491            } catch (RemoteException re) {
4492                // Shouldn't happen
4493            } finally {
4494                restoreCallingIdentity(id);
4495            }
4496        }
4497    }
4498
4499    @Override
4500    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4501        Preconditions.checkNotNull(who, "ComponentName is null");
4502        final int userHandle = UserHandle.getCallingUserId();
4503        synchronized (this) {
4504            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4505
4506            IPackageManager pm = AppGlobals.getPackageManager();
4507            long id = Binder.clearCallingIdentity();
4508            try {
4509                pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4510            } catch (RemoteException re) {
4511                // Shouldn't happen
4512            } finally {
4513                restoreCallingIdentity(id);
4514            }
4515        }
4516    }
4517
4518    @Override
4519    public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4520        Preconditions.checkNotNull(who, "ComponentName is null");
4521        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4522        synchronized (this) {
4523            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4524
4525            long id = Binder.clearCallingIdentity();
4526            try {
4527                mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4528            } finally {
4529                restoreCallingIdentity(id);
4530            }
4531        }
4532    }
4533
4534    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4535            PersistableBundle args) {
4536        if (!mHasFeature) {
4537            return;
4538        }
4539        Preconditions.checkNotNull(admin, "admin is null");
4540        Preconditions.checkNotNull(agent, "agent is null");
4541        final int userHandle = UserHandle.getCallingUserId();
4542        enforceNotManagedProfile(userHandle, "set trust agent configuration");
4543        synchronized (this) {
4544            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4545                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4546            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4547            saveSettingsLocked(userHandle);
4548            syncDeviceCapabilitiesLocked(getUserData(userHandle));
4549        }
4550    }
4551
4552    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4553            ComponentName agent, int userHandle) {
4554        if (!mHasFeature) {
4555            return null;
4556        }
4557        Preconditions.checkNotNull(agent, "agent null");
4558        enforceCrossUserPermission(userHandle);
4559
4560        synchronized (this) {
4561            final String componentName = agent.flattenToString();
4562            if (admin != null) {
4563                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4564                if (ap == null) return null;
4565                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4566                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4567                List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4568                result.add(trustAgentInfo.options);
4569                return result;
4570            }
4571
4572            // Return strictest policy for this user and profiles that are visible from this user.
4573            final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4574            List<PersistableBundle> result = null;
4575
4576            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4577            // of the options. If any admin doesn't have options, discard options for the rest
4578            // and return null.
4579            boolean allAdminsHaveOptions = true;
4580            for (UserInfo userInfo : profiles) {
4581                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4582                final int N = policy.mAdminList.size();
4583                for (int i=0; i < N; i++) {
4584                    final ActiveAdmin active = policy.mAdminList.get(i);
4585                    final boolean disablesTrust = (active.disabledKeyguardFeatures
4586                            & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4587                    final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4588                    if (info != null && info.options != null && !info.options.isEmpty()) {
4589                        if (disablesTrust) {
4590                            if (result == null) {
4591                                result = new ArrayList<PersistableBundle>();
4592                            }
4593                            result.add(info.options);
4594                        } else {
4595                            Log.w(LOG_TAG, "Ignoring admin " + active.info
4596                                    + " because it has trust options but doesn't declare "
4597                                    + "KEYGUARD_DISABLE_TRUST_AGENTS");
4598                        }
4599                    } else if (disablesTrust) {
4600                        allAdminsHaveOptions = false;
4601                        break;
4602                    }
4603                }
4604            }
4605            return allAdminsHaveOptions ? result : null;
4606        }
4607    }
4608
4609    @Override
4610    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4611        Preconditions.checkNotNull(who, "ComponentName is null");
4612        synchronized (this) {
4613            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4614
4615            int userHandle = UserHandle.getCallingUserId();
4616            DevicePolicyData userData = getUserData(userHandle);
4617            userData.mRestrictionsProvider = permissionProvider;
4618            saveSettingsLocked(userHandle);
4619        }
4620    }
4621
4622    @Override
4623    public ComponentName getRestrictionsProvider(int userHandle) {
4624        synchronized (this) {
4625            if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4626                throw new SecurityException("Only the system can query the permission provider");
4627            }
4628            DevicePolicyData userData = getUserData(userHandle);
4629            return userData != null ? userData.mRestrictionsProvider : null;
4630        }
4631    }
4632
4633    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4634        Preconditions.checkNotNull(who, "ComponentName is null");
4635        int callingUserId = UserHandle.getCallingUserId();
4636        synchronized (this) {
4637            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4638
4639            IPackageManager pm = AppGlobals.getPackageManager();
4640            long id = Binder.clearCallingIdentity();
4641            try {
4642                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4643                    pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
4644                            UserHandle.USER_OWNER, 0);
4645                }
4646                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4647                    pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4648                            UserHandle.USER_OWNER, callingUserId, 0);
4649                }
4650            } catch (RemoteException re) {
4651                // Shouldn't happen
4652            } finally {
4653                restoreCallingIdentity(id);
4654            }
4655        }
4656    }
4657
4658    public void clearCrossProfileIntentFilters(ComponentName who) {
4659        Preconditions.checkNotNull(who, "ComponentName is null");
4660        int callingUserId = UserHandle.getCallingUserId();
4661        synchronized (this) {
4662            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4663            IPackageManager pm = AppGlobals.getPackageManager();
4664            long id = Binder.clearCallingIdentity();
4665            try {
4666                // Removing those that go from the managed profile to the primary user.
4667                pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
4668                // And those that go from the primary user to the managed profile.
4669                // If we want to support multiple managed profiles, we will have to only remove
4670                // those that have callingUserId as their target.
4671                pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
4672            } catch (RemoteException re) {
4673                // Shouldn't happen
4674            } finally {
4675                restoreCallingIdentity(id);
4676            }
4677        }
4678    }
4679
4680    /**
4681     * @return true if all packages in enabledPackages are either in the list
4682     * permittedList or are a system app.
4683     */
4684    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
4685            List<String> permittedList) {
4686        int userIdToCheck = UserHandle.getCallingUserId();
4687        long id = Binder.clearCallingIdentity();
4688        try {
4689            // If we have an enabled packages list for a managed profile the packages
4690            // we should check are installed for the parent user.
4691            UserInfo user = mUserManager.getUserInfo(userIdToCheck);
4692            if (user.isManagedProfile()) {
4693                userIdToCheck = user.profileGroupId;
4694            }
4695
4696            IPackageManager pm = AppGlobals.getPackageManager();
4697            for (String enabledPackage : enabledPackages) {
4698                boolean systemService = false;
4699                try {
4700                    ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
4701                            PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
4702                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
4703                } catch (RemoteException e) {
4704                    Log.i(LOG_TAG, "Can't talk to package managed", e);
4705                }
4706                if (!systemService && !permittedList.contains(enabledPackage)) {
4707                    return false;
4708                }
4709            }
4710        } finally {
4711            restoreCallingIdentity(id);
4712        }
4713        return true;
4714    }
4715
4716    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
4717        // Not using AccessibilityManager.getInstance because that guesses
4718        // at the user you require based on callingUid and caches for a given
4719        // process.
4720        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
4721        IAccessibilityManager service = iBinder == null
4722                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
4723        return new AccessibilityManager(mContext, service, userId);
4724    }
4725
4726    @Override
4727    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
4728        if (!mHasFeature) {
4729            return false;
4730        }
4731        Preconditions.checkNotNull(who, "ComponentName is null");
4732
4733        if (packageList != null) {
4734            int userId = UserHandle.getCallingUserId();
4735            List<AccessibilityServiceInfo> enabledServices = null;
4736            long id = Binder.clearCallingIdentity();
4737            try {
4738                UserInfo user = mUserManager.getUserInfo(userId);
4739                if (user.isManagedProfile()) {
4740                    userId = user.profileGroupId;
4741                }
4742                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
4743                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
4744                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
4745            } finally {
4746                restoreCallingIdentity(id);
4747            }
4748
4749            if (enabledServices != null) {
4750                List<String> enabledPackages = new ArrayList<String>();
4751                for (AccessibilityServiceInfo service : enabledServices) {
4752                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
4753                }
4754                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4755                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
4756                            + "because it contains already enabled accesibility services.");
4757                    return false;
4758                }
4759            }
4760        }
4761
4762        synchronized (this) {
4763            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4764                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4765            admin.permittedAccessiblityServices = packageList;
4766            saveSettingsLocked(UserHandle.getCallingUserId());
4767        }
4768        return true;
4769    }
4770
4771    @Override
4772    public List getPermittedAccessibilityServices(ComponentName who) {
4773        if (!mHasFeature) {
4774            return null;
4775        }
4776        Preconditions.checkNotNull(who, "ComponentName is null");
4777
4778        synchronized (this) {
4779            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4780                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4781            return admin.permittedAccessiblityServices;
4782        }
4783    }
4784
4785    @Override
4786    public List getPermittedAccessibilityServicesForUser(int userId) {
4787        if (!mHasFeature) {
4788            return null;
4789        }
4790        synchronized (this) {
4791            List<String> result = null;
4792            // If we have multiple profiles we return the intersection of the
4793            // permitted lists. This can happen in cases where we have a device
4794            // and profile owner.
4795            List<UserInfo> profiles = mUserManager.getProfiles(userId);
4796            final int PROFILES_SIZE = profiles.size();
4797            for (int i = 0; i < PROFILES_SIZE; ++i) {
4798                // Just loop though all admins, only device or profiles
4799                // owners can have permitted lists set.
4800                DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4801                final int N = policy.mAdminList.size();
4802                for (int j = 0; j < N; j++) {
4803                    ActiveAdmin admin = policy.mAdminList.get(j);
4804                    List<String> fromAdmin = admin.permittedAccessiblityServices;
4805                    if (fromAdmin != null) {
4806                        if (result == null) {
4807                            result = new ArrayList<String>(fromAdmin);
4808                        } else {
4809                            result.retainAll(fromAdmin);
4810                        }
4811                    }
4812                }
4813            }
4814
4815            // If we have a permitted list add all system accessibility services.
4816            if (result != null) {
4817                long id = Binder.clearCallingIdentity();
4818                try {
4819                    UserInfo user = mUserManager.getUserInfo(userId);
4820                    if (user.isManagedProfile()) {
4821                        userId = user.profileGroupId;
4822                    }
4823                    AccessibilityManager accessibilityManager =
4824                            getAccessibilityManagerForUser(userId);
4825                    List<AccessibilityServiceInfo> installedServices =
4826                            accessibilityManager.getInstalledAccessibilityServiceList();
4827
4828                    IPackageManager pm = AppGlobals.getPackageManager();
4829                    if (installedServices != null) {
4830                        for (AccessibilityServiceInfo service : installedServices) {
4831                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
4832                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
4833                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4834                                result.add(serviceInfo.packageName);
4835                            }
4836                        }
4837                    }
4838                } finally {
4839                    restoreCallingIdentity(id);
4840                }
4841            }
4842
4843            return result;
4844        }
4845    }
4846
4847    private boolean checkCallerIsCurrentUserOrProfile() {
4848        int callingUserId = UserHandle.getCallingUserId();
4849        long token = Binder.clearCallingIdentity();
4850        try {
4851            UserInfo currentUser;
4852            UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
4853            try {
4854                currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4855            } catch (RemoteException e) {
4856                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
4857                return false;
4858            }
4859
4860            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
4861                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
4862                        + "of a user that isn't the foreground user.");
4863                return false;
4864            }
4865            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
4866                Slog.e(LOG_TAG, "Cannot set permitted input methods "
4867                        + "of a user that isn't the foreground user.");
4868                return false;
4869            }
4870        } finally {
4871            Binder.restoreCallingIdentity(token);
4872        }
4873        return true;
4874    }
4875
4876    @Override
4877    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
4878        if (!mHasFeature) {
4879            return false;
4880        }
4881        Preconditions.checkNotNull(who, "ComponentName is null");
4882
4883        // TODO When InputMethodManager supports per user calls remove
4884        //      this restriction.
4885        if (!checkCallerIsCurrentUserOrProfile()) {
4886            return false;
4887        }
4888
4889        if (packageList != null) {
4890            // InputMethodManager fetches input methods for current user.
4891            // So this can only be set when calling user is the current user
4892            // or parent is current user in case of managed profiles.
4893            InputMethodManager inputMethodManager = (InputMethodManager) mContext
4894                    .getSystemService(Context.INPUT_METHOD_SERVICE);
4895            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
4896
4897            if (enabledImes != null) {
4898                List<String> enabledPackages = new ArrayList<String>();
4899                for (InputMethodInfo ime : enabledImes) {
4900                    enabledPackages.add(ime.getPackageName());
4901                }
4902                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
4903                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
4904                            + "because it contains already enabled input method.");
4905                    return false;
4906                }
4907            }
4908        }
4909
4910        synchronized (this) {
4911            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4912                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4913            admin.permittedInputMethods = packageList;
4914            saveSettingsLocked(UserHandle.getCallingUserId());
4915        }
4916        return true;
4917    }
4918
4919    @Override
4920    public List getPermittedInputMethods(ComponentName who) {
4921        if (!mHasFeature) {
4922            return null;
4923        }
4924        Preconditions.checkNotNull(who, "ComponentName is null");
4925
4926        synchronized (this) {
4927            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
4928                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4929            return admin.permittedInputMethods;
4930        }
4931    }
4932
4933    @Override
4934    public List getPermittedInputMethodsForCurrentUser() {
4935        UserInfo currentUser;
4936        try {
4937            currentUser = ActivityManagerNative.getDefault().getCurrentUser();
4938        } catch (RemoteException e) {
4939            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
4940            // Activity managed is dead, just allow all IMEs
4941            return null;
4942        }
4943
4944        int userId = currentUser.id;
4945        synchronized (this) {
4946            List<String> result = null;
4947            // If we have multiple profiles we return the intersection of the
4948            // permitted lists. This can happen in cases where we have a device
4949            // and profile owner.
4950            List<UserInfo> profiles = mUserManager.getProfiles(userId);
4951            final int PROFILES_SIZE = profiles.size();
4952            for (int i = 0; i < PROFILES_SIZE; ++i) {
4953                // Just loop though all admins, only device or profiles
4954                // owners can have permitted lists set.
4955                DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
4956                final int N = policy.mAdminList.size();
4957                for (int j = 0; j < N; j++) {
4958                    ActiveAdmin admin = policy.mAdminList.get(j);
4959                    List<String> fromAdmin = admin.permittedInputMethods;
4960                    if (fromAdmin != null) {
4961                        if (result == null) {
4962                            result = new ArrayList<String>(fromAdmin);
4963                        } else {
4964                            result.retainAll(fromAdmin);
4965                        }
4966                    }
4967                }
4968            }
4969
4970            // If we have a permitted list add all system input methods.
4971            if (result != null) {
4972                InputMethodManager inputMethodManager = (InputMethodManager) mContext
4973                        .getSystemService(Context.INPUT_METHOD_SERVICE);
4974                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
4975                long id = Binder.clearCallingIdentity();
4976                try {
4977                    IPackageManager pm = AppGlobals.getPackageManager();
4978                    if (imes != null) {
4979                        for (InputMethodInfo ime : imes) {
4980                            ServiceInfo serviceInfo = ime.getServiceInfo();
4981                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
4982                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4983                                result.add(serviceInfo.packageName);
4984                            }
4985                        }
4986                    }
4987                } finally {
4988                    restoreCallingIdentity(id);
4989                }
4990            }
4991            return result;
4992        }
4993    }
4994
4995    @Override
4996    public UserHandle createUser(ComponentName who, String name) {
4997        Preconditions.checkNotNull(who, "ComponentName is null");
4998        synchronized (this) {
4999            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5000
5001            long id = Binder.clearCallingIdentity();
5002            try {
5003                UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
5004                if (userInfo != null) {
5005                    return userInfo.getUserHandle();
5006                }
5007                return null;
5008            } finally {
5009                restoreCallingIdentity(id);
5010            }
5011        }
5012    }
5013
5014    @Override
5015    public UserHandle createAndInitializeUser(ComponentName who, String name,
5016            String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
5017        UserHandle user = createUser(who, name);
5018        if (user == null) {
5019            return null;
5020        }
5021        long id = Binder.clearCallingIdentity();
5022        try {
5023            String profileOwnerPkg = profileOwnerComponent.getPackageName();
5024            final IPackageManager ipm = AppGlobals.getPackageManager();
5025            IActivityManager activityManager = ActivityManagerNative.getDefault();
5026
5027            try {
5028                // Install the profile owner if not present.
5029                if (!ipm.isPackageAvailable(profileOwnerPkg, user.getIdentifier())) {
5030                    ipm.installExistingPackageAsUser(profileOwnerPkg, user.getIdentifier());
5031                }
5032
5033                // Start user in background.
5034                activityManager.startUserInBackground(user.getIdentifier());
5035            } catch (RemoteException e) {
5036                Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
5037            }
5038
5039            setActiveAdmin(profileOwnerComponent, true, user.getIdentifier(), adminExtras);
5040            setProfileOwner(profileOwnerComponent, ownerName, user.getIdentifier());
5041            return user;
5042        } finally {
5043            restoreCallingIdentity(id);
5044        }
5045    }
5046
5047    @Override
5048    public boolean removeUser(ComponentName who, UserHandle userHandle) {
5049        Preconditions.checkNotNull(who, "ComponentName is null");
5050        synchronized (this) {
5051            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5052
5053            long id = Binder.clearCallingIdentity();
5054            try {
5055                return mUserManager.removeUser(userHandle.getIdentifier());
5056            } finally {
5057                restoreCallingIdentity(id);
5058            }
5059        }
5060    }
5061
5062    @Override
5063    public boolean switchUser(ComponentName who, UserHandle userHandle) {
5064        Preconditions.checkNotNull(who, "ComponentName is null");
5065        synchronized (this) {
5066            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5067
5068            long id = Binder.clearCallingIdentity();
5069            try {
5070                int userId = UserHandle.USER_OWNER;
5071                if (userHandle != null) {
5072                    userId = userHandle.getIdentifier();
5073                }
5074                return ActivityManagerNative.getDefault().switchUser(userId);
5075            } catch (RemoteException e) {
5076                Log.e(LOG_TAG, "Couldn't switch user", e);
5077                return false;
5078            } finally {
5079                restoreCallingIdentity(id);
5080            }
5081        }
5082    }
5083
5084    @Override
5085    public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
5086        Preconditions.checkNotNull(who, "ComponentName is null");
5087        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5088
5089        synchronized (this) {
5090            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5091
5092            long id = Binder.clearCallingIdentity();
5093            try {
5094                Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
5095                // if no restrictions were saved, mUserManager.getApplicationRestrictions
5096                // returns null, but DPM method should return an empty Bundle as per JavaDoc
5097                return bundle != null ? bundle : Bundle.EMPTY;
5098            } finally {
5099                restoreCallingIdentity(id);
5100            }
5101        }
5102    }
5103
5104    @Override
5105    public void setUserRestriction(ComponentName who, String key, boolean enabled) {
5106        Preconditions.checkNotNull(who, "ComponentName is null");
5107        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
5108        final int userHandle = user.getIdentifier();
5109        synchronized (this) {
5110            ActiveAdmin activeAdmin =
5111                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5112            boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
5113            if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
5114                    && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
5115                throw new SecurityException("Profile owners cannot set user restriction " + key);
5116            }
5117            if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
5118                throw new SecurityException("User restriction " + key + " cannot be changed");
5119            }
5120            boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
5121
5122            IAudioService iAudioService = null;
5123            if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
5124                    || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5125                iAudioService = IAudioService.Stub.asInterface(
5126                        ServiceManager.getService(Context.AUDIO_SERVICE));
5127            }
5128
5129            if (enabled && !alreadyRestricted) {
5130                try {
5131                    if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5132                        iAudioService.setMicrophoneMute(true, who.getPackageName());
5133                    } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5134                        iAudioService.setMasterMute(true, 0, who.getPackageName());
5135                    }
5136                } catch (RemoteException re) {
5137                    Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5138                }
5139            }
5140            long id = Binder.clearCallingIdentity();
5141            try {
5142                if (enabled && !alreadyRestricted) {
5143                    if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
5144                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5145                                Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
5146                                userHandle);
5147                    } else if (UserManager.DISALLOW_USB_FILE_TRANSFER.equals(key)) {
5148                        UsbManager manager =
5149                                (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
5150                        manager.setCurrentFunction("none", false);
5151                    } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5152                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5153                                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
5154                                userHandle);
5155                        Settings.Secure.putStringForUser(mContext.getContentResolver(),
5156                                Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
5157                                userHandle);
5158                    } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
5159                        // Only disable adb if changing for primary user, since it is global
5160                        if (userHandle == UserHandle.USER_OWNER) {
5161                            Settings.Global.putStringForUser(mContext.getContentResolver(),
5162                                    Settings.Global.ADB_ENABLED, "0", userHandle);
5163                        }
5164                    } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
5165                        Settings.Global.putStringForUser(mContext.getContentResolver(),
5166                                Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
5167                                userHandle);
5168                        Settings.Global.putStringForUser(mContext.getContentResolver(),
5169                                Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
5170                                userHandle);
5171                    } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
5172                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5173                                Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
5174                                userHandle);
5175                    }
5176                }
5177                mUserManager.setUserRestriction(key, enabled, user);
5178                if (enabled != alreadyRestricted) {
5179                    if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5180                        // Send out notifications however as some clients may want to reread the
5181                        // value which actually changed due to a restriction having been applied.
5182                        final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
5183                        long version = SystemProperties.getLong(property, 0) + 1;
5184                        SystemProperties.set(property, Long.toString(version));
5185
5186                        final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
5187                        Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
5188                        mContext.getContentResolver().notifyChange(url, null, true, userHandle);
5189                    }
5190                }
5191            } finally {
5192                restoreCallingIdentity(id);
5193            }
5194            if (!enabled && alreadyRestricted) {
5195                try {
5196                    if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5197                        iAudioService.setMicrophoneMute(false, who.getPackageName());
5198                    } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5199                        iAudioService.setMasterMute(false, 0, who.getPackageName());
5200                    }
5201                } catch (RemoteException re) {
5202                    Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5203                }
5204            }
5205            sendChangedNotification(userHandle);
5206        }
5207    }
5208
5209    @Override
5210    public boolean setApplicationHidden(ComponentName who, String packageName,
5211            boolean hidden) {
5212        Preconditions.checkNotNull(who, "ComponentName is null");
5213        int callingUserId = UserHandle.getCallingUserId();
5214        synchronized (this) {
5215            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5216
5217            long id = Binder.clearCallingIdentity();
5218            try {
5219                IPackageManager pm = AppGlobals.getPackageManager();
5220                return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
5221            } catch (RemoteException re) {
5222                // shouldn't happen
5223                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
5224            } finally {
5225                restoreCallingIdentity(id);
5226            }
5227            return false;
5228        }
5229    }
5230
5231    @Override
5232    public boolean isApplicationHidden(ComponentName who, String packageName) {
5233        Preconditions.checkNotNull(who, "ComponentName is null");
5234        int callingUserId = UserHandle.getCallingUserId();
5235        synchronized (this) {
5236            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5237
5238            long id = Binder.clearCallingIdentity();
5239            try {
5240                IPackageManager pm = AppGlobals.getPackageManager();
5241                return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
5242            } catch (RemoteException re) {
5243                // shouldn't happen
5244                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
5245            } finally {
5246                restoreCallingIdentity(id);
5247            }
5248            return false;
5249        }
5250    }
5251
5252    @Override
5253    public void enableSystemApp(ComponentName who, String packageName) {
5254        Preconditions.checkNotNull(who, "ComponentName is null");
5255        synchronized (this) {
5256            // This API can only be called by an active device admin,
5257            // so try to retrieve it to check that the caller is one.
5258            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5259
5260            int userId = UserHandle.getCallingUserId();
5261            long id = Binder.clearCallingIdentity();
5262
5263            try {
5264                if (DBG) {
5265                    Slog.v(LOG_TAG, "installing " + packageName + " for "
5266                            + userId);
5267                }
5268
5269                UserManager um = UserManager.get(mContext);
5270                UserInfo primaryUser = um.getProfileParent(userId);
5271
5272                // Call did not come from a managed profile
5273                if (primaryUser == null) {
5274                    primaryUser = um.getUserInfo(userId);
5275                }
5276
5277                IPackageManager pm = AppGlobals.getPackageManager();
5278                if (!isSystemApp(pm, packageName, primaryUser.id)) {
5279                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
5280                }
5281
5282                // Install the app.
5283                pm.installExistingPackageAsUser(packageName, userId);
5284
5285            } catch (RemoteException re) {
5286                // shouldn't happen
5287                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5288            } finally {
5289                restoreCallingIdentity(id);
5290            }
5291        }
5292    }
5293
5294    @Override
5295    public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5296        Preconditions.checkNotNull(who, "ComponentName is null");
5297        synchronized (this) {
5298            // This API can only be called by an active device admin,
5299            // so try to retrieve it to check that the caller is one.
5300            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5301
5302            int userId = UserHandle.getCallingUserId();
5303            long id = Binder.clearCallingIdentity();
5304
5305            try {
5306                UserManager um = UserManager.get(mContext);
5307                UserInfo primaryUser = um.getProfileParent(userId);
5308
5309                // Call did not come from a managed profile.
5310                if (primaryUser == null) {
5311                    primaryUser = um.getUserInfo(userId);
5312                }
5313
5314                IPackageManager pm = AppGlobals.getPackageManager();
5315                List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5316                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5317                        0, // no flags
5318                        primaryUser.id);
5319
5320                if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5321                int numberOfAppsInstalled = 0;
5322                if (activitiesToEnable != null) {
5323                    for (ResolveInfo info : activitiesToEnable) {
5324                        if (info.activityInfo != null) {
5325                            String packageName = info.activityInfo.packageName;
5326                            if (isSystemApp(pm, packageName, primaryUser.id)) {
5327                                numberOfAppsInstalled++;
5328                                pm.installExistingPackageAsUser(packageName, userId);
5329                            } else {
5330                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
5331                                        + " system app");
5332                            }
5333                        }
5334                    }
5335                }
5336                return numberOfAppsInstalled;
5337            } catch (RemoteException e) {
5338                // shouldn't happen
5339                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5340                return 0;
5341            } finally {
5342                restoreCallingIdentity(id);
5343            }
5344        }
5345    }
5346
5347    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5348            throws RemoteException {
5349        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5350                userId);
5351        if (appInfo == null) {
5352            throw new IllegalArgumentException("The application " + packageName +
5353                    " is not present on this device");
5354        }
5355        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5356    }
5357
5358    @Override
5359    public void setAccountManagementDisabled(ComponentName who, String accountType,
5360            boolean disabled) {
5361        if (!mHasFeature) {
5362            return;
5363        }
5364        Preconditions.checkNotNull(who, "ComponentName is null");
5365        synchronized (this) {
5366            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5367                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5368            if (disabled) {
5369                ap.accountTypesWithManagementDisabled.add(accountType);
5370            } else {
5371                ap.accountTypesWithManagementDisabled.remove(accountType);
5372            }
5373            saveSettingsLocked(UserHandle.getCallingUserId());
5374        }
5375    }
5376
5377    @Override
5378    public String[] getAccountTypesWithManagementDisabled() {
5379        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5380    }
5381
5382    @Override
5383    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5384        enforceCrossUserPermission(userId);
5385        if (!mHasFeature) {
5386            return null;
5387        }
5388        synchronized (this) {
5389            DevicePolicyData policy = getUserData(userId);
5390            final int N = policy.mAdminList.size();
5391            HashSet<String> resultSet = new HashSet<String>();
5392            for (int i = 0; i < N; i++) {
5393                ActiveAdmin admin = policy.mAdminList.get(i);
5394                resultSet.addAll(admin.accountTypesWithManagementDisabled);
5395            }
5396            return resultSet.toArray(new String[resultSet.size()]);
5397        }
5398    }
5399
5400    @Override
5401    public void setUninstallBlocked(ComponentName who, String packageName,
5402            boolean uninstallBlocked) {
5403        Preconditions.checkNotNull(who, "ComponentName is null");
5404        final int userId = UserHandle.getCallingUserId();
5405        synchronized (this) {
5406            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5407
5408            long id = Binder.clearCallingIdentity();
5409            try {
5410                IPackageManager pm = AppGlobals.getPackageManager();
5411                pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5412            } catch (RemoteException re) {
5413                // Shouldn't happen.
5414                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5415            } finally {
5416                restoreCallingIdentity(id);
5417            }
5418        }
5419    }
5420
5421    @Override
5422    public boolean isUninstallBlocked(ComponentName who, String packageName) {
5423        // This function should return true if and only if the package is blocked by
5424        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5425        // when the package is a system app, or when it is an active device admin.
5426        final int userId = UserHandle.getCallingUserId();
5427
5428        synchronized (this) {
5429            if (who != null) {
5430                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5431            }
5432
5433            long id = Binder.clearCallingIdentity();
5434            try {
5435                IPackageManager pm = AppGlobals.getPackageManager();
5436                return pm.getBlockUninstallForUser(packageName, userId);
5437            } catch (RemoteException re) {
5438                // Shouldn't happen.
5439                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5440            } finally {
5441                restoreCallingIdentity(id);
5442            }
5443        }
5444        return false;
5445    }
5446
5447    @Override
5448    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5449        if (!mHasFeature) {
5450            return;
5451        }
5452        Preconditions.checkNotNull(who, "ComponentName is null");
5453        synchronized (this) {
5454            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5455                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5456            if (admin.disableCallerId != disabled) {
5457                admin.disableCallerId = disabled;
5458                saveSettingsLocked(UserHandle.getCallingUserId());
5459            }
5460        }
5461    }
5462
5463    @Override
5464    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5465        if (!mHasFeature) {
5466            return false;
5467        }
5468        Preconditions.checkNotNull(who, "ComponentName is null");
5469        synchronized (this) {
5470            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5471                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5472            return admin.disableCallerId;
5473        }
5474    }
5475
5476    @Override
5477    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5478        // TODO: Should there be a check to make sure this relationship is within a profile group?
5479        //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5480        synchronized (this) {
5481            ActiveAdmin admin = getProfileOwnerAdmin(userId);
5482            return (admin != null) ? admin.disableCallerId : false;
5483        }
5484    }
5485
5486    @Override
5487    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5488            Intent originalIntent) {
5489        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
5490                actualLookupKey, actualContactId, originalIntent);
5491        final int callingUserId = UserHandle.getCallingUserId();
5492
5493        final long ident = Binder.clearCallingIdentity();
5494        try {
5495            synchronized (this) {
5496                final int managedUserId = getManagedUserId(callingUserId);
5497                if (managedUserId < 0) {
5498                    return;
5499                }
5500                if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
5501                    if (VERBOSE_LOG) {
5502                        Log.v(LOG_TAG,
5503                                "Cross-profile contacts access disabled for user " + managedUserId);
5504                    }
5505                    return;
5506                }
5507                ContactsInternal.startQuickContactWithErrorToastForUser(
5508                        mContext, intent, new UserHandle(managedUserId));
5509            }
5510        } finally {
5511            Binder.restoreCallingIdentity(ident);
5512        }
5513    }
5514
5515    /**
5516     * @return the user ID of the managed user that is linked to the current user, if any.
5517     * Otherwise -1.
5518     */
5519    public int getManagedUserId(int callingUserId) {
5520        if (VERBOSE_LOG) {
5521            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
5522        }
5523
5524        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
5525            if (ui.id == callingUserId || !ui.isManagedProfile()) {
5526                continue; // Caller user self, or not a managed profile.  Skip.
5527            }
5528            if (VERBOSE_LOG) {
5529                Log.v(LOG_TAG, "Managed user=" + ui.id);
5530            }
5531            return ui.id;
5532        }
5533        if (VERBOSE_LOG) {
5534            Log.v(LOG_TAG, "Managed user not found.");
5535        }
5536        return -1;
5537    }
5538
5539    @Override
5540    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
5541        if (!mHasFeature) {
5542            return;
5543        }
5544        Preconditions.checkNotNull(who, "ComponentName is null");
5545        synchronized (this) {
5546            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5547                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5548            if (admin.disableBluetoothContactSharing != disabled) {
5549                admin.disableBluetoothContactSharing = disabled;
5550                saveSettingsLocked(UserHandle.getCallingUserId());
5551            }
5552        }
5553    }
5554
5555    @Override
5556    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
5557        if (!mHasFeature) {
5558            return false;
5559        }
5560        Preconditions.checkNotNull(who, "ComponentName is null");
5561        synchronized (this) {
5562            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5563                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5564            return admin.disableBluetoothContactSharing;
5565        }
5566    }
5567
5568    @Override
5569    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
5570        // TODO: Should there be a check to make sure this relationship is
5571        // within a profile group?
5572        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5573        synchronized (this) {
5574            ActiveAdmin admin = getProfileOwnerAdmin(userId);
5575            return (admin != null) ? admin.disableBluetoothContactSharing : false;
5576        }
5577    }
5578
5579    /**
5580     * Sets which packages may enter lock task mode.
5581     *
5582     * This function can only be called by the device owner.
5583     * @param packages The list of packages allowed to enter lock task mode.
5584     */
5585    public void setLockTaskPackages(ComponentName who, String[] packages) throws SecurityException {
5586        Preconditions.checkNotNull(who, "ComponentName is null");
5587        synchronized (this) {
5588            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5589
5590            int userHandle = Binder.getCallingUserHandle().getIdentifier();
5591            DevicePolicyData policy = getUserData(userHandle);
5592            policy.mLockTaskPackages.clear();
5593            if (packages != null) {
5594                for (int j = 0; j < packages.length; j++) {
5595                    String pkg = packages[j];
5596                    policy.mLockTaskPackages.add(pkg);
5597                }
5598            }
5599
5600            // Store the settings persistently.
5601            saveSettingsLocked(userHandle);
5602            updateLockTaskPackagesLocked(policy, userHandle);
5603        }
5604    }
5605
5606    /**
5607     * This function returns the list of components allowed to start the task lock mode.
5608     */
5609    public String[] getLockTaskPackages(ComponentName who) {
5610        Preconditions.checkNotNull(who, "ComponentName is null");
5611        synchronized (this) {
5612            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5613
5614            int userHandle = Binder.getCallingUserHandle().getIdentifier();
5615            DevicePolicyData policy = getUserData(userHandle);
5616            return policy.mLockTaskPackages.toArray(new String[policy.mLockTaskPackages.size()]);
5617        }
5618    }
5619
5620    /**
5621     * This function lets the caller know whether the given package is allowed to start the
5622     * lock task mode.
5623     * @param pkg The package to check
5624     */
5625    public boolean isLockTaskPermitted(String pkg) {
5626        // Get current user's devicepolicy
5627        int uid = Binder.getCallingUid();
5628        int userHandle = UserHandle.getUserId(uid);
5629        DevicePolicyData policy = getUserData(userHandle);
5630        synchronized (this) {
5631            for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5632                String lockTaskPackage = policy.mLockTaskPackages.get(i);
5633
5634                // If the given package equals one of the packages stored our list,
5635                // we allow this package to start lock task mode.
5636                if (lockTaskPackage.equals(pkg)) {
5637                    return true;
5638                }
5639            }
5640        }
5641        return false;
5642    }
5643
5644    @Override
5645    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5646        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5647            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5648        }
5649        synchronized (this) {
5650            final DevicePolicyData policy = getUserData(userHandle);
5651            Bundle adminExtras = new Bundle();
5652            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5653            for (ActiveAdmin admin : policy.mAdminList) {
5654                boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5655                boolean ownsProfile = (getProfileOwner(userHandle) != null
5656                        && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5657                if (ownsDevice || ownsProfile) {
5658                    if (isEnabled) {
5659                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5660                                adminExtras, null);
5661                    } else {
5662                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
5663                    }
5664                }
5665            }
5666        }
5667    }
5668
5669    @Override
5670    public void setGlobalSetting(ComponentName who, String setting, String value) {
5671        final ContentResolver contentResolver = mContext.getContentResolver();
5672        Preconditions.checkNotNull(who, "ComponentName is null");
5673
5674        synchronized (this) {
5675            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5676
5677            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
5678                // BLUETOOTH_ON and WIFI_ON used to be supported but not any more. We do not want to
5679                // throw a SecurityException not to break apps.
5680                if (!Settings.Global.BLUETOOTH_ON.equals(setting)
5681                        && !Settings.Global.WIFI_ON.equals(setting)) {
5682                    throw new SecurityException(String.format(
5683                            "Permission denial: device owners cannot update %1$s", setting));
5684                }
5685            }
5686
5687            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
5688                // ignore if it contradicts an existing policy
5689                long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
5690                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
5691                    return;
5692                }
5693            }
5694
5695            long id = Binder.clearCallingIdentity();
5696            try {
5697                Settings.Global.putString(contentResolver, setting, value);
5698            } finally {
5699                restoreCallingIdentity(id);
5700            }
5701        }
5702    }
5703
5704    @Override
5705    public void setSecureSetting(ComponentName who, String setting, String value) {
5706        Preconditions.checkNotNull(who, "ComponentName is null");
5707        int callingUserId = UserHandle.getCallingUserId();
5708        final ContentResolver contentResolver = mContext.getContentResolver();
5709
5710        synchronized (this) {
5711            ActiveAdmin activeAdmin =
5712                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5713
5714            if (isDeviceOwner(activeAdmin.info.getPackageName())) {
5715                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
5716                    throw new SecurityException(String.format(
5717                            "Permission denial: Device owners cannot update %1$s", setting));
5718                }
5719            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
5720                throw new SecurityException(String.format(
5721                        "Permission denial: Profile owners cannot update %1$s", setting));
5722            }
5723
5724            long id = Binder.clearCallingIdentity();
5725            try {
5726                Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
5727            } finally {
5728                restoreCallingIdentity(id);
5729            }
5730        }
5731    }
5732
5733    @Override
5734    public void setMasterVolumeMuted(ComponentName who, boolean on) {
5735        Preconditions.checkNotNull(who, "ComponentName is null");
5736        synchronized (this) {
5737            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5738
5739            IAudioService iAudioService = IAudioService.Stub.asInterface(
5740                    ServiceManager.getService(Context.AUDIO_SERVICE));
5741            try {
5742                iAudioService.setMasterMute(on, 0, who.getPackageName());
5743            } catch (RemoteException re) {
5744                Slog.e(LOG_TAG, "Failed to setMasterMute", re);
5745            }
5746        }
5747    }
5748
5749    @Override
5750    public boolean isMasterVolumeMuted(ComponentName who) {
5751        Preconditions.checkNotNull(who, "ComponentName is null");
5752        synchronized (this) {
5753            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5754
5755            AudioManager audioManager =
5756                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
5757            return audioManager.isMasterMute();
5758        }
5759    }
5760
5761    @Override
5762    public void setUserIcon(ComponentName who, Bitmap icon) {
5763        synchronized (this) {
5764            Preconditions.checkNotNull(who, "ComponentName is null");
5765            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5766
5767            int userId = UserHandle.getCallingUserId();
5768            long id = Binder.clearCallingIdentity();
5769            try {
5770                mUserManager.setUserIcon(userId, icon);
5771            } finally {
5772                restoreCallingIdentity(id);
5773            }
5774        }
5775    }
5776
5777    @Override
5778    public void sendDeviceInitializerStatus(int statusCode, String description) {
5779        synchronized (this) {
5780            String packageName = getDeviceInitializer();
5781            if (packageName == null) {
5782                throw new SecurityException("No device initializers");
5783            }
5784            UserHandle callingUser = Binder.getCallingUserHandle();
5785            int deviceInitializerUid = -1;
5786            try {
5787                deviceInitializerUid = mContext.getPackageManager().getPackageUid(
5788                        packageName, callingUser.getIdentifier());
5789            } catch (NameNotFoundException e) {
5790                throw new SecurityException(e);
5791            }
5792            if (Binder.getCallingUid() != deviceInitializerUid) {
5793                throw new SecurityException("Caller must be a device initializer");
5794            }
5795            long id = Binder.clearCallingIdentity();
5796            try {
5797                Intent intent = new Intent(
5798                        DevicePolicyManager.ACTION_SEND_DEVICE_INITIALIZER_STATUS);
5799                intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_INITIALIZER_STATUS_CODE,
5800                        statusCode);
5801                intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_INITIALIZER_STATUS_DESCRIPTION,
5802                        description);
5803                mContext.sendBroadcastAsUser(intent, callingUser,
5804                        android.Manifest.permission.RECEIVE_DEVICE_INITIALIZER_STATUS);
5805            } finally {
5806                restoreCallingIdentity(id);
5807            }
5808        }
5809    }
5810
5811    /**
5812     * We need to update the internal state of whether a user has completed setup once. After
5813     * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
5814     * as we don't trust any apps that might try to reset it.
5815     * <p>
5816     * Unfortunately, we don't know which user's setup state was changed, so we write all of
5817     * them.
5818     */
5819    void updateUserSetupComplete() {
5820        List<UserInfo> users = mUserManager.getUsers(true);
5821        ContentResolver resolver = mContext.getContentResolver();
5822        final int N = users.size();
5823        for (int i = 0; i < N; i++) {
5824            int userHandle = users.get(i).id;
5825            if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
5826                    userHandle) != 0) {
5827                DevicePolicyData policy = getUserData(userHandle);
5828                if (!policy.mUserSetupComplete) {
5829                    policy.mUserSetupComplete = true;
5830                    synchronized (this) {
5831                        saveSettingsLocked(userHandle);
5832                    }
5833                }
5834            }
5835        }
5836    }
5837
5838    private class SetupContentObserver extends ContentObserver {
5839
5840        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
5841                Settings.Secure.USER_SETUP_COMPLETE);
5842
5843        public SetupContentObserver(Handler handler) {
5844            super(handler);
5845        }
5846
5847        void register(ContentResolver resolver) {
5848            resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
5849        }
5850
5851        @Override
5852        public void onChange(boolean selfChange, Uri uri) {
5853            if (mUserSetupComplete.equals(uri)) {
5854                updateUserSetupComplete();
5855            }
5856        }
5857    }
5858
5859    private final class LocalService extends DevicePolicyManagerInternal {
5860        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
5861
5862        @Override
5863        public List<String> getCrossProfileWidgetProviders(int profileId) {
5864            synchronized (DevicePolicyManagerService.this) {
5865                if (mDeviceOwner == null) {
5866                    return Collections.emptyList();
5867                }
5868                ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
5869                if (ownerComponent == null) {
5870                    return Collections.emptyList();
5871                }
5872
5873                DevicePolicyData policy = getUserDataUnchecked(profileId);
5874                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
5875
5876                if (admin == null || admin.crossProfileWidgetProviders == null
5877                        || admin.crossProfileWidgetProviders.isEmpty()) {
5878                    return Collections.emptyList();
5879                }
5880
5881                return admin.crossProfileWidgetProviders;
5882            }
5883        }
5884
5885        @Override
5886        public void addOnCrossProfileWidgetProvidersChangeListener(
5887                OnCrossProfileWidgetProvidersChangeListener listener) {
5888            synchronized (DevicePolicyManagerService.this) {
5889                if (mWidgetProviderListeners == null) {
5890                    mWidgetProviderListeners = new ArrayList<>();
5891                }
5892                if (!mWidgetProviderListeners.contains(listener)) {
5893                    mWidgetProviderListeners.add(listener);
5894                }
5895            }
5896        }
5897
5898        @Override
5899        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
5900            final int userId = UserHandle.getUserId(uid);
5901            synchronized(DevicePolicyManagerService.this) {
5902                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
5903            }
5904        }
5905
5906        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
5907            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
5908            synchronized (DevicePolicyManagerService.this) {
5909                listeners = new ArrayList<>(mWidgetProviderListeners);
5910            }
5911            final int listenerCount = listeners.size();
5912            for (int i = 0; i < listenerCount; i++) {
5913                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
5914                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
5915            }
5916        }
5917    }
5918
5919    /**
5920     * Returns true if specified admin is allowed to limit passwords and has a
5921     * {@code passwordQuality} of at least {@code minPasswordQuality}
5922     */
5923    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
5924        if (admin.passwordQuality < minPasswordQuality) {
5925            return false;
5926        }
5927        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
5928    }
5929}
5930