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