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            }
4240        }
4241    }
4242
4243    @Override
4244    public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) {
4245        if (!mHasFeature) {
4246            return false;
4247        }
4248        if (initializer == null || !DeviceOwner.isInstalled(
4249                initializer.getPackageName(), mContext.getPackageManager())) {
4250            throw new IllegalArgumentException("Invalid component name " + initializer
4251                    + " for device initializer");
4252        }
4253        boolean isInitializerSystemApp;
4254        try {
4255            isInitializerSystemApp = isSystemApp(AppGlobals.getPackageManager(),
4256                    initializer.getPackageName(), Binder.getCallingUserHandle().getIdentifier());
4257        } catch (RemoteException | IllegalArgumentException e) {
4258            isInitializerSystemApp = false;
4259            Slog.e(LOG_TAG, "Fail to check if device initialzer is system app.", e);
4260        }
4261        if (!isInitializerSystemApp) {
4262            throw new IllegalArgumentException("Only system app can be set as device initializer.");
4263        }
4264        synchronized (this) {
4265            enforceCanSetDeviceInitializer(who);
4266
4267            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4268                throw new IllegalStateException(
4269                        "Trying to set device initializer but device initializer is already set.");
4270            }
4271
4272            if (mDeviceOwner == null) {
4273                // Device owner state does not exist, create it.
4274                mDeviceOwner = DeviceOwner.createWithDeviceInitializer(initializer);
4275            } else {
4276                // Device owner already exists, update it.
4277                mDeviceOwner.setDeviceInitializer(initializer);
4278            }
4279
4280            addDeviceInitializerToLockTaskPackagesLocked(UserHandle.USER_OWNER);
4281            mDeviceOwner.writeOwnerFile();
4282            return true;
4283        }
4284    }
4285
4286    private void enforceCanSetDeviceInitializer(ComponentName who) {
4287        if (who == null) {
4288            mContext.enforceCallingOrSelfPermission(
4289                    android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4290            if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4291                throw new IllegalStateException(
4292                        "Trying to set device initializer but device is already provisioned.");
4293            }
4294        } else {
4295            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
4296        }
4297    }
4298
4299    @Override
4300    public boolean isDeviceInitializer(String packageName) {
4301        if (!mHasFeature) {
4302            return false;
4303        }
4304        synchronized (this) {
4305            return mDeviceOwner != null
4306                    && mDeviceOwner.hasDeviceInitializer()
4307                    && mDeviceOwner.getDeviceInitializerPackageName().equals(packageName);
4308        }
4309    }
4310
4311    @Override
4312    public String getDeviceInitializer() {
4313        if (!mHasFeature) {
4314            return null;
4315        }
4316        synchronized (this) {
4317            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4318                return mDeviceOwner.getDeviceInitializerPackageName();
4319            }
4320        }
4321        return null;
4322    }
4323
4324    @Override
4325    public ComponentName getDeviceInitializerComponent() {
4326        if (!mHasFeature) {
4327            return null;
4328        }
4329        synchronized (this) {
4330            if (mDeviceOwner != null && mDeviceOwner.hasDeviceInitializer()) {
4331                return mDeviceOwner.getDeviceInitializerComponent();
4332            }
4333        }
4334        return null;
4335    }
4336
4337    @Override
4338    public void clearDeviceInitializer(ComponentName who) {
4339        if (!mHasFeature) {
4340            return;
4341        }
4342        Preconditions.checkNotNull(who, "ComponentName is null");
4343
4344        ActiveAdmin admin = getActiveAdminUncheckedLocked(who, UserHandle.getCallingUserId());
4345
4346        if (admin.getUid() != Binder.getCallingUid()) {
4347            throw new SecurityException("Admin " + who + " is not owned by uid "
4348                    + Binder.getCallingUid());
4349        }
4350
4351        if (!isDeviceInitializer(admin.info.getPackageName())
4352                && !isDeviceOwner(admin.info.getPackageName())) {
4353            throw new SecurityException(
4354                    "clearDeviceInitializer can only be called by the device initializer/owner");
4355        }
4356        synchronized (this) {
4357            long ident = Binder.clearCallingIdentity();
4358            try {
4359                if (mDeviceOwner != null) {
4360                    mDeviceOwner.clearDeviceInitializer();
4361                    mDeviceOwner.writeOwnerFile();
4362                }
4363            } finally {
4364                Binder.restoreCallingIdentity(ident);
4365            }
4366        }
4367    }
4368
4369    @Override
4370    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
4371        if (!mHasFeature) {
4372            return false;
4373        }
4374        if (who == null
4375                || !DeviceOwner.isInstalledForUser(who.getPackageName(), userHandle)) {
4376            throw new IllegalArgumentException("Component " + who
4377                    + " not installed for userId:" + userHandle);
4378        }
4379        synchronized (this) {
4380            enforceCanSetProfileOwner(userHandle);
4381            if (mDeviceOwner == null) {
4382                // Device owner state does not exist, create it.
4383                mDeviceOwner = DeviceOwner.createWithProfileOwner(who, ownerName,
4384                        userHandle);
4385            } else {
4386                // Device owner state already exists, update it.
4387                mDeviceOwner.setProfileOwner(who, ownerName, userHandle);
4388            }
4389            mDeviceOwner.writeOwnerFile();
4390            return true;
4391        }
4392    }
4393
4394    @Override
4395    public void clearProfileOwner(ComponentName who) {
4396        if (!mHasFeature) {
4397            return;
4398        }
4399        UserHandle callingUser = Binder.getCallingUserHandle();
4400        // Check if this is the profile owner who is calling
4401        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4402        synchronized (this) {
4403            clearUserPoliciesLocked(callingUser);
4404            if (mDeviceOwner != null) {
4405                mDeviceOwner.removeProfileOwner(callingUser.getIdentifier());
4406                mDeviceOwner.writeOwnerFile();
4407            }
4408        }
4409    }
4410
4411    private void clearUserPoliciesLocked(UserHandle userHandle) {
4412        int userId = userHandle.getIdentifier();
4413        // Reset some of the user-specific policies
4414        DevicePolicyData policy = getUserData(userId);
4415        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
4416        policy.mDelegatedCertInstallerPackage = null;
4417        policy.mStatusBarDisabled = false;
4418        saveSettingsLocked(userId);
4419
4420        final long ident = Binder.clearCallingIdentity();
4421        try {
4422            clearUserRestrictions(userHandle);
4423            AppGlobals.getPackageManager().updatePermissionFlagsForAllApps(
4424                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
4425                    0  /* flagValues */, userHandle.getIdentifier());
4426        } catch (RemoteException re) {
4427        } finally {
4428            Binder.restoreCallingIdentity(ident);
4429        }
4430    }
4431
4432
4433    private void clearUserRestrictions(UserHandle userHandle) {
4434        Bundle userRestrictions = mUserManager.getUserRestrictions();
4435        mUserManager.setUserRestrictions(new Bundle(), userHandle);
4436        IAudioService iAudioService = IAudioService.Stub.asInterface(
4437                ServiceManager.getService(Context.AUDIO_SERVICE));
4438        if (userRestrictions.getBoolean(UserManager.DISALLOW_ADJUST_VOLUME)) {
4439            try {
4440                iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
4441                        userHandle.getIdentifier());
4442            } catch (RemoteException e) {
4443                // Not much we can do here.
4444            }
4445        }
4446        if (userRestrictions.getBoolean(UserManager.DISALLOW_UNMUTE_MICROPHONE)) {
4447            try {
4448                iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
4449                        userHandle.getIdentifier());
4450            } catch (RemoteException e) {
4451                // Not much we can do here.
4452            }
4453        }
4454    }
4455
4456    @Override
4457    public boolean hasUserSetupCompleted() {
4458        return hasUserSetupCompleted(UserHandle.getCallingUserId());
4459    }
4460
4461    private boolean hasUserSetupCompleted(int userHandle) {
4462        if (!mHasFeature) {
4463            return true;
4464        }
4465        DevicePolicyData policy = getUserData(userHandle);
4466        // If policy is null, return true, else check if the setup has completed.
4467        return policy == null || policy.mUserSetupComplete;
4468    }
4469
4470    @Override
4471    public boolean setUserEnabled(ComponentName who) {
4472        if (!mHasFeature) {
4473            return false;
4474        }
4475        synchronized (this) {
4476            if (who == null) {
4477                throw new NullPointerException("ComponentName is null");
4478            }
4479            int userId = UserHandle.getCallingUserId();
4480
4481            ActiveAdmin activeAdmin =
4482                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4483            if (!isDeviceInitializer(activeAdmin.info.getPackageName())) {
4484                throw new SecurityException(
4485                        "This method can only be called by device initializers");
4486            }
4487
4488            long id = Binder.clearCallingIdentity();
4489            try {
4490                if (!isDeviceOwner(activeAdmin.info.getPackageName())) {
4491                    IPackageManager ipm = AppGlobals.getPackageManager();
4492                    ipm.setComponentEnabledSetting(who,
4493                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
4494                            PackageManager.DONT_KILL_APP, userId);
4495
4496                    removeActiveAdmin(who, userId);
4497                }
4498
4499                if (userId == UserHandle.USER_OWNER) {
4500                    Settings.Global.putInt(mContext.getContentResolver(),
4501                            Settings.Global.DEVICE_PROVISIONED, 1);
4502                }
4503                Settings.Secure.putIntForUser(mContext.getContentResolver(),
4504                        Settings.Secure.USER_SETUP_COMPLETE, 1, userId);
4505            } catch (RemoteException e) {
4506                Log.i(LOG_TAG, "Can't talk to package manager", e);
4507                return false;
4508            } finally {
4509                restoreCallingIdentity(id);
4510            }
4511            return true;
4512        }
4513    }
4514
4515    @Override
4516    public void setProfileEnabled(ComponentName who) {
4517        if (!mHasFeature) {
4518            return;
4519        }
4520        Preconditions.checkNotNull(who, "ComponentName is null");
4521        final int userHandle = UserHandle.getCallingUserId();
4522        synchronized (this) {
4523            // Check if this is the profile owner who is calling
4524            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4525            int userId = UserHandle.getCallingUserId();
4526
4527            long id = Binder.clearCallingIdentity();
4528            try {
4529                mUserManager.setUserEnabled(userId);
4530                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
4531                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userHandle));
4532                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
4533                        Intent.FLAG_RECEIVER_FOREGROUND);
4534                // TODO This should send to parent of profile (which is always owner at the moment).
4535                mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
4536            } finally {
4537                restoreCallingIdentity(id);
4538            }
4539        }
4540    }
4541
4542    @Override
4543    public void setProfileName(ComponentName who, String profileName) {
4544        Preconditions.checkNotNull(who, "ComponentName is null");
4545        int userId = UserHandle.getCallingUserId();
4546        // Check if this is the profile owner (includes device owner).
4547        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4548
4549        long id = Binder.clearCallingIdentity();
4550        try {
4551            mUserManager.setUserName(userId, profileName);
4552        } finally {
4553            restoreCallingIdentity(id);
4554        }
4555    }
4556
4557    @Override
4558    public ComponentName getProfileOwner(int userHandle) {
4559        if (!mHasFeature) {
4560            return null;
4561        }
4562
4563        synchronized (this) {
4564            if (mDeviceOwner != null) {
4565                return mDeviceOwner.getProfileOwnerComponent(userHandle);
4566            }
4567        }
4568        return null;
4569    }
4570
4571    // Returns the active profile owner for this user or null if the current user has no
4572    // profile owner.
4573    private ActiveAdmin getProfileOwnerAdmin(int userHandle) {
4574        ComponentName profileOwner =
4575                mDeviceOwner != null ? mDeviceOwner.getProfileOwnerComponent(userHandle) : null;
4576        if (profileOwner == null) {
4577            return null;
4578        }
4579        DevicePolicyData policy = getUserData(userHandle);
4580        final int n = policy.mAdminList.size();
4581        for (int i = 0; i < n; i++) {
4582            ActiveAdmin admin = policy.mAdminList.get(i);
4583            if (profileOwner.equals(admin.info.getComponent())) {
4584                return admin;
4585            }
4586        }
4587        return null;
4588    }
4589
4590    @Override
4591    public String getProfileOwnerName(int userHandle) {
4592        if (!mHasFeature) {
4593            return null;
4594        }
4595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
4596        ComponentName profileOwner = getProfileOwner(userHandle);
4597        if (profileOwner == null) {
4598            return null;
4599        }
4600        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
4601    }
4602
4603    /**
4604     * Canonical name for a given package.
4605     */
4606    private String getApplicationLabel(String packageName, int userHandle) {
4607        long token = Binder.clearCallingIdentity();
4608        try {
4609            final Context userContext;
4610            try {
4611                UserHandle handle = new UserHandle(userHandle);
4612                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
4613            } catch (PackageManager.NameNotFoundException nnfe) {
4614                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
4615                return null;
4616            }
4617            ApplicationInfo appInfo = userContext.getApplicationInfo();
4618            CharSequence result = null;
4619            if (appInfo != null) {
4620                PackageManager pm = userContext.getPackageManager();
4621                result = pm.getApplicationLabel(appInfo);
4622            }
4623            return result != null ? result.toString() : null;
4624        } finally {
4625            Binder.restoreCallingIdentity(token);
4626        }
4627    }
4628
4629    /**
4630     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4631     * permission.
4632     * The profile owner can only be set before the user setup phase has completed,
4633     * except for:
4634     * - SYSTEM_UID
4635     * - adb if there are not accounts.
4636     */
4637    private void enforceCanSetProfileOwner(int userHandle) {
4638        UserInfo info = mUserManager.getUserInfo(userHandle);
4639        if (info == null) {
4640            // User doesn't exist.
4641            throw new IllegalArgumentException(
4642                    "Attempted to set profile owner for invalid userId: " + userHandle);
4643        }
4644        if (info.isGuest()) {
4645            throw new IllegalStateException("Cannot set a profile owner on a guest");
4646        }
4647        if (getProfileOwner(userHandle) != null) {
4648            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
4649                    + "is already set.");
4650        }
4651        int callingUid = Binder.getCallingUid();
4652        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4653            if (hasUserSetupCompleted(userHandle) &&
4654                    AccountManager.get(mContext).getAccountsAsUser(userHandle).length > 0) {
4655                throw new IllegalStateException("Not allowed to set the profile owner because "
4656                        + "there are already some accounts on the profile");
4657            }
4658            return;
4659        }
4660        mContext.enforceCallingOrSelfPermission(
4661                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4662        if (hasUserSetupCompleted(userHandle)
4663                && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
4664            throw new IllegalStateException("Cannot set the profile owner on a user which is "
4665                    + "already set-up");
4666        }
4667    }
4668
4669    /**
4670     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
4671     * permission.
4672     * The device owner can only be set before the setup phase of the primary user has completed,
4673     * except for adb if no accounts or additional users are present on the device.
4674     */
4675    private void enforceCanSetDeviceOwner() {
4676        if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
4677            throw new IllegalStateException("Trying to set the device owner, but device owner "
4678                    + "is already set.");
4679        }
4680        int callingUid = Binder.getCallingUid();
4681        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
4682            if (!hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4683                return;
4684            }
4685            if (mUserManager.getUserCount() > 1) {
4686                throw new IllegalStateException("Not allowed to set the device owner because there "
4687                        + "are already several users on the device");
4688            }
4689            if (AccountManager.get(mContext).getAccounts().length > 0) {
4690                throw new IllegalStateException("Not allowed to set the device owner because there "
4691                        + "are already some accounts on the device");
4692            }
4693            return;
4694        }
4695        mContext.enforceCallingOrSelfPermission(
4696                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
4697        if (hasUserSetupCompleted(UserHandle.USER_OWNER)) {
4698            throw new IllegalStateException("Cannot set the device owner if the device is "
4699                    + "already set-up");
4700        }
4701    }
4702
4703    private void enforceCrossUserPermission(int userHandle) {
4704        if (userHandle < 0) {
4705            throw new IllegalArgumentException("Invalid userId " + userHandle);
4706        }
4707        final int callingUid = Binder.getCallingUid();
4708        if (userHandle == UserHandle.getUserId(callingUid)) return;
4709        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4710            mContext.enforceCallingOrSelfPermission(
4711                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
4712                    + " INTERACT_ACROSS_USERS_FULL permission");
4713        }
4714    }
4715
4716    private void enforceSystemProcess(String message) {
4717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4718            throw new SecurityException(message);
4719        }
4720    }
4721
4722    private void enforceNotManagedProfile(int userHandle, String message) {
4723        if(isManagedProfile(userHandle)) {
4724            throw new SecurityException("You can not " + message + " for a managed profile. ");
4725        }
4726    }
4727
4728    private UserInfo getProfileParent(int userHandle) {
4729        long ident = Binder.clearCallingIdentity();
4730        try {
4731            return mUserManager.getProfileParent(userHandle);
4732        } finally {
4733            Binder.restoreCallingIdentity(ident);
4734        }
4735    }
4736
4737    private boolean isManagedProfile(int userHandle) {
4738        long ident = Binder.clearCallingIdentity();
4739        try {
4740            return mUserManager.getUserInfo(userHandle).isManagedProfile();
4741        } finally {
4742            Binder.restoreCallingIdentity(ident);
4743        }
4744    }
4745
4746    private void enableIfNecessary(String packageName, int userId) {
4747        try {
4748            IPackageManager ipm = AppGlobals.getPackageManager();
4749            ApplicationInfo ai = ipm.getApplicationInfo(packageName,
4750                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
4751                    userId);
4752            if (ai.enabledSetting
4753                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
4754                ipm.setApplicationEnabledSetting(packageName,
4755                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
4756                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
4757            }
4758        } catch (RemoteException e) {
4759        }
4760    }
4761
4762    @Override
4763    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4764        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4765                != PackageManager.PERMISSION_GRANTED) {
4766
4767            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
4768                    + Binder.getCallingPid()
4769                    + ", uid=" + Binder.getCallingUid());
4770            return;
4771        }
4772
4773        final Printer p = new PrintWriterPrinter(pw);
4774
4775        synchronized (this) {
4776            p.println("Current Device Policy Manager state:");
4777            if (mDeviceOwner != null) {
4778                mDeviceOwner.dump("  ", pw);
4779            }
4780            int userCount = mUserData.size();
4781            for (int u = 0; u < userCount; u++) {
4782                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
4783                p.println("  Enabled Device Admins (User " + policy.mUserHandle + "):");
4784                final int N = policy.mAdminList.size();
4785                for (int i=0; i<N; i++) {
4786                    ActiveAdmin ap = policy.mAdminList.get(i);
4787                    if (ap != null) {
4788                        pw.print("  "); pw.print(ap.info.getComponent().flattenToShortString());
4789                                pw.println(":");
4790                        ap.dump("    ", pw);
4791                    }
4792                }
4793                if (!policy.mRemovingAdmins.isEmpty()) {
4794                    p.println("  Removing Device Admins (User " + policy.mUserHandle + "): "
4795                            + policy.mRemovingAdmins);
4796                }
4797
4798                pw.println(" ");
4799                pw.print("  mPasswordOwner="); pw.println(policy.mPasswordOwner);
4800            }
4801        }
4802    }
4803
4804    @Override
4805    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
4806            ComponentName activity) {
4807        Preconditions.checkNotNull(who, "ComponentName is null");
4808        final int userHandle = UserHandle.getCallingUserId();
4809        synchronized (this) {
4810            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4811
4812            IPackageManager pm = AppGlobals.getPackageManager();
4813            long id = Binder.clearCallingIdentity();
4814            try {
4815                pm.addPersistentPreferredActivity(filter, activity, userHandle);
4816            } catch (RemoteException re) {
4817                // Shouldn't happen
4818            } finally {
4819                restoreCallingIdentity(id);
4820            }
4821        }
4822    }
4823
4824    @Override
4825    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
4826        Preconditions.checkNotNull(who, "ComponentName is null");
4827        final int userHandle = UserHandle.getCallingUserId();
4828        synchronized (this) {
4829            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4830
4831            IPackageManager pm = AppGlobals.getPackageManager();
4832            long id = Binder.clearCallingIdentity();
4833            try {
4834                pm.clearPackagePersistentPreferredActivities(packageName, userHandle);
4835            } catch (RemoteException re) {
4836                // Shouldn't happen
4837            } finally {
4838                restoreCallingIdentity(id);
4839            }
4840        }
4841    }
4842
4843    @Override
4844    public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
4845        Preconditions.checkNotNull(who, "ComponentName is null");
4846        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4847        synchronized (this) {
4848            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4849
4850            long id = Binder.clearCallingIdentity();
4851            try {
4852                mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
4853            } finally {
4854                restoreCallingIdentity(id);
4855            }
4856        }
4857    }
4858
4859    @Override
4860    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
4861            PersistableBundle args) {
4862        if (!mHasFeature) {
4863            return;
4864        }
4865        Preconditions.checkNotNull(admin, "admin is null");
4866        Preconditions.checkNotNull(agent, "agent is null");
4867        final int userHandle = UserHandle.getCallingUserId();
4868        enforceNotManagedProfile(userHandle, "set trust agent configuration");
4869        synchronized (this) {
4870            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
4871                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
4872            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
4873            saveSettingsLocked(userHandle);
4874            syncDeviceCapabilitiesLocked(getUserData(userHandle));
4875        }
4876    }
4877
4878    @Override
4879    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
4880            ComponentName agent, int userHandle) {
4881        if (!mHasFeature) {
4882            return null;
4883        }
4884        Preconditions.checkNotNull(agent, "agent null");
4885        enforceCrossUserPermission(userHandle);
4886
4887        synchronized (this) {
4888            final String componentName = agent.flattenToString();
4889            if (admin != null) {
4890                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle);
4891                if (ap == null) return null;
4892                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
4893                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
4894                List<PersistableBundle> result = new ArrayList<PersistableBundle>();
4895                result.add(trustAgentInfo.options);
4896                return result;
4897            }
4898
4899            // Return strictest policy for this user and profiles that are visible from this user.
4900            final List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
4901            List<PersistableBundle> result = null;
4902
4903            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
4904            // of the options. If any admin doesn't have options, discard options for the rest
4905            // and return null.
4906            boolean allAdminsHaveOptions = true;
4907            for (UserInfo userInfo : profiles) {
4908                DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4909                final int N = policy.mAdminList.size();
4910                for (int i=0; i < N; i++) {
4911                    final ActiveAdmin active = policy.mAdminList.get(i);
4912                    final boolean disablesTrust = (active.disabledKeyguardFeatures
4913                            & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
4914                    final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
4915                    if (info != null && info.options != null && !info.options.isEmpty()) {
4916                        if (disablesTrust) {
4917                            if (result == null) {
4918                                result = new ArrayList<PersistableBundle>();
4919                            }
4920                            result.add(info.options);
4921                        } else {
4922                            Log.w(LOG_TAG, "Ignoring admin " + active.info
4923                                    + " because it has trust options but doesn't declare "
4924                                    + "KEYGUARD_DISABLE_TRUST_AGENTS");
4925                        }
4926                    } else if (disablesTrust) {
4927                        allAdminsHaveOptions = false;
4928                        break;
4929                    }
4930                }
4931            }
4932            return allAdminsHaveOptions ? result : null;
4933        }
4934    }
4935
4936    @Override
4937    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
4938        Preconditions.checkNotNull(who, "ComponentName is null");
4939        synchronized (this) {
4940            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4941
4942            int userHandle = UserHandle.getCallingUserId();
4943            DevicePolicyData userData = getUserData(userHandle);
4944            userData.mRestrictionsProvider = permissionProvider;
4945            saveSettingsLocked(userHandle);
4946        }
4947    }
4948
4949    @Override
4950    public ComponentName getRestrictionsProvider(int userHandle) {
4951        synchronized (this) {
4952            if (Binder.getCallingUid() != Process.SYSTEM_UID) {
4953                throw new SecurityException("Only the system can query the permission provider");
4954            }
4955            DevicePolicyData userData = getUserData(userHandle);
4956            return userData != null ? userData.mRestrictionsProvider : null;
4957        }
4958    }
4959
4960    @Override
4961    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
4962        Preconditions.checkNotNull(who, "ComponentName is null");
4963        int callingUserId = UserHandle.getCallingUserId();
4964        synchronized (this) {
4965            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4966
4967            IPackageManager pm = AppGlobals.getPackageManager();
4968            long id = Binder.clearCallingIdentity();
4969            try {
4970                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
4971                    pm.addCrossProfileIntentFilter(filter, who.getPackageName(), callingUserId,
4972                            UserHandle.USER_OWNER, 0);
4973                }
4974                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
4975                    pm.addCrossProfileIntentFilter(filter, who.getPackageName(),
4976                            UserHandle.USER_OWNER, callingUserId, 0);
4977                }
4978            } catch (RemoteException re) {
4979                // Shouldn't happen
4980            } finally {
4981                restoreCallingIdentity(id);
4982            }
4983        }
4984    }
4985
4986    @Override
4987    public void clearCrossProfileIntentFilters(ComponentName who) {
4988        Preconditions.checkNotNull(who, "ComponentName is null");
4989        int callingUserId = UserHandle.getCallingUserId();
4990        synchronized (this) {
4991            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4992            IPackageManager pm = AppGlobals.getPackageManager();
4993            long id = Binder.clearCallingIdentity();
4994            try {
4995                // Removing those that go from the managed profile to the primary user.
4996                pm.clearCrossProfileIntentFilters(callingUserId, who.getPackageName());
4997                // And those that go from the primary user to the managed profile.
4998                // If we want to support multiple managed profiles, we will have to only remove
4999                // those that have callingUserId as their target.
5000                pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER, who.getPackageName());
5001            } catch (RemoteException re) {
5002                // Shouldn't happen
5003            } finally {
5004                restoreCallingIdentity(id);
5005            }
5006        }
5007    }
5008
5009    /**
5010     * @return true if all packages in enabledPackages are either in the list
5011     * permittedList or are a system app.
5012     */
5013    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
5014            List<String> permittedList) {
5015        int userIdToCheck = UserHandle.getCallingUserId();
5016        long id = Binder.clearCallingIdentity();
5017        try {
5018            // If we have an enabled packages list for a managed profile the packages
5019            // we should check are installed for the parent user.
5020            UserInfo user = mUserManager.getUserInfo(userIdToCheck);
5021            if (user.isManagedProfile()) {
5022                userIdToCheck = user.profileGroupId;
5023            }
5024
5025            IPackageManager pm = AppGlobals.getPackageManager();
5026            for (String enabledPackage : enabledPackages) {
5027                boolean systemService = false;
5028                try {
5029                    ApplicationInfo applicationInfo = pm.getApplicationInfo(enabledPackage,
5030                            PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
5031                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5032                } catch (RemoteException e) {
5033                    Log.i(LOG_TAG, "Can't talk to package managed", e);
5034                }
5035                if (!systemService && !permittedList.contains(enabledPackage)) {
5036                    return false;
5037                }
5038            }
5039        } finally {
5040            restoreCallingIdentity(id);
5041        }
5042        return true;
5043    }
5044
5045    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
5046        // Not using AccessibilityManager.getInstance because that guesses
5047        // at the user you require based on callingUid and caches for a given
5048        // process.
5049        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
5050        IAccessibilityManager service = iBinder == null
5051                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
5052        return new AccessibilityManager(mContext, service, userId);
5053    }
5054
5055    @Override
5056    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
5057        if (!mHasFeature) {
5058            return false;
5059        }
5060        Preconditions.checkNotNull(who, "ComponentName is null");
5061
5062        if (packageList != null) {
5063            int userId = UserHandle.getCallingUserId();
5064            List<AccessibilityServiceInfo> enabledServices = null;
5065            long id = Binder.clearCallingIdentity();
5066            try {
5067                UserInfo user = mUserManager.getUserInfo(userId);
5068                if (user.isManagedProfile()) {
5069                    userId = user.profileGroupId;
5070                }
5071                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
5072                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
5073                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
5074            } finally {
5075                restoreCallingIdentity(id);
5076            }
5077
5078            if (enabledServices != null) {
5079                List<String> enabledPackages = new ArrayList<String>();
5080                for (AccessibilityServiceInfo service : enabledServices) {
5081                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
5082                }
5083                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5084                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
5085                            + "because it contains already enabled accesibility services.");
5086                    return false;
5087                }
5088            }
5089        }
5090
5091        synchronized (this) {
5092            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5093                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5094            admin.permittedAccessiblityServices = packageList;
5095            saveSettingsLocked(UserHandle.getCallingUserId());
5096        }
5097        return true;
5098    }
5099
5100    @Override
5101    public List getPermittedAccessibilityServices(ComponentName who) {
5102        if (!mHasFeature) {
5103            return null;
5104        }
5105        Preconditions.checkNotNull(who, "ComponentName is null");
5106
5107        synchronized (this) {
5108            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5109                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5110            return admin.permittedAccessiblityServices;
5111        }
5112    }
5113
5114    @Override
5115    public List getPermittedAccessibilityServicesForUser(int userId) {
5116        if (!mHasFeature) {
5117            return null;
5118        }
5119        synchronized (this) {
5120            List<String> result = null;
5121            // If we have multiple profiles we return the intersection of the
5122            // permitted lists. This can happen in cases where we have a device
5123            // and profile owner.
5124            List<UserInfo> profiles = mUserManager.getProfiles(userId);
5125            final int PROFILES_SIZE = profiles.size();
5126            for (int i = 0; i < PROFILES_SIZE; ++i) {
5127                // Just loop though all admins, only device or profiles
5128                // owners can have permitted lists set.
5129                DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5130                final int N = policy.mAdminList.size();
5131                for (int j = 0; j < N; j++) {
5132                    ActiveAdmin admin = policy.mAdminList.get(j);
5133                    List<String> fromAdmin = admin.permittedAccessiblityServices;
5134                    if (fromAdmin != null) {
5135                        if (result == null) {
5136                            result = new ArrayList<String>(fromAdmin);
5137                        } else {
5138                            result.retainAll(fromAdmin);
5139                        }
5140                    }
5141                }
5142            }
5143
5144            // If we have a permitted list add all system accessibility services.
5145            if (result != null) {
5146                long id = Binder.clearCallingIdentity();
5147                try {
5148                    UserInfo user = mUserManager.getUserInfo(userId);
5149                    if (user.isManagedProfile()) {
5150                        userId = user.profileGroupId;
5151                    }
5152                    AccessibilityManager accessibilityManager =
5153                            getAccessibilityManagerForUser(userId);
5154                    List<AccessibilityServiceInfo> installedServices =
5155                            accessibilityManager.getInstalledAccessibilityServiceList();
5156
5157                    IPackageManager pm = AppGlobals.getPackageManager();
5158                    if (installedServices != null) {
5159                        for (AccessibilityServiceInfo service : installedServices) {
5160                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
5161                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5162                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5163                                result.add(serviceInfo.packageName);
5164                            }
5165                        }
5166                    }
5167                } finally {
5168                    restoreCallingIdentity(id);
5169                }
5170            }
5171
5172            return result;
5173        }
5174    }
5175
5176    private boolean checkCallerIsCurrentUserOrProfile() {
5177        int callingUserId = UserHandle.getCallingUserId();
5178        long token = Binder.clearCallingIdentity();
5179        try {
5180            UserInfo currentUser;
5181            UserInfo callingUser = mUserManager.getUserInfo(callingUserId);
5182            try {
5183                currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5184            } catch (RemoteException e) {
5185                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
5186                return false;
5187            }
5188
5189            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
5190                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
5191                        + "of a user that isn't the foreground user.");
5192                return false;
5193            }
5194            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
5195                Slog.e(LOG_TAG, "Cannot set permitted input methods "
5196                        + "of a user that isn't the foreground user.");
5197                return false;
5198            }
5199        } finally {
5200            Binder.restoreCallingIdentity(token);
5201        }
5202        return true;
5203    }
5204
5205    @Override
5206    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
5207        if (!mHasFeature) {
5208            return false;
5209        }
5210        Preconditions.checkNotNull(who, "ComponentName is null");
5211
5212        // TODO When InputMethodManager supports per user calls remove
5213        //      this restriction.
5214        if (!checkCallerIsCurrentUserOrProfile()) {
5215            return false;
5216        }
5217
5218        if (packageList != null) {
5219            // InputMethodManager fetches input methods for current user.
5220            // So this can only be set when calling user is the current user
5221            // or parent is current user in case of managed profiles.
5222            InputMethodManager inputMethodManager = (InputMethodManager) mContext
5223                    .getSystemService(Context.INPUT_METHOD_SERVICE);
5224            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
5225
5226            if (enabledImes != null) {
5227                List<String> enabledPackages = new ArrayList<String>();
5228                for (InputMethodInfo ime : enabledImes) {
5229                    enabledPackages.add(ime.getPackageName());
5230                }
5231                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList)) {
5232                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
5233                            + "because it contains already enabled input method.");
5234                    return false;
5235                }
5236            }
5237        }
5238
5239        synchronized (this) {
5240            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5241                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5242            admin.permittedInputMethods = packageList;
5243            saveSettingsLocked(UserHandle.getCallingUserId());
5244        }
5245        return true;
5246    }
5247
5248    @Override
5249    public List getPermittedInputMethods(ComponentName who) {
5250        if (!mHasFeature) {
5251            return null;
5252        }
5253        Preconditions.checkNotNull(who, "ComponentName is null");
5254
5255        synchronized (this) {
5256            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5257                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5258            return admin.permittedInputMethods;
5259        }
5260    }
5261
5262    @Override
5263    public List getPermittedInputMethodsForCurrentUser() {
5264        UserInfo currentUser;
5265        try {
5266            currentUser = ActivityManagerNative.getDefault().getCurrentUser();
5267        } catch (RemoteException e) {
5268            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
5269            // Activity managed is dead, just allow all IMEs
5270            return null;
5271        }
5272
5273        int userId = currentUser.id;
5274        synchronized (this) {
5275            List<String> result = null;
5276            // If we have multiple profiles we return the intersection of the
5277            // permitted lists. This can happen in cases where we have a device
5278            // and profile owner.
5279            List<UserInfo> profiles = mUserManager.getProfiles(userId);
5280            final int PROFILES_SIZE = profiles.size();
5281            for (int i = 0; i < PROFILES_SIZE; ++i) {
5282                // Just loop though all admins, only device or profiles
5283                // owners can have permitted lists set.
5284                DevicePolicyData policy = getUserDataUnchecked(profiles.get(i).id);
5285                final int N = policy.mAdminList.size();
5286                for (int j = 0; j < N; j++) {
5287                    ActiveAdmin admin = policy.mAdminList.get(j);
5288                    List<String> fromAdmin = admin.permittedInputMethods;
5289                    if (fromAdmin != null) {
5290                        if (result == null) {
5291                            result = new ArrayList<String>(fromAdmin);
5292                        } else {
5293                            result.retainAll(fromAdmin);
5294                        }
5295                    }
5296                }
5297            }
5298
5299            // If we have a permitted list add all system input methods.
5300            if (result != null) {
5301                InputMethodManager inputMethodManager = (InputMethodManager) mContext
5302                        .getSystemService(Context.INPUT_METHOD_SERVICE);
5303                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
5304                long id = Binder.clearCallingIdentity();
5305                try {
5306                    IPackageManager pm = AppGlobals.getPackageManager();
5307                    if (imes != null) {
5308                        for (InputMethodInfo ime : imes) {
5309                            ServiceInfo serviceInfo = ime.getServiceInfo();
5310                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
5311                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5312                                result.add(serviceInfo.packageName);
5313                            }
5314                        }
5315                    }
5316                } finally {
5317                    restoreCallingIdentity(id);
5318                }
5319            }
5320            return result;
5321        }
5322    }
5323
5324    @Override
5325    public UserHandle createUser(ComponentName who, String name) {
5326        Preconditions.checkNotNull(who, "ComponentName is null");
5327        synchronized (this) {
5328            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5329
5330            long id = Binder.clearCallingIdentity();
5331            try {
5332                UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
5333                if (userInfo != null) {
5334                    return userInfo.getUserHandle();
5335                }
5336                return null;
5337            } finally {
5338                restoreCallingIdentity(id);
5339            }
5340        }
5341    }
5342
5343    @Override
5344    public UserHandle createAndInitializeUser(ComponentName who, String name,
5345            String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
5346        UserHandle user = createUser(who, name);
5347        if (user == null) {
5348            return null;
5349        }
5350        long id = Binder.clearCallingIdentity();
5351        try {
5352            String profileOwnerPkg = profileOwnerComponent.getPackageName();
5353            final IPackageManager ipm = AppGlobals.getPackageManager();
5354            IActivityManager activityManager = ActivityManagerNative.getDefault();
5355
5356            final int userHandle = user.getIdentifier();
5357            try {
5358                // Install the profile owner if not present.
5359                if (!ipm.isPackageAvailable(profileOwnerPkg, userHandle)) {
5360                    ipm.installExistingPackageAsUser(profileOwnerPkg, userHandle);
5361                }
5362
5363                // Start user in background.
5364                activityManager.startUserInBackground(userHandle);
5365            } catch (RemoteException e) {
5366                Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
5367            }
5368
5369            setActiveAdmin(profileOwnerComponent, true, userHandle, adminExtras);
5370            setProfileOwner(profileOwnerComponent, ownerName, userHandle);
5371            return user;
5372        } finally {
5373            restoreCallingIdentity(id);
5374        }
5375    }
5376
5377    @Override
5378    public boolean removeUser(ComponentName who, UserHandle userHandle) {
5379        Preconditions.checkNotNull(who, "ComponentName is null");
5380        synchronized (this) {
5381            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5382
5383            long id = Binder.clearCallingIdentity();
5384            try {
5385                return mUserManager.removeUser(userHandle.getIdentifier());
5386            } finally {
5387                restoreCallingIdentity(id);
5388            }
5389        }
5390    }
5391
5392    @Override
5393    public boolean switchUser(ComponentName who, UserHandle userHandle) {
5394        Preconditions.checkNotNull(who, "ComponentName is null");
5395        synchronized (this) {
5396            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5397
5398            long id = Binder.clearCallingIdentity();
5399            try {
5400                int userId = UserHandle.USER_OWNER;
5401                if (userHandle != null) {
5402                    userId = userHandle.getIdentifier();
5403                }
5404                return ActivityManagerNative.getDefault().switchUser(userId);
5405            } catch (RemoteException e) {
5406                Log.e(LOG_TAG, "Couldn't switch user", e);
5407                return false;
5408            } finally {
5409                restoreCallingIdentity(id);
5410            }
5411        }
5412    }
5413
5414    @Override
5415    public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
5416        Preconditions.checkNotNull(who, "ComponentName is null");
5417        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5418
5419        synchronized (this) {
5420            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5421
5422            long id = Binder.clearCallingIdentity();
5423            try {
5424                Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
5425                // if no restrictions were saved, mUserManager.getApplicationRestrictions
5426                // returns null, but DPM method should return an empty Bundle as per JavaDoc
5427                return bundle != null ? bundle : Bundle.EMPTY;
5428            } finally {
5429                restoreCallingIdentity(id);
5430            }
5431        }
5432    }
5433
5434    @Override
5435    public void setUserRestriction(ComponentName who, String key, boolean enabled) {
5436        Preconditions.checkNotNull(who, "ComponentName is null");
5437        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
5438        final int userHandle = user.getIdentifier();
5439        synchronized (this) {
5440            ActiveAdmin activeAdmin =
5441                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5442            boolean isDeviceOwner = isDeviceOwner(activeAdmin.info.getPackageName());
5443            if (!isDeviceOwner && userHandle != UserHandle.USER_OWNER
5444                    && DEVICE_OWNER_USER_RESTRICTIONS.contains(key)) {
5445                throw new SecurityException("Profile owners cannot set user restriction " + key);
5446            }
5447            if (IMMUTABLE_USER_RESTRICTIONS.contains(key)) {
5448                throw new SecurityException("User restriction " + key + " cannot be changed");
5449            }
5450            boolean alreadyRestricted = mUserManager.hasUserRestriction(key, user);
5451
5452            IAudioService iAudioService = null;
5453            if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)
5454                    || UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5455                iAudioService = IAudioService.Stub.asInterface(
5456                        ServiceManager.getService(Context.AUDIO_SERVICE));
5457            }
5458
5459            long id = Binder.clearCallingIdentity();
5460            try {
5461                if (enabled && !alreadyRestricted) {
5462                    if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5463                        iAudioService.setMicrophoneMute(true, mContext.getPackageName(),
5464                                userHandle);
5465                    } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5466                        iAudioService.setMasterMute(true, 0, mContext.getPackageName(),
5467                                userHandle);
5468                    }
5469                    if (UserManager.DISALLOW_CONFIG_WIFI.equals(key)) {
5470                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5471                                Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0,
5472                                userHandle);
5473                    } else if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5474                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5475                                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF,
5476                                userHandle);
5477                        Settings.Secure.putStringForUser(mContext.getContentResolver(),
5478                                Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "",
5479                                userHandle);
5480                    } else if (UserManager.DISALLOW_DEBUGGING_FEATURES.equals(key)) {
5481                        // Only disable adb if changing for primary user, since it is global
5482                        if (userHandle == UserHandle.USER_OWNER) {
5483                            Settings.Global.putStringForUser(mContext.getContentResolver(),
5484                                    Settings.Global.ADB_ENABLED, "0", userHandle);
5485                        }
5486                    } else if (UserManager.ENSURE_VERIFY_APPS.equals(key)) {
5487                        Settings.Global.putStringForUser(mContext.getContentResolver(),
5488                                Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
5489                                userHandle);
5490                        Settings.Global.putStringForUser(mContext.getContentResolver(),
5491                                Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
5492                                userHandle);
5493                    } else if (UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES.equals(key)) {
5494                        Settings.Secure.putIntForUser(mContext.getContentResolver(),
5495                                Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
5496                                userHandle);
5497                    }
5498                }
5499                mUserManager.setUserRestriction(key, enabled, user);
5500                if (enabled != alreadyRestricted) {
5501                    if (UserManager.DISALLOW_SHARE_LOCATION.equals(key)) {
5502                        // Send out notifications however as some clients may want to reread the
5503                        // value which actually changed due to a restriction having been applied.
5504                        final String property = Settings.Secure.SYS_PROP_SETTING_VERSION;
5505                        long version = SystemProperties.getLong(property, 0) + 1;
5506                        SystemProperties.set(property, Long.toString(version));
5507
5508                        final String name = Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
5509                        Uri url = Uri.withAppendedPath(Settings.Secure.CONTENT_URI, name);
5510                        mContext.getContentResolver().notifyChange(url, null, true, userHandle);
5511                    }
5512                }
5513                if (!enabled && alreadyRestricted) {
5514                    if (UserManager.DISALLOW_UNMUTE_MICROPHONE.equals(key)) {
5515                        iAudioService.setMicrophoneMute(false, mContext.getPackageName(),
5516                                userHandle);
5517                    } else if (UserManager.DISALLOW_ADJUST_VOLUME.equals(key)) {
5518                        iAudioService.setMasterMute(false, 0, mContext.getPackageName(),
5519                                userHandle);
5520                    }
5521                }
5522            } catch (RemoteException re) {
5523                Slog.e(LOG_TAG, "Failed to talk to AudioService.", re);
5524            } finally {
5525                restoreCallingIdentity(id);
5526            }
5527            sendChangedNotification(userHandle);
5528        }
5529    }
5530
5531    @Override
5532    public boolean setApplicationHidden(ComponentName who, String packageName,
5533            boolean hidden) {
5534        Preconditions.checkNotNull(who, "ComponentName is null");
5535        int callingUserId = UserHandle.getCallingUserId();
5536        synchronized (this) {
5537            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5538
5539            long id = Binder.clearCallingIdentity();
5540            try {
5541                IPackageManager pm = AppGlobals.getPackageManager();
5542                return pm.setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
5543            } catch (RemoteException re) {
5544                // shouldn't happen
5545                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
5546            } finally {
5547                restoreCallingIdentity(id);
5548            }
5549            return false;
5550        }
5551    }
5552
5553    @Override
5554    public boolean isApplicationHidden(ComponentName who, String packageName) {
5555        Preconditions.checkNotNull(who, "ComponentName is null");
5556        int callingUserId = UserHandle.getCallingUserId();
5557        synchronized (this) {
5558            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5559
5560            long id = Binder.clearCallingIdentity();
5561            try {
5562                IPackageManager pm = AppGlobals.getPackageManager();
5563                return pm.getApplicationHiddenSettingAsUser(packageName, callingUserId);
5564            } catch (RemoteException re) {
5565                // shouldn't happen
5566                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
5567            } finally {
5568                restoreCallingIdentity(id);
5569            }
5570            return false;
5571        }
5572    }
5573
5574    @Override
5575    public void enableSystemApp(ComponentName who, String packageName) {
5576        Preconditions.checkNotNull(who, "ComponentName is null");
5577        synchronized (this) {
5578            // This API can only be called by an active device admin,
5579            // so try to retrieve it to check that the caller is one.
5580            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5581
5582            int userId = UserHandle.getCallingUserId();
5583            long id = Binder.clearCallingIdentity();
5584
5585            try {
5586                if (DBG) {
5587                    Slog.v(LOG_TAG, "installing " + packageName + " for "
5588                            + userId);
5589                }
5590
5591                UserManager um = UserManager.get(mContext);
5592                UserInfo primaryUser = um.getProfileParent(userId);
5593
5594                // Call did not come from a managed profile
5595                if (primaryUser == null) {
5596                    primaryUser = um.getUserInfo(userId);
5597                }
5598
5599                IPackageManager pm = AppGlobals.getPackageManager();
5600                if (!isSystemApp(pm, packageName, primaryUser.id)) {
5601                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
5602                }
5603
5604                // Install the app.
5605                pm.installExistingPackageAsUser(packageName, userId);
5606
5607            } catch (RemoteException re) {
5608                // shouldn't happen
5609                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
5610            } finally {
5611                restoreCallingIdentity(id);
5612            }
5613        }
5614    }
5615
5616    @Override
5617    public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
5618        Preconditions.checkNotNull(who, "ComponentName is null");
5619        synchronized (this) {
5620            // This API can only be called by an active device admin,
5621            // so try to retrieve it to check that the caller is one.
5622            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5623
5624            int userId = UserHandle.getCallingUserId();
5625            long id = Binder.clearCallingIdentity();
5626
5627            try {
5628                UserManager um = UserManager.get(mContext);
5629                UserInfo primaryUser = um.getProfileParent(userId);
5630
5631                // Call did not come from a managed profile.
5632                if (primaryUser == null) {
5633                    primaryUser = um.getUserInfo(userId);
5634                }
5635
5636                IPackageManager pm = AppGlobals.getPackageManager();
5637                List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
5638                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5639                        0, // no flags
5640                        primaryUser.id);
5641
5642                if (DBG) Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
5643                int numberOfAppsInstalled = 0;
5644                if (activitiesToEnable != null) {
5645                    for (ResolveInfo info : activitiesToEnable) {
5646                        if (info.activityInfo != null) {
5647                            String packageName = info.activityInfo.packageName;
5648                            if (isSystemApp(pm, packageName, primaryUser.id)) {
5649                                numberOfAppsInstalled++;
5650                                pm.installExistingPackageAsUser(packageName, userId);
5651                            } else {
5652                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
5653                                        + " system app");
5654                            }
5655                        }
5656                    }
5657                }
5658                return numberOfAppsInstalled;
5659            } catch (RemoteException e) {
5660                // shouldn't happen
5661                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
5662                return 0;
5663            } finally {
5664                restoreCallingIdentity(id);
5665            }
5666        }
5667    }
5668
5669    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
5670            throws RemoteException {
5671        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
5672                userId);
5673        if (appInfo == null) {
5674            throw new IllegalArgumentException("The application " + packageName +
5675                    " is not present on this device");
5676        }
5677        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5678    }
5679
5680    @Override
5681    public void setAccountManagementDisabled(ComponentName who, String accountType,
5682            boolean disabled) {
5683        if (!mHasFeature) {
5684            return;
5685        }
5686        Preconditions.checkNotNull(who, "ComponentName is null");
5687        synchronized (this) {
5688            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5689                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5690            if (disabled) {
5691                ap.accountTypesWithManagementDisabled.add(accountType);
5692            } else {
5693                ap.accountTypesWithManagementDisabled.remove(accountType);
5694            }
5695            saveSettingsLocked(UserHandle.getCallingUserId());
5696        }
5697    }
5698
5699    @Override
5700    public String[] getAccountTypesWithManagementDisabled() {
5701        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
5702    }
5703
5704    @Override
5705    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
5706        enforceCrossUserPermission(userId);
5707        if (!mHasFeature) {
5708            return null;
5709        }
5710        synchronized (this) {
5711            DevicePolicyData policy = getUserData(userId);
5712            final int N = policy.mAdminList.size();
5713            HashSet<String> resultSet = new HashSet<String>();
5714            for (int i = 0; i < N; i++) {
5715                ActiveAdmin admin = policy.mAdminList.get(i);
5716                resultSet.addAll(admin.accountTypesWithManagementDisabled);
5717            }
5718            return resultSet.toArray(new String[resultSet.size()]);
5719        }
5720    }
5721
5722    @Override
5723    public void setUninstallBlocked(ComponentName who, String packageName,
5724            boolean uninstallBlocked) {
5725        Preconditions.checkNotNull(who, "ComponentName is null");
5726        final int userId = UserHandle.getCallingUserId();
5727        synchronized (this) {
5728            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5729
5730            long id = Binder.clearCallingIdentity();
5731            try {
5732                IPackageManager pm = AppGlobals.getPackageManager();
5733                pm.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
5734            } catch (RemoteException re) {
5735                // Shouldn't happen.
5736                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
5737            } finally {
5738                restoreCallingIdentity(id);
5739            }
5740        }
5741    }
5742
5743    @Override
5744    public boolean isUninstallBlocked(ComponentName who, String packageName) {
5745        // This function should return true if and only if the package is blocked by
5746        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
5747        // when the package is a system app, or when it is an active device admin.
5748        final int userId = UserHandle.getCallingUserId();
5749
5750        synchronized (this) {
5751            if (who != null) {
5752                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5753            }
5754
5755            long id = Binder.clearCallingIdentity();
5756            try {
5757                IPackageManager pm = AppGlobals.getPackageManager();
5758                return pm.getBlockUninstallForUser(packageName, userId);
5759            } catch (RemoteException re) {
5760                // Shouldn't happen.
5761                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
5762            } finally {
5763                restoreCallingIdentity(id);
5764            }
5765        }
5766        return false;
5767    }
5768
5769    @Override
5770    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
5771        if (!mHasFeature) {
5772            return;
5773        }
5774        Preconditions.checkNotNull(who, "ComponentName is null");
5775        synchronized (this) {
5776            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5777                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5778            if (admin.disableCallerId != disabled) {
5779                admin.disableCallerId = disabled;
5780                saveSettingsLocked(UserHandle.getCallingUserId());
5781            }
5782        }
5783    }
5784
5785    @Override
5786    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
5787        if (!mHasFeature) {
5788            return false;
5789        }
5790        Preconditions.checkNotNull(who, "ComponentName is null");
5791        synchronized (this) {
5792            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5793                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5794            return admin.disableCallerId;
5795        }
5796    }
5797
5798    @Override
5799    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
5800        // TODO: Should there be a check to make sure this relationship is within a profile group?
5801        //enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5802        synchronized (this) {
5803            ActiveAdmin admin = getProfileOwnerAdmin(userId);
5804            return (admin != null) ? admin.disableCallerId : false;
5805        }
5806    }
5807
5808    @Override
5809    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
5810            Intent originalIntent) {
5811        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(
5812                actualLookupKey, actualContactId, originalIntent);
5813        final int callingUserId = UserHandle.getCallingUserId();
5814
5815        final long ident = Binder.clearCallingIdentity();
5816        try {
5817            synchronized (this) {
5818                final int managedUserId = getManagedUserId(callingUserId);
5819                if (managedUserId < 0) {
5820                    return;
5821                }
5822                if (getCrossProfileCallerIdDisabledForUser(managedUserId)) {
5823                    if (VERBOSE_LOG) {
5824                        Log.v(LOG_TAG,
5825                                "Cross-profile contacts access disabled for user " + managedUserId);
5826                    }
5827                    return;
5828                }
5829                ContactsInternal.startQuickContactWithErrorToastForUser(
5830                        mContext, intent, new UserHandle(managedUserId));
5831            }
5832        } finally {
5833            Binder.restoreCallingIdentity(ident);
5834        }
5835    }
5836
5837    /**
5838     * @return the user ID of the managed user that is linked to the current user, if any.
5839     * Otherwise -1.
5840     */
5841    public int getManagedUserId(int callingUserId) {
5842        if (VERBOSE_LOG) {
5843            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
5844        }
5845
5846        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
5847            if (ui.id == callingUserId || !ui.isManagedProfile()) {
5848                continue; // Caller user self, or not a managed profile.  Skip.
5849            }
5850            if (VERBOSE_LOG) {
5851                Log.v(LOG_TAG, "Managed user=" + ui.id);
5852            }
5853            return ui.id;
5854        }
5855        if (VERBOSE_LOG) {
5856            Log.v(LOG_TAG, "Managed user not found.");
5857        }
5858        return -1;
5859    }
5860
5861    @Override
5862    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
5863        if (!mHasFeature) {
5864            return;
5865        }
5866        Preconditions.checkNotNull(who, "ComponentName is null");
5867        synchronized (this) {
5868            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5869                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5870            if (admin.disableBluetoothContactSharing != disabled) {
5871                admin.disableBluetoothContactSharing = disabled;
5872                saveSettingsLocked(UserHandle.getCallingUserId());
5873            }
5874        }
5875    }
5876
5877    @Override
5878    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
5879        if (!mHasFeature) {
5880            return false;
5881        }
5882        Preconditions.checkNotNull(who, "ComponentName is null");
5883        synchronized (this) {
5884            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5885                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5886            return admin.disableBluetoothContactSharing;
5887        }
5888    }
5889
5890    @Override
5891    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
5892        // TODO: Should there be a check to make sure this relationship is
5893        // within a profile group?
5894        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
5895        synchronized (this) {
5896            ActiveAdmin admin = getProfileOwnerAdmin(userId);
5897            return (admin != null) ? admin.disableBluetoothContactSharing : false;
5898        }
5899    }
5900
5901    /**
5902     * Sets which packages may enter lock task mode.
5903     *
5904     * This function can only be called by the device owner.
5905     * @param packages The list of packages allowed to enter lock task mode.
5906     */
5907    @Override
5908    public void setLockTaskPackages(ComponentName who, String[] packages)
5909            throws SecurityException {
5910        Preconditions.checkNotNull(who, "ComponentName is null");
5911        synchronized (this) {
5912            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5913
5914            int userHandle = Binder.getCallingUserHandle().getIdentifier();
5915            setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
5916        }
5917    }
5918
5919    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
5920        DevicePolicyData policy = getUserData(userHandle);
5921        policy.mLockTaskPackages = packages;
5922
5923        // Store the settings persistently.
5924        saveSettingsLocked(userHandle);
5925        updateLockTaskPackagesLocked(packages, userHandle);
5926    }
5927
5928    /**
5929     * This function returns the list of components allowed to start the task lock mode.
5930     */
5931    @Override
5932    public String[] getLockTaskPackages(ComponentName who) {
5933        Preconditions.checkNotNull(who, "ComponentName is null");
5934        synchronized (this) {
5935            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5936            int userHandle = Binder.getCallingUserHandle().getIdentifier();
5937            final List<String> packages = getLockTaskPackagesLocked(userHandle);
5938            return packages.toArray(new String[packages.size()]);
5939        }
5940    }
5941
5942    private List<String> getLockTaskPackagesLocked(int userHandle) {
5943        final DevicePolicyData policy = getUserData(userHandle);
5944        return policy.mLockTaskPackages;
5945    }
5946
5947    /**
5948     * This function lets the caller know whether the given package is allowed to start the
5949     * lock task mode.
5950     * @param pkg The package to check
5951     */
5952    @Override
5953    public boolean isLockTaskPermitted(String pkg) {
5954        // Get current user's devicepolicy
5955        int uid = Binder.getCallingUid();
5956        int userHandle = UserHandle.getUserId(uid);
5957        DevicePolicyData policy = getUserData(userHandle);
5958        synchronized (this) {
5959            for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
5960                String lockTaskPackage = policy.mLockTaskPackages.get(i);
5961
5962                // If the given package equals one of the packages stored our list,
5963                // we allow this package to start lock task mode.
5964                if (lockTaskPackage.equals(pkg)) {
5965                    return true;
5966                }
5967            }
5968        }
5969        return false;
5970    }
5971
5972    @Override
5973    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
5974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5975            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
5976        }
5977        synchronized (this) {
5978            final DevicePolicyData policy = getUserData(userHandle);
5979            Bundle adminExtras = new Bundle();
5980            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
5981            for (ActiveAdmin admin : policy.mAdminList) {
5982                boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
5983                boolean ownsProfile = (getProfileOwner(userHandle) != null
5984                        && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
5985                if (ownsDevice || ownsProfile) {
5986                    if (isEnabled) {
5987                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
5988                                adminExtras, null);
5989                    } else {
5990                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
5991                    }
5992                }
5993            }
5994        }
5995    }
5996
5997    @Override
5998    public void setGlobalSetting(ComponentName who, String setting, String value) {
5999        final ContentResolver contentResolver = mContext.getContentResolver();
6000        Preconditions.checkNotNull(who, "ComponentName is null");
6001
6002        synchronized (this) {
6003            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6004
6005            // Some settings are no supported any more. However we do not want to throw a
6006            // SecurityException to avoid breaking apps.
6007            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
6008                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
6009                return;
6010            }
6011
6012            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
6013                throw new SecurityException(String.format(
6014                        "Permission denial: device owners cannot update %1$s", setting));
6015            }
6016
6017            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
6018                // ignore if it contradicts an existing policy
6019                long timeMs = getMaximumTimeToLock(who, UserHandle.getCallingUserId());
6020                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
6021                    return;
6022                }
6023            }
6024
6025            long id = Binder.clearCallingIdentity();
6026            try {
6027                Settings.Global.putString(contentResolver, setting, value);
6028            } finally {
6029                restoreCallingIdentity(id);
6030            }
6031        }
6032    }
6033
6034    @Override
6035    public void setSecureSetting(ComponentName who, String setting, String value) {
6036        Preconditions.checkNotNull(who, "ComponentName is null");
6037        int callingUserId = UserHandle.getCallingUserId();
6038        final ContentResolver contentResolver = mContext.getContentResolver();
6039
6040        synchronized (this) {
6041            ActiveAdmin activeAdmin =
6042                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6043
6044            if (isDeviceOwner(activeAdmin.info.getPackageName())) {
6045                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
6046                    throw new SecurityException(String.format(
6047                            "Permission denial: Device owners cannot update %1$s", setting));
6048                }
6049            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
6050                throw new SecurityException(String.format(
6051                        "Permission denial: Profile owners cannot update %1$s", setting));
6052            }
6053
6054            long id = Binder.clearCallingIdentity();
6055            try {
6056                Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
6057            } finally {
6058                restoreCallingIdentity(id);
6059            }
6060        }
6061    }
6062
6063    @Override
6064    public void setMasterVolumeMuted(ComponentName who, boolean on) {
6065        Preconditions.checkNotNull(who, "ComponentName is null");
6066        synchronized (this) {
6067            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6068            int userId = UserHandle.getCallingUserId();
6069            long identity = Binder.clearCallingIdentity();
6070            try {
6071                IAudioService iAudioService = IAudioService.Stub.asInterface(
6072                        ServiceManager.getService(Context.AUDIO_SERVICE));
6073                iAudioService.setMasterMute(on, 0, mContext.getPackageName(), userId);
6074            } catch (RemoteException re) {
6075                Slog.e(LOG_TAG, "Failed to setMasterMute", re);
6076            } finally {
6077                Binder.restoreCallingIdentity(identity);
6078            }
6079        }
6080    }
6081
6082    @Override
6083    public boolean isMasterVolumeMuted(ComponentName who) {
6084        Preconditions.checkNotNull(who, "ComponentName is null");
6085        synchronized (this) {
6086            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6087
6088            AudioManager audioManager =
6089                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
6090            return audioManager.isMasterMute();
6091        }
6092    }
6093
6094    @Override
6095    public void setUserIcon(ComponentName who, Bitmap icon) {
6096        synchronized (this) {
6097            Preconditions.checkNotNull(who, "ComponentName is null");
6098            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6099
6100            int userId = UserHandle.getCallingUserId();
6101            long id = Binder.clearCallingIdentity();
6102            try {
6103                mUserManager.setUserIcon(userId, icon);
6104            } finally {
6105                restoreCallingIdentity(id);
6106            }
6107        }
6108    }
6109
6110    @Override
6111    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
6112        Preconditions.checkNotNull(who, "ComponentName is null");
6113        synchronized (this) {
6114            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6115        }
6116        final int userId = UserHandle.getCallingUserId();
6117        LockPatternUtils utils = new LockPatternUtils(mContext);
6118
6119        long ident = Binder.clearCallingIdentity();
6120        try {
6121            // disallow disabling the keyguard if a password is currently set
6122            if (disabled && utils.isSecure(userId)) {
6123                return false;
6124            }
6125            utils.setLockScreenDisabled(disabled, userId);
6126        } finally {
6127            Binder.restoreCallingIdentity(ident);
6128        }
6129        return true;
6130    }
6131
6132    @Override
6133    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
6134        int userId = UserHandle.getCallingUserId();
6135        synchronized (this) {
6136            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6137            DevicePolicyData policy = getUserData(userId);
6138            if (policy.mStatusBarDisabled != disabled) {
6139                if (!setStatusBarDisabledInternal(disabled, userId)) {
6140                    return false;
6141                }
6142                policy.mStatusBarDisabled = disabled;
6143                saveSettingsLocked(userId);
6144            }
6145        }
6146        return true;
6147    }
6148
6149    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
6150        long ident = Binder.clearCallingIdentity();
6151        try {
6152            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
6153                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
6154            if (statusBarService != null) {
6155                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
6156                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
6157                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
6158                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
6159                return true;
6160            }
6161        } catch (RemoteException e) {
6162            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
6163        } finally {
6164            Binder.restoreCallingIdentity(ident);
6165        }
6166        return false;
6167    }
6168
6169    /**
6170     * We need to update the internal state of whether a user has completed setup once. After
6171     * that, we ignore any changes that reset the Settings.Secure.USER_SETUP_COMPLETE changes
6172     * as we don't trust any apps that might try to reset it.
6173     * <p>
6174     * Unfortunately, we don't know which user's setup state was changed, so we write all of
6175     * them.
6176     */
6177    void updateUserSetupComplete() {
6178        List<UserInfo> users = mUserManager.getUsers(true);
6179        ContentResolver resolver = mContext.getContentResolver();
6180        final int N = users.size();
6181        for (int i = 0; i < N; i++) {
6182            int userHandle = users.get(i).id;
6183            if (Settings.Secure.getIntForUser(resolver, Settings.Secure.USER_SETUP_COMPLETE, 0,
6184                    userHandle) != 0) {
6185                DevicePolicyData policy = getUserData(userHandle);
6186                if (!policy.mUserSetupComplete) {
6187                    policy.mUserSetupComplete = true;
6188                    synchronized (this) {
6189                        // The DeviceInitializer was whitelisted but now should be removed.
6190                        removeDeviceInitializerFromLockTaskPackages(userHandle);
6191                        saveSettingsLocked(userHandle);
6192                    }
6193                }
6194            }
6195        }
6196    }
6197
6198    private void addDeviceInitializerToLockTaskPackagesLocked(int userHandle) {
6199        if (hasUserSetupCompleted(userHandle)) {
6200            return;
6201        }
6202
6203        final String deviceInitializerPackage = getDeviceInitializer();
6204        if (deviceInitializerPackage == null) {
6205            return;
6206        }
6207
6208        final List<String> packages = getLockTaskPackagesLocked(userHandle);
6209        if (!packages.contains(deviceInitializerPackage)) {
6210            packages.add(deviceInitializerPackage);
6211            setLockTaskPackagesLocked(userHandle, packages);
6212        }
6213    }
6214
6215    private void removeDeviceInitializerFromLockTaskPackages(int userHandle) {
6216        final String deviceInitializerPackage = getDeviceInitializer();
6217        if (deviceInitializerPackage == null) {
6218            return;
6219        }
6220
6221        List<String> packages = getLockTaskPackagesLocked(userHandle);
6222        if (packages.remove(deviceInitializerPackage)) {
6223            setLockTaskPackagesLocked(userHandle, packages);
6224        }
6225    }
6226
6227    private class SetupContentObserver extends ContentObserver {
6228
6229        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
6230                Settings.Secure.USER_SETUP_COMPLETE);
6231
6232        public SetupContentObserver(Handler handler) {
6233            super(handler);
6234        }
6235
6236        void register(ContentResolver resolver) {
6237            resolver.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
6238        }
6239
6240        @Override
6241        public void onChange(boolean selfChange, Uri uri) {
6242            if (mUserSetupComplete.equals(uri)) {
6243                updateUserSetupComplete();
6244            }
6245        }
6246    }
6247
6248    private final class LocalService extends DevicePolicyManagerInternal {
6249        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
6250
6251        @Override
6252        public List<String> getCrossProfileWidgetProviders(int profileId) {
6253            synchronized (DevicePolicyManagerService.this) {
6254                if (mDeviceOwner == null) {
6255                    return Collections.emptyList();
6256                }
6257                ComponentName ownerComponent = mDeviceOwner.getProfileOwnerComponent(profileId);
6258                if (ownerComponent == null) {
6259                    return Collections.emptyList();
6260                }
6261
6262                DevicePolicyData policy = getUserDataUnchecked(profileId);
6263                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
6264
6265                if (admin == null || admin.crossProfileWidgetProviders == null
6266                        || admin.crossProfileWidgetProviders.isEmpty()) {
6267                    return Collections.emptyList();
6268                }
6269
6270                return admin.crossProfileWidgetProviders;
6271            }
6272        }
6273
6274        @Override
6275        public void addOnCrossProfileWidgetProvidersChangeListener(
6276                OnCrossProfileWidgetProvidersChangeListener listener) {
6277            synchronized (DevicePolicyManagerService.this) {
6278                if (mWidgetProviderListeners == null) {
6279                    mWidgetProviderListeners = new ArrayList<>();
6280                }
6281                if (!mWidgetProviderListeners.contains(listener)) {
6282                    mWidgetProviderListeners.add(listener);
6283                }
6284            }
6285        }
6286
6287        @Override
6288        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
6289            final int userId = UserHandle.getUserId(uid);
6290            synchronized(DevicePolicyManagerService.this) {
6291                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
6292            }
6293        }
6294
6295        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
6296            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
6297            synchronized (DevicePolicyManagerService.this) {
6298                listeners = new ArrayList<>(mWidgetProviderListeners);
6299            }
6300            final int listenerCount = listeners.size();
6301            for (int i = 0; i < listenerCount; i++) {
6302                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
6303                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
6304            }
6305        }
6306    }
6307
6308    /**
6309     * Returns true if specified admin is allowed to limit passwords and has a
6310     * {@code passwordQuality} of at least {@code minPasswordQuality}
6311     */
6312    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
6313        if (admin.passwordQuality < minPasswordQuality) {
6314            return false;
6315        }
6316        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
6317    }
6318
6319    @Override
6320    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
6321        if (policy != null && !policy.isValid()) {
6322            throw new IllegalArgumentException("Invalid system update policy.");
6323        }
6324        synchronized (this) {
6325            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6326            if (policy == null) {
6327                mDeviceOwner.clearSystemUpdatePolicy();
6328            } else {
6329                mDeviceOwner.setSystemUpdatePolicy(policy);
6330            }
6331            mDeviceOwner.writeOwnerFile();
6332        }
6333        mContext.sendBroadcastAsUser(
6334                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
6335                UserHandle.OWNER);
6336    }
6337
6338    @Override
6339    public SystemUpdatePolicy getSystemUpdatePolicy() {
6340        synchronized (this) {
6341            SystemUpdatePolicy policy =  mDeviceOwner.getSystemUpdatePolicy();
6342            if (policy != null && !policy.isValid()) {
6343                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
6344                return null;
6345            }
6346            return policy;
6347        }
6348    }
6349
6350    /**
6351     * Checks if the caller of the method is the device owner app or device initialization app.
6352     *
6353     * @param callerUid UID of the caller.
6354     * @return true if the caller is the device owner app or device initializer.
6355     */
6356    private boolean isCallerDeviceOwnerOrInitializer(int callerUid) {
6357        String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
6358        for (String pkg : pkgs) {
6359            if (isDeviceOwner(pkg) || isDeviceInitializer(pkg)) {
6360                return true;
6361            }
6362        }
6363        return false;
6364    }
6365
6366    @Override
6367    public void notifyPendingSystemUpdate(long updateReceivedTime) {
6368        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
6369                "Only the system update service can broadcast update information");
6370
6371        if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
6372            Slog.w(LOG_TAG, "Only the system update service in the primary user" +
6373                    "can broadcast update information.");
6374            return;
6375        }
6376        Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
6377        intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
6378                updateReceivedTime);
6379
6380        synchronized (this) {
6381            String deviceOwnerPackage = getDeviceOwner();
6382            if (deviceOwnerPackage == null) {
6383                return;
6384            }
6385
6386            ActivityInfo[] receivers = null;
6387            try {
6388                receivers  = mContext.getPackageManager().getPackageInfo(
6389                        deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
6390            } catch (NameNotFoundException e) {
6391                Log.e(LOG_TAG, "Cannot find device owner package", e);
6392            }
6393            if (receivers != null) {
6394                long ident = Binder.clearCallingIdentity();
6395                try {
6396                    for (int i = 0; i < receivers.length; i++) {
6397                        if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
6398                            intent.setComponent(new ComponentName(deviceOwnerPackage,
6399                                    receivers[i].name));
6400                            mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
6401                        }
6402                    }
6403                } finally {
6404                    Binder.restoreCallingIdentity(ident);
6405                }
6406            }
6407        }
6408    }
6409
6410    @Override
6411    public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
6412        int userId = UserHandle.getCallingUserId();
6413        synchronized (this) {
6414            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6415            DevicePolicyData userPolicy = getUserData(userId);
6416            if (userPolicy.mPermissionPolicy != policy) {
6417                userPolicy.mPermissionPolicy = policy;
6418                saveSettingsLocked(userId);
6419            }
6420        }
6421    }
6422
6423    @Override
6424    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
6425        int userId = UserHandle.getCallingUserId();
6426        synchronized (this) {
6427            DevicePolicyData userPolicy = getUserData(userId);
6428            return userPolicy.mPermissionPolicy;
6429        }
6430    }
6431
6432    @Override
6433    public boolean setPermissionGrantState(ComponentName admin, String packageName,
6434            String permission, int grantState) throws RemoteException {
6435        UserHandle user = Binder.getCallingUserHandle();
6436        synchronized (this) {
6437            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6438            long ident = Binder.clearCallingIdentity();
6439            try {
6440                final ApplicationInfo ai = AppGlobals.getPackageManager()
6441                        .getApplicationInfo(packageName, 0, user.getIdentifier());
6442                final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
6443                if (targetSdkVersion < android.os.Build.VERSION_CODES.M) {
6444                    return false;
6445                }
6446                final PackageManager packageManager = mContext.getPackageManager();
6447                switch (grantState) {
6448                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
6449                        packageManager.grantRuntimePermission(packageName, permission, user);
6450                        packageManager.updatePermissionFlags(permission, packageName,
6451                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6452                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6453                    } break;
6454
6455                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
6456                        packageManager.revokeRuntimePermission(packageName,
6457                                permission, user);
6458                        packageManager.updatePermissionFlags(permission, packageName,
6459                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6460                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
6461                    } break;
6462
6463                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
6464                        packageManager.updatePermissionFlags(permission, packageName,
6465                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
6466                    } break;
6467                }
6468                return true;
6469            } catch (SecurityException se) {
6470                return false;
6471            } finally {
6472                Binder.restoreCallingIdentity(ident);
6473            }
6474        }
6475    }
6476
6477    @Override
6478    public int getPermissionGrantState(ComponentName admin, String packageName,
6479            String permission) throws RemoteException {
6480        PackageManager packageManager = mContext.getPackageManager();
6481
6482        UserHandle user = Binder.getCallingUserHandle();
6483        synchronized (this) {
6484            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6485            long ident = Binder.clearCallingIdentity();
6486            try {
6487                int granted = AppGlobals.getPackageManager().checkPermission(permission,
6488                        packageName, user.getIdentifier());
6489                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
6490                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
6491                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
6492                    // Not controlled by policy
6493                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
6494                } else {
6495                    // Policy controlled so return result based on permission grant state
6496                    return granted == PackageManager.PERMISSION_GRANTED
6497                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
6498                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
6499                }
6500            } finally {
6501                Binder.restoreCallingIdentity(ident);
6502            }
6503        }
6504    }
6505}
6506