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