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