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