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