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