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