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