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