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