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