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