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