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