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