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