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