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