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