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