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