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