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