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