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