DevicePolicyManagerService.java revision 35c62a4668a85aa4318c9ec564f2e06e8a2d2a30
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<ComponentName> mLockTaskComponents = new ArrayList<ComponentName>();
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.mLockTaskComponents.size(); i++) {
1018                ComponentName component = policy.mLockTaskComponents.get(i);
1019                out.startTag(null, LOCK_TASK_COMPONENTS_XML);
1020                out.attribute(null, "name", component.flattenToString());
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.mLockTaskComponents.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.mLockTaskComponents.add
1135                        (ComponentName.unflattenFromString
1136                         (parser.getAttributeValue(null, "name")));
1137                    XmlUtils.skipCurrentTag(parser);
1138                } else {
1139                    Slog.w(LOG_TAG, "Unknown tag: " + tag);
1140                    XmlUtils.skipCurrentTag(parser);
1141                }
1142            }
1143        } catch (NullPointerException e) {
1144            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1145        } catch (NumberFormatException e) {
1146            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1147        } catch (XmlPullParserException e) {
1148            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1149        } catch (FileNotFoundException e) {
1150            // Don't be noisy, this is normal if we haven't defined any policies.
1151        } catch (IOException e) {
1152            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1153        } catch (IndexOutOfBoundsException e) {
1154            Slog.w(LOG_TAG, "failed parsing " + file + " " + e);
1155        }
1156        try {
1157            if (stream != null) {
1158                stream.close();
1159            }
1160        } catch (IOException e) {
1161            // Ignore
1162        }
1163
1164        // Validate that what we stored for the password quality matches
1165        // sufficiently what is currently set.  Note that this is only
1166        // a sanity check in case the two get out of sync; this should
1167        // never normally happen.
1168        LockPatternUtils utils = new LockPatternUtils(mContext);
1169        if (utils.getActivePasswordQuality() < policy.mActivePasswordQuality) {
1170            Slog.w(LOG_TAG, "Active password quality 0x"
1171                    + Integer.toHexString(policy.mActivePasswordQuality)
1172                    + " does not match actual quality 0x"
1173                    + Integer.toHexString(utils.getActivePasswordQuality()));
1174            policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1175            policy.mActivePasswordLength = 0;
1176            policy.mActivePasswordUpperCase = 0;
1177            policy.mActivePasswordLowerCase = 0;
1178            policy.mActivePasswordLetters = 0;
1179            policy.mActivePasswordNumeric = 0;
1180            policy.mActivePasswordSymbols = 0;
1181            policy.mActivePasswordNonLetter = 0;
1182        }
1183
1184        validatePasswordOwnerLocked(policy);
1185        syncDeviceCapabilitiesLocked(policy);
1186        updateMaximumTimeToLockLocked(policy);
1187    }
1188
1189    static void validateQualityConstant(int quality) {
1190        switch (quality) {
1191            case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
1192            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
1193            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1194            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1195            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1196            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1197            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1198                return;
1199        }
1200        throw new IllegalArgumentException("Invalid quality constant: 0x"
1201                + Integer.toHexString(quality));
1202    }
1203
1204    void validatePasswordOwnerLocked(DevicePolicyData policy) {
1205        if (policy.mPasswordOwner >= 0) {
1206            boolean haveOwner = false;
1207            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1208                if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
1209                    haveOwner = true;
1210                    break;
1211                }
1212            }
1213            if (!haveOwner) {
1214                Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
1215                        + " no longer active; disabling");
1216                policy.mPasswordOwner = -1;
1217            }
1218        }
1219    }
1220
1221    /**
1222     * Pushes down policy information to the system for any policies related to general device
1223     * capabilities that need to be enforced by lower level services (e.g. Camera services).
1224     */
1225    void syncDeviceCapabilitiesLocked(DevicePolicyData policy) {
1226        // Ensure the status of the camera is synced down to the system. Interested native services
1227        // should monitor this value and act accordingly.
1228        boolean systemState = SystemProperties.getBoolean(SYSTEM_PROP_DISABLE_CAMERA, false);
1229        boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle);
1230        if (cameraDisabled != systemState) {
1231            long token = Binder.clearCallingIdentity();
1232            try {
1233                String value = cameraDisabled ? "1" : "0";
1234                if (DBG) Slog.v(LOG_TAG, "Change in camera state ["
1235                        + SYSTEM_PROP_DISABLE_CAMERA + "] = " + value);
1236                SystemProperties.set(SYSTEM_PROP_DISABLE_CAMERA, value);
1237            } finally {
1238                Binder.restoreCallingIdentity(token);
1239            }
1240        }
1241    }
1242
1243    public void systemReady() {
1244        if (!mHasFeature) {
1245            return;
1246        }
1247        synchronized (this) {
1248            loadSettingsLocked(getUserData(UserHandle.USER_OWNER), UserHandle.USER_OWNER);
1249            loadDeviceOwner();
1250        }
1251        cleanUpOldUsers();
1252        mAppOpsService = IAppOpsService.Stub.asInterface(
1253                ServiceManager.getService(Context.APP_OPS_SERVICE));
1254        if (mDeviceOwner != null) {
1255            if (mDeviceOwner.hasDeviceOwner()) {
1256                try {
1257                    mAppOpsService.setDeviceOwner(mDeviceOwner.getDeviceOwnerPackageName());
1258                } catch (RemoteException e) {
1259                    Log.w(LOG_TAG, "Unable to notify AppOpsService of DeviceOwner", e);
1260                }
1261            }
1262            for (Integer i : mDeviceOwner.getProfileOwnerKeys()) {
1263                try {
1264                    mAppOpsService.setProfileOwner(mDeviceOwner.getProfileOwnerPackageName(i), i);
1265                } catch (RemoteException e) {
1266                    Log.w(LOG_TAG, "Unable to notify AppOpsService of ProfileOwner", e);
1267                }
1268            }
1269        }
1270    }
1271
1272    private void cleanUpOldUsers() {
1273        // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
1274        // before reboot
1275        Set<Integer> usersWithProfileOwners;
1276        Set<Integer> usersWithData;
1277        synchronized(this) {
1278            usersWithProfileOwners = mDeviceOwner != null
1279                    ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>();
1280            usersWithData = new HashSet<Integer>();
1281            for (int i = 0; i < mUserData.size(); i++) {
1282                usersWithData.add(mUserData.keyAt(i));
1283            }
1284        }
1285        List<UserInfo> allUsers = mUserManager.getUsers();
1286
1287        Set<Integer> deletedUsers = new HashSet<Integer>();
1288        deletedUsers.addAll(usersWithProfileOwners);
1289        deletedUsers.addAll(usersWithData);
1290        for (UserInfo userInfo : allUsers) {
1291            deletedUsers.remove(userInfo.id);
1292        }
1293        for (Integer userId : deletedUsers) {
1294            removeUserData(userId);
1295        }
1296    }
1297
1298    private void handlePasswordExpirationNotification(int userHandle) {
1299        synchronized (this) {
1300            final long now = System.currentTimeMillis();
1301
1302            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1303            for (UserInfo ui : profiles) {
1304                int profileUserHandle = ui.getUserHandle().getIdentifier();
1305                final DevicePolicyData policy = getUserData(profileUserHandle);
1306                final int count = policy.mAdminList.size();
1307                if (count > 0) {
1308                    for (int i = 0; i < count; i++) {
1309                        final ActiveAdmin admin = policy.mAdminList.get(i);
1310                        if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
1311                                && admin.passwordExpirationTimeout > 0L
1312                                && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
1313                                && admin.passwordExpirationDate > 0L) {
1314                            sendAdminCommandLocked(admin,
1315                                    DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
1316                        }
1317                    }
1318                }
1319            }
1320            setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1321        }
1322    }
1323
1324    private void manageMonitoringCertificateNotification(Intent intent) {
1325        final NotificationManager notificationManager = getNotificationManager();
1326
1327        final boolean hasCert = DevicePolicyManager.hasAnyCaCertsInstalled();
1328        if (! hasCert) {
1329            if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) {
1330                for (UserInfo user : mUserManager.getUsers()) {
1331                    notificationManager.cancelAsUser(
1332                            null, MONITORING_CERT_NOTIFICATION_ID, user.getUserHandle());
1333                }
1334            }
1335            return;
1336        }
1337        final boolean isManaged = getDeviceOwner() != null;
1338        int smallIconId;
1339        String contentText;
1340        if (isManaged) {
1341            contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
1342                    getDeviceOwnerName());
1343            smallIconId = R.drawable.stat_sys_certificate_info;
1344        } else {
1345            contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
1346            smallIconId = android.R.drawable.stat_sys_warning;
1347        }
1348
1349        Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
1350        dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1351        dialogIntent.setPackage("com.android.settings");
1352        // Notification will be sent individually to all users. The activity should start as
1353        // whichever user is current when it starts.
1354        PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0, dialogIntent,
1355                PendingIntent.FLAG_UPDATE_CURRENT, null, UserHandle.CURRENT);
1356
1357        Notification noti = new Notification.Builder(mContext)
1358            .setSmallIcon(smallIconId)
1359            .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning))
1360            .setContentText(contentText)
1361            .setContentIntent(notifyIntent)
1362            .setPriority(Notification.PRIORITY_HIGH)
1363            .setShowWhen(false)
1364            .build();
1365
1366        // If this is a boot intent, this will fire for each user. But if this is a storage changed
1367        // intent, it will fire once, so we need to notify all users.
1368        if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) {
1369            for (UserInfo user : mUserManager.getUsers()) {
1370                notificationManager.notifyAsUser(
1371                        null, MONITORING_CERT_NOTIFICATION_ID, noti, user.getUserHandle());
1372            }
1373        } else {
1374            notificationManager.notifyAsUser(
1375                    null, MONITORING_CERT_NOTIFICATION_ID, noti, UserHandle.CURRENT);
1376        }
1377    }
1378
1379    /**
1380     * @param adminReceiver The admin to add
1381     * @param refreshing true = update an active admin, no error
1382     */
1383    public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
1384        if (!mHasFeature) {
1385            return;
1386        }
1387        setActiveAdmin(adminReceiver, refreshing, userHandle, null);
1388    }
1389
1390    private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
1391            Bundle onEnableData) {
1392        mContext.enforceCallingOrSelfPermission(
1393                android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1394        enforceCrossUserPermission(userHandle);
1395
1396        DevicePolicyData policy = getUserData(userHandle);
1397        DeviceAdminInfo info = findAdmin(adminReceiver, userHandle);
1398        if (info == null) {
1399            throw new IllegalArgumentException("Bad admin: " + adminReceiver);
1400        }
1401        synchronized (this) {
1402            long ident = Binder.clearCallingIdentity();
1403            try {
1404                if (!refreshing
1405                        && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) {
1406                    throw new IllegalArgumentException("Admin is already added");
1407                }
1408                ActiveAdmin newAdmin = new ActiveAdmin(info);
1409                policy.mAdminMap.put(adminReceiver, newAdmin);
1410                int replaceIndex = -1;
1411                if (refreshing) {
1412                    final int N = policy.mAdminList.size();
1413                    for (int i=0; i < N; i++) {
1414                        ActiveAdmin oldAdmin = policy.mAdminList.get(i);
1415                        if (oldAdmin.info.getComponent().equals(adminReceiver)) {
1416                            replaceIndex = i;
1417                            break;
1418                        }
1419                    }
1420                }
1421                if (replaceIndex == -1) {
1422                    policy.mAdminList.add(newAdmin);
1423                    enableIfNecessary(info.getPackageName(), userHandle);
1424                } else {
1425                    policy.mAdminList.set(replaceIndex, newAdmin);
1426                }
1427                saveSettingsLocked(userHandle);
1428                sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
1429                        onEnableData, null);
1430            } finally {
1431                Binder.restoreCallingIdentity(ident);
1432            }
1433        }
1434    }
1435
1436    public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
1437        if (!mHasFeature) {
1438            return false;
1439        }
1440        enforceCrossUserPermission(userHandle);
1441        synchronized (this) {
1442            return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
1443        }
1444    }
1445
1446    public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
1447        if (!mHasFeature) {
1448            return false;
1449        }
1450        enforceCrossUserPermission(userHandle);
1451        synchronized (this) {
1452            ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1453            if (administrator == null) {
1454                throw new SecurityException("No active admin " + adminReceiver);
1455            }
1456            return administrator.info.usesPolicy(policyId);
1457        }
1458    }
1459
1460    @SuppressWarnings("unchecked")
1461    public List<ComponentName> getActiveAdmins(int userHandle) {
1462        if (!mHasFeature) {
1463            return Collections.EMPTY_LIST;
1464        }
1465
1466        enforceCrossUserPermission(userHandle);
1467        synchronized (this) {
1468            DevicePolicyData policy = getUserData(userHandle);
1469            final int N = policy.mAdminList.size();
1470            if (N <= 0) {
1471                return null;
1472            }
1473            ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
1474            for (int i=0; i<N; i++) {
1475                res.add(policy.mAdminList.get(i).info.getComponent());
1476            }
1477            return res;
1478        }
1479    }
1480
1481    public boolean packageHasActiveAdmins(String packageName, int userHandle) {
1482        if (!mHasFeature) {
1483            return false;
1484        }
1485        enforceCrossUserPermission(userHandle);
1486        synchronized (this) {
1487            DevicePolicyData policy = getUserData(userHandle);
1488            final int N = policy.mAdminList.size();
1489            for (int i=0; i<N; i++) {
1490                if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
1491                    return true;
1492                }
1493            }
1494            return false;
1495        }
1496    }
1497
1498    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
1499        if (!mHasFeature) {
1500            return;
1501        }
1502        enforceCrossUserPermission(userHandle);
1503        synchronized (this) {
1504            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
1505            if (admin == null) {
1506                return;
1507            }
1508            if (admin.getUid() != Binder.getCallingUid()) {
1509                // If trying to remove device owner, refuse when the caller is not the owner.
1510                if (isDeviceOwner(adminReceiver.getPackageName())) {
1511                    return;
1512                }
1513                mContext.enforceCallingOrSelfPermission(
1514                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
1515            }
1516            long ident = Binder.clearCallingIdentity();
1517            try {
1518                removeActiveAdminLocked(adminReceiver, userHandle);
1519            } finally {
1520                Binder.restoreCallingIdentity(ident);
1521            }
1522        }
1523    }
1524
1525    public void setPasswordQuality(ComponentName who, int quality, int userHandle) {
1526        if (!mHasFeature) {
1527            return;
1528        }
1529        validateQualityConstant(quality);
1530        enforceCrossUserPermission(userHandle);
1531
1532        synchronized (this) {
1533            if (who == null) {
1534                throw new NullPointerException("ComponentName is null");
1535            }
1536            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1537                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1538            if (ap.passwordQuality != quality) {
1539                ap.passwordQuality = quality;
1540                saveSettingsLocked(userHandle);
1541            }
1542        }
1543    }
1544
1545    public int getPasswordQuality(ComponentName who, int userHandle) {
1546        if (!mHasFeature) {
1547            return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1548        }
1549        enforceCrossUserPermission(userHandle);
1550        synchronized (this) {
1551            int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
1552
1553            if (who != null) {
1554                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1555                return admin != null ? admin.passwordQuality : mode;
1556            }
1557
1558            // Return strictest policy for this user and profiles that are visible from this user.
1559            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1560            for (UserInfo userInfo : profiles) {
1561                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1562                final int N = policy.mAdminList.size();
1563                for (int i=0; i<N; i++) {
1564                    ActiveAdmin admin = policy.mAdminList.get(i);
1565                    if (mode < admin.passwordQuality) {
1566                        mode = admin.passwordQuality;
1567                    }
1568                }
1569            }
1570            return mode;
1571        }
1572    }
1573
1574    public void setPasswordMinimumLength(ComponentName who, int length, int userHandle) {
1575        if (!mHasFeature) {
1576            return;
1577        }
1578        enforceCrossUserPermission(userHandle);
1579        synchronized (this) {
1580            if (who == null) {
1581                throw new NullPointerException("ComponentName is null");
1582            }
1583            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1584                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1585            if (ap.minimumPasswordLength != length) {
1586                ap.minimumPasswordLength = length;
1587                saveSettingsLocked(userHandle);
1588            }
1589        }
1590    }
1591
1592    public int getPasswordMinimumLength(ComponentName who, int userHandle) {
1593        if (!mHasFeature) {
1594            return 0;
1595        }
1596        enforceCrossUserPermission(userHandle);
1597        synchronized (this) {
1598            int length = 0;
1599
1600            if (who != null) {
1601                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1602                return admin != null ? admin.minimumPasswordLength : length;
1603            }
1604
1605            // Return strictest policy for this user and profiles that are visible from this user.
1606            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1607            for (UserInfo userInfo : profiles) {
1608                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1609                final int N = policy.mAdminList.size();
1610                for (int i=0; i<N; i++) {
1611                    ActiveAdmin admin = policy.mAdminList.get(i);
1612                    if (length < admin.minimumPasswordLength) {
1613                        length = admin.minimumPasswordLength;
1614                    }
1615                }
1616            }
1617            return length;
1618        }
1619    }
1620
1621    public void setPasswordHistoryLength(ComponentName who, int length, int userHandle) {
1622        if (!mHasFeature) {
1623            return;
1624        }
1625        enforceCrossUserPermission(userHandle);
1626        synchronized (this) {
1627            if (who == null) {
1628                throw new NullPointerException("ComponentName is null");
1629            }
1630            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1631                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1632            if (ap.passwordHistoryLength != length) {
1633                ap.passwordHistoryLength = length;
1634                saveSettingsLocked(userHandle);
1635            }
1636        }
1637    }
1638
1639    public int getPasswordHistoryLength(ComponentName who, int userHandle) {
1640        if (!mHasFeature) {
1641            return 0;
1642        }
1643        enforceCrossUserPermission(userHandle);
1644        synchronized (this) {
1645            int length = 0;
1646
1647            if (who != null) {
1648                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1649                return admin != null ? admin.passwordHistoryLength : length;
1650            }
1651
1652            // Return strictest policy for this user and profiles that are visible from this user.
1653            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1654            for (UserInfo userInfo : profiles) {
1655                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1656                final int N = policy.mAdminList.size();
1657                for (int i = 0; i < N; i++) {
1658                    ActiveAdmin admin = policy.mAdminList.get(i);
1659                    if (length < admin.passwordHistoryLength) {
1660                        length = admin.passwordHistoryLength;
1661                    }
1662                }
1663            }
1664            return length;
1665        }
1666    }
1667
1668    public void setPasswordExpirationTimeout(ComponentName who, long timeout, int userHandle) {
1669        if (!mHasFeature) {
1670            return;
1671        }
1672        enforceCrossUserPermission(userHandle);
1673        synchronized (this) {
1674            if (who == null) {
1675                throw new NullPointerException("ComponentName is null");
1676            }
1677            if (timeout < 0) {
1678                throw new IllegalArgumentException("Timeout must be >= 0 ms");
1679            }
1680            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1681                    DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
1682            // Calling this API automatically bumps the expiration date
1683            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
1684            ap.passwordExpirationDate = expiration;
1685            ap.passwordExpirationTimeout = timeout;
1686            if (timeout > 0L) {
1687                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
1688                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
1689                        .format(new Date(expiration)));
1690            }
1691            saveSettingsLocked(userHandle);
1692            // in case this is the first one
1693            setExpirationAlarmCheckLocked(mContext, getUserData(userHandle));
1694        }
1695    }
1696
1697    /**
1698     * Return a single admin's expiration cycle time, or the min of all cycle times.
1699     * Returns 0 if not configured.
1700     */
1701    public long getPasswordExpirationTimeout(ComponentName who, int userHandle) {
1702        if (!mHasFeature) {
1703            return 0L;
1704        }
1705        enforceCrossUserPermission(userHandle);
1706        synchronized (this) {
1707            long timeout = 0L;
1708
1709            if (who != null) {
1710                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1711                return admin != null ? admin.passwordExpirationTimeout : timeout;
1712            }
1713
1714            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1715            for (UserInfo userInfo : profiles) {
1716                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1717                final int N = policy.mAdminList.size();
1718                for (int i = 0; i < N; i++) {
1719                    ActiveAdmin admin = policy.mAdminList.get(i);
1720                    if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
1721                            && timeout > admin.passwordExpirationTimeout)) {
1722                        timeout = admin.passwordExpirationTimeout;
1723                    }
1724                }
1725            }
1726            return timeout;
1727        }
1728    }
1729
1730    /**
1731     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
1732     * Returns 0 if not configured.
1733     */
1734    private long getPasswordExpirationLocked(ComponentName who, int userHandle) {
1735        long timeout = 0L;
1736
1737        if (who != null) {
1738            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1739            return admin != null ? admin.passwordExpirationDate : timeout;
1740        }
1741
1742        List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1743        for (UserInfo userInfo : profiles) {
1744            DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1745            final int N = policy.mAdminList.size();
1746            for (int i = 0; i < N; i++) {
1747                ActiveAdmin admin = policy.mAdminList.get(i);
1748                if (timeout == 0L || (admin.passwordExpirationDate != 0
1749                        && timeout > admin.passwordExpirationDate)) {
1750                    timeout = admin.passwordExpirationDate;
1751                }
1752            }
1753        }
1754        return timeout;
1755    }
1756
1757    public long getPasswordExpiration(ComponentName who, int userHandle) {
1758        if (!mHasFeature) {
1759            return 0L;
1760        }
1761        enforceCrossUserPermission(userHandle);
1762        synchronized (this) {
1763            return getPasswordExpirationLocked(who, userHandle);
1764        }
1765    }
1766
1767    public void setPasswordMinimumUpperCase(ComponentName who, int length, int userHandle) {
1768        if (!mHasFeature) {
1769            return;
1770        }
1771        enforceCrossUserPermission(userHandle);
1772        synchronized (this) {
1773            if (who == null) {
1774                throw new NullPointerException("ComponentName is null");
1775            }
1776            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1777                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1778            if (ap.minimumPasswordUpperCase != length) {
1779                ap.minimumPasswordUpperCase = length;
1780                saveSettingsLocked(userHandle);
1781            }
1782        }
1783    }
1784
1785    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) {
1786        if (!mHasFeature) {
1787            return 0;
1788        }
1789        enforceCrossUserPermission(userHandle);
1790        synchronized (this) {
1791            int length = 0;
1792
1793            if (who != null) {
1794                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1795                return admin != null ? admin.minimumPasswordUpperCase : length;
1796            }
1797
1798            // Return strictest policy for this user and profiles that are visible from this user.
1799            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1800            for (UserInfo userInfo : profiles) {
1801                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1802                final int N = policy.mAdminList.size();
1803                for (int i=0; i<N; i++) {
1804                    ActiveAdmin admin = policy.mAdminList.get(i);
1805                    if (length < admin.minimumPasswordUpperCase) {
1806                        length = admin.minimumPasswordUpperCase;
1807                    }
1808                }
1809            }
1810            return length;
1811        }
1812    }
1813
1814    public void setPasswordMinimumLowerCase(ComponentName who, int length, int userHandle) {
1815        enforceCrossUserPermission(userHandle);
1816        synchronized (this) {
1817            if (who == null) {
1818                throw new NullPointerException("ComponentName is null");
1819            }
1820            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1821                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1822            if (ap.minimumPasswordLowerCase != length) {
1823                ap.minimumPasswordLowerCase = length;
1824                saveSettingsLocked(userHandle);
1825            }
1826        }
1827    }
1828
1829    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) {
1830        if (!mHasFeature) {
1831            return 0;
1832        }
1833        enforceCrossUserPermission(userHandle);
1834        synchronized (this) {
1835            int length = 0;
1836
1837            if (who != null) {
1838                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1839                return admin != null ? admin.minimumPasswordLowerCase : length;
1840            }
1841
1842            // Return strictest policy for this user and profiles that are visible from this user.
1843            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1844            for (UserInfo userInfo : profiles) {
1845                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1846                final int N = policy.mAdminList.size();
1847                for (int i=0; i<N; i++) {
1848                    ActiveAdmin admin = policy.mAdminList.get(i);
1849                    if (length < admin.minimumPasswordLowerCase) {
1850                        length = admin.minimumPasswordLowerCase;
1851                    }
1852                }
1853            }
1854            return length;
1855        }
1856    }
1857
1858    public void setPasswordMinimumLetters(ComponentName who, int length, int userHandle) {
1859        if (!mHasFeature) {
1860            return;
1861        }
1862        enforceCrossUserPermission(userHandle);
1863        synchronized (this) {
1864            if (who == null) {
1865                throw new NullPointerException("ComponentName is null");
1866            }
1867            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1868                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1869            if (ap.minimumPasswordLetters != length) {
1870                ap.minimumPasswordLetters = length;
1871                saveSettingsLocked(userHandle);
1872            }
1873        }
1874    }
1875
1876    public int getPasswordMinimumLetters(ComponentName who, int userHandle) {
1877        if (!mHasFeature) {
1878            return 0;
1879        }
1880        enforceCrossUserPermission(userHandle);
1881        synchronized (this) {
1882            int length = 0;
1883
1884            if (who != null) {
1885                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1886                return admin != null ? admin.minimumPasswordLetters : length;
1887            }
1888
1889            // Return strictest policy for this user and profiles that are visible from this user.
1890            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1891            for (UserInfo userInfo : profiles) {
1892                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1893                final int N = policy.mAdminList.size();
1894                for (int i=0; i<N; i++) {
1895                    ActiveAdmin admin = policy.mAdminList.get(i);
1896                    if (length < admin.minimumPasswordLetters) {
1897                        length = admin.minimumPasswordLetters;
1898                    }
1899                }
1900            }
1901            return length;
1902        }
1903    }
1904
1905    public void setPasswordMinimumNumeric(ComponentName who, int length, int userHandle) {
1906        if (!mHasFeature) {
1907            return;
1908        }
1909        enforceCrossUserPermission(userHandle);
1910        synchronized (this) {
1911            if (who == null) {
1912                throw new NullPointerException("ComponentName is null");
1913            }
1914            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1915                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1916            if (ap.minimumPasswordNumeric != length) {
1917                ap.minimumPasswordNumeric = length;
1918                saveSettingsLocked(userHandle);
1919            }
1920        }
1921    }
1922
1923    public int getPasswordMinimumNumeric(ComponentName who, int userHandle) {
1924        if (!mHasFeature) {
1925            return 0;
1926        }
1927        enforceCrossUserPermission(userHandle);
1928        synchronized (this) {
1929            int length = 0;
1930
1931            if (who != null) {
1932                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1933                return admin != null ? admin.minimumPasswordNumeric : length;
1934            }
1935
1936            // Return strictest policy for this user and profiles that are visible from this user.
1937            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1938            for (UserInfo userInfo : profiles) {
1939                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1940                final int N = policy.mAdminList.size();
1941                for (int i = 0; i < N; i++) {
1942                    ActiveAdmin admin = policy.mAdminList.get(i);
1943                    if (length < admin.minimumPasswordNumeric) {
1944                        length = admin.minimumPasswordNumeric;
1945                    }
1946                }
1947            }
1948            return length;
1949        }
1950    }
1951
1952    public void setPasswordMinimumSymbols(ComponentName who, int length, int userHandle) {
1953        if (!mHasFeature) {
1954            return;
1955        }
1956        enforceCrossUserPermission(userHandle);
1957        synchronized (this) {
1958            if (who == null) {
1959                throw new NullPointerException("ComponentName is null");
1960            }
1961            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
1962                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
1963            if (ap.minimumPasswordSymbols != length) {
1964                ap.minimumPasswordSymbols = length;
1965                saveSettingsLocked(userHandle);
1966            }
1967        }
1968    }
1969
1970    public int getPasswordMinimumSymbols(ComponentName who, int userHandle) {
1971        if (!mHasFeature) {
1972            return 0;
1973        }
1974        enforceCrossUserPermission(userHandle);
1975        synchronized (this) {
1976            int length = 0;
1977
1978            if (who != null) {
1979                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1980                return admin != null ? admin.minimumPasswordSymbols : length;
1981            }
1982
1983            // Return strictest policy for this user and profiles that are visible from this user.
1984            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
1985            for (UserInfo userInfo : profiles) {
1986                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
1987                final int N = policy.mAdminList.size();
1988                for (int i=0; i<N; i++) {
1989                    ActiveAdmin admin = policy.mAdminList.get(i);
1990                    if (length < admin.minimumPasswordSymbols) {
1991                        length = admin.minimumPasswordSymbols;
1992                    }
1993                }
1994            }
1995            return length;
1996        }
1997    }
1998
1999    public void setPasswordMinimumNonLetter(ComponentName who, int length, int userHandle) {
2000        if (!mHasFeature) {
2001            return;
2002        }
2003        enforceCrossUserPermission(userHandle);
2004        synchronized (this) {
2005            if (who == null) {
2006                throw new NullPointerException("ComponentName is null");
2007            }
2008            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2009                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2010            if (ap.minimumPasswordNonLetter != length) {
2011                ap.minimumPasswordNonLetter = length;
2012                saveSettingsLocked(userHandle);
2013            }
2014        }
2015    }
2016
2017    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) {
2018        if (!mHasFeature) {
2019            return 0;
2020        }
2021        enforceCrossUserPermission(userHandle);
2022        synchronized (this) {
2023            int length = 0;
2024
2025            if (who != null) {
2026                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2027                return admin != null ? admin.minimumPasswordNonLetter : length;
2028            }
2029
2030            // Return strictest policy for this user and profiles that are visible from this user.
2031            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2032            for (UserInfo userInfo : profiles) {
2033                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
2034                final int N = policy.mAdminList.size();
2035                for (int i=0; i<N; i++) {
2036                    ActiveAdmin admin = policy.mAdminList.get(i);
2037                    if (length < admin.minimumPasswordNonLetter) {
2038                        length = admin.minimumPasswordNonLetter;
2039                    }
2040                }
2041            }
2042            return length;
2043        }
2044    }
2045
2046    public boolean isActivePasswordSufficient(int userHandle) {
2047        if (!mHasFeature) {
2048            return true;
2049        }
2050        enforceCrossUserPermission(userHandle);
2051
2052        synchronized (this) {
2053
2054            // The active password is stored in the user that runs the launcher
2055            // If the user this is called from is part of a profile group, that is the parent
2056            // of the group.
2057            UserInfo parent = getProfileParent(userHandle);
2058            int id = parent == null ? userHandle : parent.id;
2059            DevicePolicyData policy = getUserData(id);
2060
2061            // This API can only be called by an active device admin,
2062            // so try to retrieve it to check that the caller is one.
2063            getActiveAdminForCallerLocked(null,
2064                    DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
2065            if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle)
2066                    || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) {
2067                return false;
2068            }
2069            if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2070                return true;
2071            }
2072            return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle)
2073                && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle)
2074                && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle)
2075                && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle)
2076                && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle)
2077                && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle);
2078        }
2079    }
2080
2081    public int getCurrentFailedPasswordAttempts(int userHandle) {
2082        synchronized (this) {
2083            // This API can only be called by an active device admin,
2084            // so try to retrieve it to check that the caller is one.
2085            getActiveAdminForCallerLocked(null,
2086                    DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2087
2088            // The active password is stored in the parent.
2089            DevicePolicyData policy = getUserData(getProfileParent(userHandle).id);
2090
2091            return policy.mFailedPasswordAttempts;
2092        }
2093    }
2094
2095    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, int userHandle) {
2096        if (!mHasFeature) {
2097            return;
2098        }
2099        enforceCrossUserPermission(userHandle);
2100        synchronized (this) {
2101            if (who == null) {
2102                throw new NullPointerException("ComponentName is null");
2103            }
2104            // This API can only be called by an active device admin,
2105            // so try to retrieve it to check that the caller is one.
2106            getActiveAdminForCallerLocked(who,
2107                    DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2108            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2109                    DeviceAdminInfo.USES_POLICY_WATCH_LOGIN);
2110            if (ap.maximumFailedPasswordsForWipe != num) {
2111                ap.maximumFailedPasswordsForWipe = num;
2112                saveSettingsLocked(userHandle);
2113            }
2114        }
2115    }
2116
2117    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) {
2118        if (!mHasFeature) {
2119            return 0;
2120        }
2121        enforceCrossUserPermission(userHandle);
2122        synchronized (this) {
2123            int count = 0;
2124
2125            if (who != null) {
2126                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2127                return admin != null ? admin.maximumFailedPasswordsForWipe : count;
2128            }
2129
2130            // Return strictest policy for this user and profiles that are visible from this user.
2131            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2132            for (UserInfo userInfo : profiles) {
2133                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
2134                final int N = policy.mAdminList.size();
2135                for (int i=0; i<N; i++) {
2136                    ActiveAdmin admin = policy.mAdminList.get(i);
2137                    if (count == 0) {
2138                        count = admin.maximumFailedPasswordsForWipe;
2139                    } else if (admin.maximumFailedPasswordsForWipe != 0
2140                            && count > admin.maximumFailedPasswordsForWipe) {
2141                        count = admin.maximumFailedPasswordsForWipe;
2142                    }
2143                }
2144            }
2145            return count;
2146        }
2147    }
2148
2149    public boolean resetPassword(String password, int flags, int userHandle) {
2150        if (!mHasFeature) {
2151            return false;
2152        }
2153        enforceCrossUserPermission(userHandle);
2154        enforceNotManagedProfile(userHandle, "reset the password");
2155
2156        int quality;
2157        synchronized (this) {
2158            // This api can only be called by an active device admin,
2159            // so try to retrieve it to check that the caller is one.
2160            getActiveAdminForCallerLocked(null,
2161                    DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
2162            quality = getPasswordQuality(null, userHandle);
2163            if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
2164                int realQuality = LockPatternUtils.computePasswordQuality(password);
2165                if (realQuality < quality
2166                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2167                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
2168                            + Integer.toHexString(realQuality)
2169                            + " does not meet required quality 0x"
2170                            + Integer.toHexString(quality));
2171                    return false;
2172                }
2173                quality = Math.max(realQuality, quality);
2174            }
2175            int length = getPasswordMinimumLength(null, userHandle);
2176            if (password.length() < length) {
2177                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
2178                        + " does not meet required length " + length);
2179                return false;
2180            }
2181            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
2182                int letters = 0;
2183                int uppercase = 0;
2184                int lowercase = 0;
2185                int numbers = 0;
2186                int symbols = 0;
2187                int nonletter = 0;
2188                for (int i = 0; i < password.length(); i++) {
2189                    char c = password.charAt(i);
2190                    if (c >= 'A' && c <= 'Z') {
2191                        letters++;
2192                        uppercase++;
2193                    } else if (c >= 'a' && c <= 'z') {
2194                        letters++;
2195                        lowercase++;
2196                    } else if (c >= '0' && c <= '9') {
2197                        numbers++;
2198                        nonletter++;
2199                    } else {
2200                        symbols++;
2201                        nonletter++;
2202                    }
2203                }
2204                int neededLetters = getPasswordMinimumLetters(null, userHandle);
2205                if(letters < neededLetters) {
2206                    Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
2207                            + " does not meet required number of letters " + neededLetters);
2208                    return false;
2209                }
2210                int neededNumbers = getPasswordMinimumNumeric(null, userHandle);
2211                if (numbers < neededNumbers) {
2212                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
2213                            + " does not meet required number of numerical digits "
2214                            + neededNumbers);
2215                    return false;
2216                }
2217                int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle);
2218                if (lowercase < neededLowerCase) {
2219                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
2220                            + " does not meet required number of lowercase letters "
2221                            + neededLowerCase);
2222                    return false;
2223                }
2224                int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle);
2225                if (uppercase < neededUpperCase) {
2226                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
2227                            + " does not meet required number of uppercase letters "
2228                            + neededUpperCase);
2229                    return false;
2230                }
2231                int neededSymbols = getPasswordMinimumSymbols(null, userHandle);
2232                if (symbols < neededSymbols) {
2233                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
2234                            + " does not meet required number of special symbols " + neededSymbols);
2235                    return false;
2236                }
2237                int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle);
2238                if (nonletter < neededNonLetter) {
2239                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
2240                            + " does not meet required number of non-letter characters "
2241                            + neededNonLetter);
2242                    return false;
2243                }
2244            }
2245        }
2246
2247        int callingUid = Binder.getCallingUid();
2248        DevicePolicyData policy = getUserData(userHandle);
2249        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
2250            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
2251            return false;
2252        }
2253
2254        // Don't do this with the lock held, because it is going to call
2255        // back in to the service.
2256        long ident = Binder.clearCallingIdentity();
2257        try {
2258            LockPatternUtils utils = new LockPatternUtils(mContext);
2259            utils.saveLockPassword(password, quality, false, userHandle);
2260            synchronized (this) {
2261                int newOwner = (flags&DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY)
2262                        != 0 ? callingUid : -1;
2263                if (policy.mPasswordOwner != newOwner) {
2264                    policy.mPasswordOwner = newOwner;
2265                    saveSettingsLocked(userHandle);
2266                }
2267            }
2268        } finally {
2269            Binder.restoreCallingIdentity(ident);
2270        }
2271
2272        return true;
2273    }
2274
2275    public void setMaximumTimeToLock(ComponentName who, long timeMs, int userHandle) {
2276        if (!mHasFeature) {
2277            return;
2278        }
2279        enforceCrossUserPermission(userHandle);
2280        synchronized (this) {
2281            if (who == null) {
2282                throw new NullPointerException("ComponentName is null");
2283            }
2284            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2285                    DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2286            if (ap.maximumTimeToUnlock != timeMs) {
2287                ap.maximumTimeToUnlock = timeMs;
2288                saveSettingsLocked(userHandle);
2289                updateMaximumTimeToLockLocked(getUserData(userHandle));
2290            }
2291        }
2292    }
2293
2294    void updateMaximumTimeToLockLocked(DevicePolicyData policy) {
2295        long timeMs = getMaximumTimeToLock(null, policy.mUserHandle);
2296        if (policy.mLastMaximumTimeToLock == timeMs) {
2297            return;
2298        }
2299
2300        long ident = Binder.clearCallingIdentity();
2301        try {
2302            if (timeMs <= 0) {
2303                timeMs = Integer.MAX_VALUE;
2304            } else {
2305                // Make sure KEEP_SCREEN_ON is disabled, since that
2306                // would allow bypassing of the maximum time to lock.
2307                Settings.Global.putInt(mContext.getContentResolver(),
2308                        Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
2309            }
2310
2311            policy.mLastMaximumTimeToLock = timeMs;
2312
2313            try {
2314                getIPowerManager().setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs);
2315            } catch (RemoteException e) {
2316                Slog.w(LOG_TAG, "Failure talking with power manager", e);
2317            }
2318        } finally {
2319            Binder.restoreCallingIdentity(ident);
2320        }
2321    }
2322
2323    public long getMaximumTimeToLock(ComponentName who, int userHandle) {
2324        if (!mHasFeature) {
2325            return 0;
2326        }
2327        enforceCrossUserPermission(userHandle);
2328        synchronized (this) {
2329            long time = 0;
2330
2331            if (who != null) {
2332                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2333                return admin != null ? admin.maximumTimeToUnlock : time;
2334            }
2335
2336            // Return strictest policy for this user and profiles that are visible from this user.
2337            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2338            for (UserInfo userInfo : profiles) {
2339                DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier());
2340                final int N = policy.mAdminList.size();
2341                for (int i=0; i<N; i++) {
2342                    ActiveAdmin admin = policy.mAdminList.get(i);
2343                    if (time == 0) {
2344                        time = admin.maximumTimeToUnlock;
2345                    } else if (admin.maximumTimeToUnlock != 0
2346                            && time > admin.maximumTimeToUnlock) {
2347                        time = admin.maximumTimeToUnlock;
2348                    }
2349                }
2350            }
2351            return time;
2352        }
2353    }
2354
2355    public void lockNow() {
2356        if (!mHasFeature) {
2357            return;
2358        }
2359        synchronized (this) {
2360            // This API can only be called by an active device admin,
2361            // so try to retrieve it to check that the caller is one.
2362            getActiveAdminForCallerLocked(null,
2363                    DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
2364            lockNowUnchecked();
2365        }
2366    }
2367
2368    private void lockNowUnchecked() {
2369        long ident = Binder.clearCallingIdentity();
2370        try {
2371            // Power off the display
2372            getIPowerManager().goToSleep(SystemClock.uptimeMillis(),
2373                    PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
2374            // Ensure the device is locked
2375            getWindowManager().lockNow(null);
2376        } catch (RemoteException e) {
2377        } finally {
2378            Binder.restoreCallingIdentity(ident);
2379        }
2380    }
2381
2382    private boolean isExtStorageEncrypted() {
2383        String state = SystemProperties.get("vold.decrypt");
2384        return !"".equals(state);
2385    }
2386
2387    public boolean installCaCert(byte[] certBuffer) throws RemoteException {
2388        mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
2389        KeyChainConnection keyChainConnection = null;
2390        byte[] pemCert;
2391        try {
2392            X509Certificate cert = parseCert(certBuffer);
2393            pemCert =  Credentials.convertToPem(cert);
2394        } catch (CertificateException ce) {
2395            Log.e(LOG_TAG, "Problem converting cert", ce);
2396            return false;
2397        } catch (IOException ioe) {
2398            Log.e(LOG_TAG, "Problem reading cert", ioe);
2399            return false;
2400        }
2401        try {
2402            keyChainConnection = KeyChain.bind(mContext);
2403            try {
2404                keyChainConnection.getService().installCaCertificate(pemCert);
2405                return true;
2406            } finally {
2407                if (keyChainConnection != null) {
2408                    keyChainConnection.close();
2409                    keyChainConnection = null;
2410                }
2411            }
2412        } catch (InterruptedException e1) {
2413            Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
2414            Thread.currentThread().interrupt();
2415        }
2416        return false;
2417    }
2418
2419    private static X509Certificate parseCert(byte[] certBuffer)
2420            throws CertificateException, IOException {
2421        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
2422        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
2423                certBuffer));
2424    }
2425
2426    public void uninstallCaCert(final byte[] certBuffer) {
2427        mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
2428        TrustedCertificateStore certStore = new TrustedCertificateStore();
2429        String alias = null;
2430        try {
2431            X509Certificate cert = parseCert(certBuffer);
2432            alias = certStore.getCertificateAlias(cert);
2433        } catch (CertificateException ce) {
2434            Log.e(LOG_TAG, "Problem creating X509Certificate", ce);
2435            return;
2436        } catch (IOException ioe) {
2437            Log.e(LOG_TAG, "Problem reading certificate", ioe);
2438            return;
2439        }
2440        try {
2441            KeyChainConnection keyChainConnection = KeyChain.bind(mContext);
2442            IKeyChainService service = keyChainConnection.getService();
2443            try {
2444                service.deleteCaCertificate(alias);
2445            } catch (RemoteException e) {
2446                Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
2447            } finally {
2448                keyChainConnection.close();
2449                keyChainConnection = null;
2450            }
2451        } catch (InterruptedException ie) {
2452            Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
2453            Thread.currentThread().interrupt();
2454        }
2455    }
2456
2457    void wipeDataLocked(int flags) {
2458        // If the SD card is encrypted and non-removable, we have to force a wipe.
2459        boolean forceExtWipe = !Environment.isExternalStorageRemovable() && isExtStorageEncrypted();
2460        boolean wipeExtRequested = (flags&DevicePolicyManager.WIPE_EXTERNAL_STORAGE) != 0;
2461
2462        // Note: we can only do the wipe via ExternalStorageFormatter if the volume is not emulated.
2463        if ((forceExtWipe || wipeExtRequested) && !Environment.isExternalStorageEmulated()) {
2464            Intent intent = new Intent(ExternalStorageFormatter.FORMAT_AND_FACTORY_RESET);
2465            intent.putExtra(ExternalStorageFormatter.EXTRA_ALWAYS_RESET, true);
2466            intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME);
2467            mWakeLock.acquire(10000);
2468            mContext.startService(intent);
2469        } else {
2470            try {
2471                RecoverySystem.rebootWipeUserData(mContext);
2472            } catch (IOException e) {
2473                Slog.w(LOG_TAG, "Failed requesting data wipe", e);
2474            }
2475        }
2476    }
2477
2478    public void wipeData(int flags, final int userHandle) {
2479        if (!mHasFeature) {
2480            return;
2481        }
2482        enforceCrossUserPermission(userHandle);
2483        if ((flags & DevicePolicyManager.WIPE_EXTERNAL_STORAGE) != 0) {
2484            enforceNotManagedProfile(userHandle, "wipe external storage");
2485        }
2486        synchronized (this) {
2487            // This API can only be called by an active device admin,
2488            // so try to retrieve it to check that the caller is one.
2489            getActiveAdminForCallerLocked(null,
2490                    DeviceAdminInfo.USES_POLICY_WIPE_DATA);
2491            long ident = Binder.clearCallingIdentity();
2492            try {
2493                wipeDeviceOrUserLocked(flags, userHandle);
2494            } finally {
2495                Binder.restoreCallingIdentity(ident);
2496            }
2497        }
2498    }
2499
2500    private void wipeDeviceOrUserLocked(int flags, final int userHandle) {
2501        if (userHandle == UserHandle.USER_OWNER) {
2502            wipeDataLocked(flags);
2503        } else {
2504            lockNowUnchecked();
2505            mHandler.post(new Runnable() {
2506                public void run() {
2507                    try {
2508                        ActivityManagerNative.getDefault().switchUser(UserHandle.USER_OWNER);
2509                        (mUserManager)
2510                                .removeUser(userHandle);
2511                    } catch (RemoteException re) {
2512                        // Shouldn't happen
2513                    }
2514                }
2515            });
2516        }
2517    }
2518
2519    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
2520        if (!mHasFeature) {
2521            return;
2522        }
2523        enforceCrossUserPermission(userHandle);
2524        mContext.enforceCallingOrSelfPermission(
2525                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
2526
2527        synchronized (this) {
2528            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
2529            if (admin == null) {
2530                try {
2531                    result.sendResult(null);
2532                } catch (RemoteException e) {
2533                }
2534                return;
2535            }
2536            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
2537            intent.setComponent(admin.info.getComponent());
2538            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
2539                    null, new BroadcastReceiver() {
2540                @Override
2541                public void onReceive(Context context, Intent intent) {
2542                    try {
2543                        result.sendResult(getResultExtras(false));
2544                    } catch (RemoteException e) {
2545                    }
2546                }
2547            }, null, Activity.RESULT_OK, null, null);
2548        }
2549    }
2550
2551    public void setActivePasswordState(int quality, int length, int letters, int uppercase,
2552            int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
2553        if (!mHasFeature) {
2554            return;
2555        }
2556        enforceCrossUserPermission(userHandle);
2557        enforceNotManagedProfile(userHandle, "set the active password");
2558
2559        mContext.enforceCallingOrSelfPermission(
2560                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
2561        DevicePolicyData p = getUserData(userHandle);
2562
2563        validateQualityConstant(quality);
2564
2565        synchronized (this) {
2566            if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length
2567                    || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters
2568                    || p.mActivePasswordUpperCase != uppercase
2569                    || p.mActivePasswordLowerCase != lowercase
2570                    || p.mActivePasswordNumeric != numbers
2571                    || p.mActivePasswordSymbols != symbols
2572                    || p.mActivePasswordNonLetter != nonletter) {
2573                long ident = Binder.clearCallingIdentity();
2574                try {
2575                    p.mActivePasswordQuality = quality;
2576                    p.mActivePasswordLength = length;
2577                    p.mActivePasswordLetters = letters;
2578                    p.mActivePasswordLowerCase = lowercase;
2579                    p.mActivePasswordUpperCase = uppercase;
2580                    p.mActivePasswordNumeric = numbers;
2581                    p.mActivePasswordSymbols = symbols;
2582                    p.mActivePasswordNonLetter = nonletter;
2583                    p.mFailedPasswordAttempts = 0;
2584                    saveSettingsLocked(userHandle);
2585                    updatePasswordExpirationsLocked(userHandle);
2586                    setExpirationAlarmCheckLocked(mContext, p);
2587                    sendAdminCommandToSelfAndProfilesLocked(
2588                            DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
2589                            DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
2590                } finally {
2591                    Binder.restoreCallingIdentity(ident);
2592                }
2593            }
2594        }
2595    }
2596
2597    /**
2598     * Called any time the device password is updated. Resets all password expiration clocks.
2599     */
2600    private void updatePasswordExpirationsLocked(int userHandle) {
2601            List<UserInfo> profiles = mUserManager.getProfiles(userHandle);
2602            for (UserInfo userInfo : profiles) {
2603                int profileId = userInfo.getUserHandle().getIdentifier();
2604                DevicePolicyData policy = getUserData(profileId);
2605                final int N = policy.mAdminList.size();
2606                if (N > 0) {
2607                    for (int i=0; i<N; i++) {
2608                        ActiveAdmin admin = policy.mAdminList.get(i);
2609                        if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
2610                            long timeout = admin.passwordExpirationTimeout;
2611                            long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
2612                            admin.passwordExpirationDate = expiration;
2613                        }
2614                    }
2615                }
2616                saveSettingsLocked(profileId);
2617            }
2618    }
2619
2620    public void reportFailedPasswordAttempt(int userHandle) {
2621        enforceCrossUserPermission(userHandle);
2622        enforceNotManagedProfile(userHandle, "report failed password attempt");
2623        mContext.enforceCallingOrSelfPermission(
2624                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
2625
2626        synchronized (this) {
2627            DevicePolicyData policy = getUserData(userHandle);
2628            long ident = Binder.clearCallingIdentity();
2629            try {
2630                policy.mFailedPasswordAttempts++;
2631                saveSettingsLocked(userHandle);
2632                if (mHasFeature) {
2633                    int max = getMaximumFailedPasswordsForWipe(null, userHandle);
2634                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
2635                        wipeDeviceOrUserLocked(0, userHandle);
2636                    }
2637                    sendAdminCommandToSelfAndProfilesLocked(
2638                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
2639                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
2640                }
2641            } finally {
2642                Binder.restoreCallingIdentity(ident);
2643            }
2644        }
2645    }
2646
2647    public void reportSuccessfulPasswordAttempt(int userHandle) {
2648        enforceCrossUserPermission(userHandle);
2649        mContext.enforceCallingOrSelfPermission(
2650                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
2651
2652        synchronized (this) {
2653            DevicePolicyData policy = getUserData(userHandle);
2654            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
2655                long ident = Binder.clearCallingIdentity();
2656                try {
2657                    policy.mFailedPasswordAttempts = 0;
2658                    policy.mPasswordOwner = -1;
2659                    saveSettingsLocked(userHandle);
2660                    if (mHasFeature) {
2661                        sendAdminCommandToSelfAndProfilesLocked(
2662                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
2663                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
2664                    }
2665                } finally {
2666                    Binder.restoreCallingIdentity(ident);
2667                }
2668            }
2669        }
2670    }
2671
2672    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
2673            String exclusionList, int userHandle) {
2674        if (!mHasFeature) {
2675            return null;
2676        }
2677        enforceCrossUserPermission(userHandle);
2678        synchronized(this) {
2679            if (who == null) {
2680                throw new NullPointerException("ComponentName is null");
2681            }
2682
2683            // Only check if owner has set global proxy. We don't allow other users to set it.
2684            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
2685            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
2686                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
2687
2688            // Scan through active admins and find if anyone has already
2689            // set the global proxy.
2690            Set<ComponentName> compSet = policy.mAdminMap.keySet();
2691            for (ComponentName component : compSet) {
2692                ActiveAdmin ap = policy.mAdminMap.get(component);
2693                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
2694                    // Another admin already sets the global proxy
2695                    // Return it to the caller.
2696                    return component;
2697                }
2698            }
2699
2700            // If the user is not the owner, don't set the global proxy. Fail silently.
2701            if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
2702                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
2703                        + userHandle + " is not permitted.");
2704                return null;
2705            }
2706            if (proxySpec == null) {
2707                admin.specifiesGlobalProxy = false;
2708                admin.globalProxySpec = null;
2709                admin.globalProxyExclusionList = null;
2710            } else {
2711
2712                admin.specifiesGlobalProxy = true;
2713                admin.globalProxySpec = proxySpec;
2714                admin.globalProxyExclusionList = exclusionList;
2715            }
2716
2717            // Reset the global proxy accordingly
2718            // Do this using system permissions, as apps cannot write to secure settings
2719            long origId = Binder.clearCallingIdentity();
2720            try {
2721                resetGlobalProxyLocked(policy);
2722            } finally {
2723                Binder.restoreCallingIdentity(origId);
2724            }
2725            return null;
2726        }
2727    }
2728
2729    public ComponentName getGlobalProxyAdmin(int userHandle) {
2730        if (!mHasFeature) {
2731            return null;
2732        }
2733        enforceCrossUserPermission(userHandle);
2734        synchronized(this) {
2735            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
2736            // Scan through active admins and find if anyone has already
2737            // set the global proxy.
2738            final int N = policy.mAdminList.size();
2739            for (int i = 0; i < N; i++) {
2740                ActiveAdmin ap = policy.mAdminList.get(i);
2741                if (ap.specifiesGlobalProxy) {
2742                    // Device admin sets the global proxy
2743                    // Return it to the caller.
2744                    return ap.info.getComponent();
2745                }
2746            }
2747        }
2748        // No device admin sets the global proxy.
2749        return null;
2750    }
2751
2752    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
2753        synchronized (this) {
2754            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
2755        }
2756        long token = Binder.clearCallingIdentity();
2757        try {
2758            ConnectivityManager connectivityManager = (ConnectivityManager)
2759                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
2760            connectivityManager.setGlobalProxy(proxyInfo);
2761        } finally {
2762            Binder.restoreCallingIdentity(token);
2763        }
2764    }
2765
2766    private void resetGlobalProxyLocked(DevicePolicyData policy) {
2767        final int N = policy.mAdminList.size();
2768        for (int i = 0; i < N; i++) {
2769            ActiveAdmin ap = policy.mAdminList.get(i);
2770            if (ap.specifiesGlobalProxy) {
2771                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
2772                return;
2773            }
2774        }
2775        // No device admins defining global proxies - reset global proxy settings to none
2776        saveGlobalProxyLocked(null, null);
2777    }
2778
2779    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
2780        if (exclusionList == null) {
2781            exclusionList = "";
2782        }
2783        if (proxySpec == null) {
2784            proxySpec = "";
2785        }
2786        // Remove white spaces
2787        proxySpec = proxySpec.trim();
2788        String data[] = proxySpec.split(":");
2789        int proxyPort = 8080;
2790        if (data.length > 1) {
2791            try {
2792                proxyPort = Integer.parseInt(data[1]);
2793            } catch (NumberFormatException e) {}
2794        }
2795        exclusionList = exclusionList.trim();
2796        ContentResolver res = mContext.getContentResolver();
2797
2798        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
2799        if (!proxyProperties.isValid()) {
2800            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
2801            return;
2802        }
2803        Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
2804        Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
2805        Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2806                exclusionList);
2807    }
2808
2809    /**
2810     * Set the storage encryption request for a single admin.  Returns the new total request
2811     * status (for all admins).
2812     */
2813    public int setStorageEncryption(ComponentName who, boolean encrypt, int userHandle) {
2814        if (!mHasFeature) {
2815            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
2816        }
2817        enforceCrossUserPermission(userHandle);
2818        synchronized (this) {
2819            // Check for permissions
2820            if (who == null) {
2821                throw new NullPointerException("ComponentName is null");
2822            }
2823            // Only owner can set storage encryption
2824            if (userHandle != UserHandle.USER_OWNER
2825                    || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) {
2826                Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User "
2827                        + UserHandle.getCallingUserId() + " is not permitted.");
2828                return 0;
2829            }
2830
2831            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2832                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
2833
2834            // Quick exit:  If the filesystem does not support encryption, we can exit early.
2835            if (!isEncryptionSupported()) {
2836                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
2837            }
2838
2839            // (1) Record the value for the admin so it's sticky
2840            if (ap.encryptionRequested != encrypt) {
2841                ap.encryptionRequested = encrypt;
2842                saveSettingsLocked(userHandle);
2843            }
2844
2845            DevicePolicyData policy = getUserData(UserHandle.USER_OWNER);
2846            // (2) Compute "max" for all admins
2847            boolean newRequested = false;
2848            final int N = policy.mAdminList.size();
2849            for (int i = 0; i < N; i++) {
2850                newRequested |= policy.mAdminList.get(i).encryptionRequested;
2851            }
2852
2853            // Notify OS of new request
2854            setEncryptionRequested(newRequested);
2855
2856            // Return the new global request status
2857            return newRequested
2858                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
2859                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
2860        }
2861    }
2862
2863    /**
2864     * Get the current storage encryption request status for a given admin, or aggregate of all
2865     * active admins.
2866     */
2867    public boolean getStorageEncryption(ComponentName who, int userHandle) {
2868        if (!mHasFeature) {
2869            return false;
2870        }
2871        enforceCrossUserPermission(userHandle);
2872        synchronized (this) {
2873            // Check for permissions if a particular caller is specified
2874            if (who != null) {
2875                // When checking for a single caller, status is based on caller's request
2876                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
2877                return ap != null ? ap.encryptionRequested : false;
2878            }
2879
2880            // If no particular caller is specified, return the aggregate set of requests.
2881            // This is short circuited by returning true on the first hit.
2882            DevicePolicyData policy = getUserData(userHandle);
2883            final int N = policy.mAdminList.size();
2884            for (int i = 0; i < N; i++) {
2885                if (policy.mAdminList.get(i).encryptionRequested) {
2886                    return true;
2887                }
2888            }
2889            return false;
2890        }
2891    }
2892
2893    /**
2894     * Get the current encryption status of the device.
2895     */
2896    public int getStorageEncryptionStatus(int userHandle) {
2897        if (!mHasFeature) {
2898            // Ok to return current status.
2899        }
2900        enforceCrossUserPermission(userHandle);
2901        return getEncryptionStatus();
2902    }
2903
2904    /**
2905     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
2906     */
2907    private boolean isEncryptionSupported() {
2908        // Note, this can be implemented as
2909        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
2910        // But is provided as a separate internal method if there's a faster way to do a
2911        // simple check for supported-or-not.
2912        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
2913    }
2914
2915    /**
2916     * Hook to low-levels:  Reporting the current status of encryption.
2917     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} or
2918     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE} or
2919     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
2920     */
2921    private int getEncryptionStatus() {
2922        String status = SystemProperties.get("ro.crypto.state", "unsupported");
2923        if ("encrypted".equalsIgnoreCase(status)) {
2924            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
2925        } else if ("unencrypted".equalsIgnoreCase(status)) {
2926            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
2927        } else {
2928            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
2929        }
2930    }
2931
2932    /**
2933     * Hook to low-levels:  If needed, record the new admin setting for encryption.
2934     */
2935    private void setEncryptionRequested(boolean encrypt) {
2936    }
2937
2938    /**
2939     * The system property used to share the state of the camera. The native camera service
2940     * is expected to read this property and act accordingly.
2941     */
2942    public static final String SYSTEM_PROP_DISABLE_CAMERA = "sys.secpolicy.camera.disabled";
2943
2944    /**
2945     * Disables all device cameras according to the specified admin.
2946     */
2947    public void setCameraDisabled(ComponentName who, boolean disabled, int userHandle) {
2948        if (!mHasFeature) {
2949            return;
2950        }
2951        enforceCrossUserPermission(userHandle);
2952        enforceNotManagedProfile(userHandle, "enable/disable cameras");
2953        synchronized (this) {
2954            if (who == null) {
2955                throw new NullPointerException("ComponentName is null");
2956            }
2957            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
2958                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
2959            if (ap.disableCamera != disabled) {
2960                ap.disableCamera = disabled;
2961                saveSettingsLocked(userHandle);
2962            }
2963            syncDeviceCapabilitiesLocked(getUserData(userHandle));
2964        }
2965    }
2966
2967    /**
2968     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
2969     * active admins.
2970     */
2971    public boolean getCameraDisabled(ComponentName who, int userHandle) {
2972        if (!mHasFeature) {
2973            return false;
2974        }
2975        synchronized (this) {
2976            if (who != null) {
2977                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2978                return (admin != null) ? admin.disableCamera : false;
2979            }
2980
2981            DevicePolicyData policy = getUserData(userHandle);
2982            // Determine whether or not the device camera is disabled for any active admins.
2983            final int N = policy.mAdminList.size();
2984            for (int i = 0; i < N; i++) {
2985                ActiveAdmin admin = policy.mAdminList.get(i);
2986                if (admin.disableCamera) {
2987                    return true;
2988                }
2989            }
2990            return false;
2991        }
2992    }
2993
2994    /**
2995     * Selectively disable keyguard features.
2996     */
2997    public void setKeyguardDisabledFeatures(ComponentName who, int which, int userHandle) {
2998        if (!mHasFeature) {
2999            return;
3000        }
3001        enforceCrossUserPermission(userHandle);
3002        enforceNotManagedProfile(userHandle, "disable keyguard features");
3003        synchronized (this) {
3004            if (who == null) {
3005                throw new NullPointerException("ComponentName is null");
3006            }
3007            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3008                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
3009            if (ap.disabledKeyguardFeatures != which) {
3010                ap.disabledKeyguardFeatures = which;
3011                saveSettingsLocked(userHandle);
3012            }
3013            syncDeviceCapabilitiesLocked(getUserData(userHandle));
3014        }
3015    }
3016
3017    /**
3018     * Gets the disabled state for features in keyguard for the given admin,
3019     * or the aggregate of all active admins if who is null.
3020     */
3021    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) {
3022        if (!mHasFeature) {
3023            return 0;
3024        }
3025        enforceCrossUserPermission(userHandle);
3026        synchronized (this) {
3027            if (who != null) {
3028                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3029                return (admin != null) ? admin.disabledKeyguardFeatures : 0;
3030            }
3031
3032            // Determine which keyguard features are disabled for any active admins.
3033            DevicePolicyData policy = getUserData(userHandle);
3034            final int N = policy.mAdminList.size();
3035            int which = 0;
3036            for (int i = 0; i < N; i++) {
3037                ActiveAdmin admin = policy.mAdminList.get(i);
3038                which |= admin.disabledKeyguardFeatures;
3039            }
3040            return which;
3041        }
3042    }
3043
3044    @Override
3045    public boolean setDeviceOwner(String packageName, String ownerName) {
3046        if (!mHasFeature) {
3047            return false;
3048        }
3049        if (packageName == null
3050                || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) {
3051            throw new IllegalArgumentException("Invalid package name " + packageName
3052                    + " for device owner");
3053        }
3054        synchronized (this) {
3055            if (isDeviceProvisioned()) {
3056                throw new IllegalStateException(
3057                        "Trying to set device owner but device is already provisioned.");
3058            }
3059
3060            if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3061                throw new IllegalStateException(
3062                        "Trying to set device owner but device owner is already set.");
3063            }
3064
3065            long token = Binder.clearCallingIdentity();
3066            try {
3067                mAppOpsService.setDeviceOwner(packageName);
3068            } catch (RemoteException e) {
3069                Log.w(LOG_TAG, "Unable to notify AppOpsService of DeviceOwner", e);
3070            } finally {
3071                Binder.restoreCallingIdentity(token);
3072            }
3073            if (mDeviceOwner == null) {
3074                // Device owner is not set and does not exist, set it.
3075                mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName);
3076                mDeviceOwner.writeOwnerFile();
3077                return true;
3078            } else {
3079                // Device owner is not set but a profile owner exists, update Device owner state.
3080                mDeviceOwner.setDeviceOwner(packageName, ownerName);
3081                mDeviceOwner.writeOwnerFile();
3082                return true;
3083            }
3084        }
3085    }
3086
3087    @Override
3088    public boolean isDeviceOwner(String packageName) {
3089        if (!mHasFeature) {
3090            return false;
3091        }
3092        synchronized (this) {
3093            return mDeviceOwner != null
3094                    && mDeviceOwner.hasDeviceOwner()
3095                    && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName);
3096        }
3097    }
3098
3099    @Override
3100    public String getDeviceOwner() {
3101        if (!mHasFeature) {
3102            return null;
3103        }
3104        synchronized (this) {
3105            if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) {
3106                return mDeviceOwner.getDeviceOwnerPackageName();
3107            }
3108        }
3109        return null;
3110    }
3111
3112    @Override
3113    public String getDeviceOwnerName() {
3114        if (!mHasFeature) {
3115            return null;
3116        }
3117        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3118        synchronized (this) {
3119            if (mDeviceOwner != null) {
3120                return mDeviceOwner.getDeviceOwnerName();
3121            }
3122        }
3123        return null;
3124    }
3125
3126    @Override
3127    public void clearDeviceOwner(String packageName) {
3128        if (packageName == null) {
3129            throw new NullPointerException("packageName is null");
3130        }
3131        try {
3132            int uid = mContext.getPackageManager().getPackageUid(packageName, 0);
3133            if (uid != Binder.getCallingUid()) {
3134                throw new SecurityException("Invalid packageName");
3135            }
3136        } catch (NameNotFoundException e) {
3137            throw new SecurityException(e);
3138        }
3139        if (!isDeviceOwner(packageName)) {
3140            throw new SecurityException("clearDeviceOwner can only be called by the device owner");
3141        }
3142        synchronized (this) {
3143            long ident = Binder.clearCallingIdentity();
3144            try {
3145                mUserManager.setUserRestrictions(new Bundle(),
3146                        new UserHandle(UserHandle.USER_OWNER));
3147                if (mDeviceOwner != null) {
3148                    mDeviceOwner.clearDeviceOwner();
3149                    mDeviceOwner.writeOwnerFile();
3150                }
3151            } finally {
3152                Binder.restoreCallingIdentity(ident);
3153            }
3154        }
3155    }
3156
3157    @Override
3158    public boolean setProfileOwner(String packageName, String ownerName, int userHandle) {
3159        if (!mHasFeature) {
3160            return false;
3161        }
3162        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3163
3164        if (mUserManager.getUserInfo(userHandle) == null) {
3165            // User doesn't exist.
3166            throw new IllegalArgumentException(
3167                    "Attempted to set profile owner for invalid userId: " + userHandle);
3168        }
3169
3170        if (packageName == null
3171                || !DeviceOwner.isInstalledForUser(packageName, userHandle)) {
3172            throw new IllegalArgumentException("Package name " + packageName
3173                    + " not installed for userId:" + userHandle);
3174        }
3175        synchronized (this) {
3176            if (isUserSetupComplete(userHandle)) {
3177                throw new IllegalStateException(
3178                        "Trying to set profile owner but user is already set-up.");
3179            }
3180            long token = Binder.clearCallingIdentity();
3181            try {
3182                mAppOpsService.setProfileOwner(packageName, userHandle);
3183            } catch (RemoteException e) {
3184                Log.w(LOG_TAG, "Unable to notify AppOpsService of ProfileOwner", e);
3185            } finally {
3186                Binder.restoreCallingIdentity(token);
3187            }
3188            if (mDeviceOwner == null) {
3189                // Device owner state does not exist, create it.
3190                mDeviceOwner = DeviceOwner.createWithProfileOwner(packageName, ownerName,
3191                        userHandle);
3192                mDeviceOwner.writeOwnerFile();
3193                return true;
3194            } else {
3195                // Device owner already exists, update it.
3196                mDeviceOwner.setProfileOwner(packageName, ownerName, userHandle);
3197                mDeviceOwner.writeOwnerFile();
3198                return true;
3199            }
3200        }
3201    }
3202
3203    @Override
3204    public void setProfileEnabled(ComponentName who) {
3205        if (!mHasFeature) {
3206            return;
3207        }
3208        synchronized (this) {
3209            // Check for permissions
3210            if (who == null) {
3211                throw new NullPointerException("ComponentName is null");
3212            }
3213            // Check if this is the profile owner who is calling
3214            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3215            int userId = UserHandle.getCallingUserId();
3216            Slog.d(LOG_TAG, "Enabling the profile for: " + userId);
3217
3218            long id = Binder.clearCallingIdentity();
3219            try {
3220                mUserManager.setUserEnabled(userId);
3221                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
3222                intent.putExtra(Intent.EXTRA_USER, new UserHandle(UserHandle.getCallingUserId()));
3223                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
3224                        Intent.FLAG_RECEIVER_FOREGROUND);
3225                // TODO This should send to parent of profile (which is always owner at the moment).
3226                mContext.sendBroadcastAsUser(intent, UserHandle.OWNER);
3227            } finally {
3228                restoreCallingIdentity(id);
3229            }
3230        }
3231    }
3232
3233    @Override
3234    public String getProfileOwner(int userHandle) {
3235        if (!mHasFeature) {
3236            return null;
3237        }
3238
3239        synchronized (this) {
3240            if (mDeviceOwner != null) {
3241                return mDeviceOwner.getProfileOwnerPackageName(userHandle);
3242            }
3243        }
3244        return null;
3245    }
3246
3247    @Override
3248    public String getProfileOwnerName(int userHandle) {
3249        if (!mHasFeature) {
3250            return null;
3251        }
3252        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
3253
3254        synchronized (this) {
3255            if (mDeviceOwner != null) {
3256                return mDeviceOwner.getProfileOwnerName(userHandle);
3257            }
3258        }
3259        return null;
3260    }
3261
3262    private boolean isDeviceProvisioned() {
3263        return Settings.Global.getInt(mContext.getContentResolver(),
3264                Settings.Global.DEVICE_PROVISIONED, 0) > 0;
3265    }
3266
3267    private boolean isUserSetupComplete(int userId) {
3268        return Settings.Secure.getIntForUser(mContext.getContentResolver(),
3269                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) > 0;
3270    }
3271
3272    private void enforceCrossUserPermission(int userHandle) {
3273        if (userHandle < 0) {
3274            throw new IllegalArgumentException("Invalid userId " + userHandle);
3275        }
3276        final int callingUid = Binder.getCallingUid();
3277        if (userHandle == UserHandle.getUserId(callingUid)) return;
3278        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3279            mContext.enforceCallingOrSelfPermission(
3280                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
3281                    + " INTERACT_ACROSS_USERS_FULL permission");
3282        }
3283    }
3284
3285    private void enforceNotManagedProfile(int userHandle, String message) {
3286        if(isManagedProfile(userHandle)) {
3287            throw new SecurityException("You can not " + message + " for a managed profile. ");
3288        }
3289    }
3290
3291    private UserInfo getProfileParent(int userHandle) {
3292        long ident = Binder.clearCallingIdentity();
3293        try {
3294            return mUserManager.getProfileParent(userHandle);
3295        } finally {
3296            Binder.restoreCallingIdentity(ident);
3297        }
3298    }
3299
3300    private boolean isManagedProfile(int userHandle) {
3301        long ident = Binder.clearCallingIdentity();
3302        try {
3303            return mUserManager.getUserInfo(userHandle).isManagedProfile();
3304        } finally {
3305            Binder.restoreCallingIdentity(ident);
3306        }
3307    }
3308
3309    private void enableIfNecessary(String packageName, int userId) {
3310        try {
3311            IPackageManager ipm = AppGlobals.getPackageManager();
3312            ApplicationInfo ai = ipm.getApplicationInfo(packageName,
3313                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
3314                    userId);
3315            if (ai.enabledSetting
3316                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
3317                ipm.setApplicationEnabledSetting(packageName,
3318                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3319                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
3320            }
3321        } catch (RemoteException e) {
3322        }
3323    }
3324
3325    @Override
3326    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3327        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3328                != PackageManager.PERMISSION_GRANTED) {
3329
3330            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
3331                    + Binder.getCallingPid()
3332                    + ", uid=" + Binder.getCallingUid());
3333            return;
3334        }
3335
3336        final Printer p = new PrintWriterPrinter(pw);
3337
3338        synchronized (this) {
3339            p.println("Current Device Policy Manager state:");
3340
3341            int userCount = mUserData.size();
3342            for (int u = 0; u < userCount; u++) {
3343                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
3344                p.println("  Enabled Device Admins (User " + policy.mUserHandle + "):");
3345                final int N = policy.mAdminList.size();
3346                for (int i=0; i<N; i++) {
3347                    ActiveAdmin ap = policy.mAdminList.get(i);
3348                    if (ap != null) {
3349                        pw.print("  "); pw.print(ap.info.getComponent().flattenToShortString());
3350                                pw.println(":");
3351                        ap.dump("    ", pw);
3352                    }
3353                }
3354
3355                pw.println(" ");
3356                pw.print("  mPasswordOwner="); pw.println(policy.mPasswordOwner);
3357            }
3358        }
3359    }
3360
3361    @Override
3362    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
3363            ComponentName activity) {
3364        synchronized (this) {
3365            if (who == null) {
3366                throw new NullPointerException("ComponentName is null");
3367            }
3368            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3369
3370            IPackageManager pm = AppGlobals.getPackageManager();
3371            long id = Binder.clearCallingIdentity();
3372            try {
3373                pm.addPersistentPreferredActivity(filter, activity, UserHandle.getCallingUserId());
3374            } catch (RemoteException re) {
3375                // Shouldn't happen
3376            } finally {
3377                restoreCallingIdentity(id);
3378            }
3379        }
3380    }
3381
3382    @Override
3383    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
3384        synchronized (this) {
3385            if (who == null) {
3386                throw new NullPointerException("ComponentName is null");
3387            }
3388            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3389
3390            IPackageManager pm = AppGlobals.getPackageManager();
3391            long id = Binder.clearCallingIdentity();
3392            try {
3393                pm.clearPackagePersistentPreferredActivities(packageName, UserHandle.getCallingUserId());
3394            } catch (RemoteException re) {
3395                // Shouldn't happen
3396            } finally {
3397                restoreCallingIdentity(id);
3398            }
3399        }
3400    }
3401
3402    @Override
3403    public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
3404        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3405
3406        synchronized (this) {
3407            if (who == null) {
3408                throw new NullPointerException("ComponentName is null");
3409            }
3410            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3411
3412            long id = Binder.clearCallingIdentity();
3413            try {
3414                mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
3415            } finally {
3416                restoreCallingIdentity(id);
3417            }
3418        }
3419    }
3420
3421    @Override
3422    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
3423        synchronized (this) {
3424            if (who == null) {
3425                throw new NullPointerException("ComponentName is null");
3426            }
3427            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3428
3429            int userHandle = UserHandle.getCallingUserId();
3430            DevicePolicyData userData = getUserData(userHandle);
3431            userData.mRestrictionsProvider = permissionProvider;
3432            saveSettingsLocked(userHandle);
3433        }
3434    }
3435
3436    @Override
3437    public ComponentName getRestrictionsProvider(int userHandle) {
3438        synchronized (this) {
3439            if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3440                throw new SecurityException("Only the system can query the permission provider");
3441            }
3442            DevicePolicyData userData = getUserData(userHandle);
3443            return userData != null ? userData.mRestrictionsProvider : null;
3444        }
3445    }
3446
3447    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
3448        int callingUserId = UserHandle.getCallingUserId();
3449        synchronized (this) {
3450            if (who == null) {
3451                throw new NullPointerException("ComponentName is null");
3452            }
3453            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3454
3455            IPackageManager pm = AppGlobals.getPackageManager();
3456            long id = Binder.clearCallingIdentity();
3457            try {
3458                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
3459                    pm.addCrossProfileIntentFilter(filter, true /*removable*/, callingUserId,
3460                            UserHandle.USER_OWNER);
3461                }
3462                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
3463                    pm.addCrossProfileIntentFilter(filter, true /*removable*/, UserHandle.USER_OWNER,
3464                            callingUserId);
3465                }
3466            } catch (RemoteException re) {
3467                // Shouldn't happen
3468            } finally {
3469                restoreCallingIdentity(id);
3470            }
3471        }
3472    }
3473
3474    public void clearCrossProfileIntentFilters(ComponentName who) {
3475        int callingUserId = UserHandle.getCallingUserId();
3476        synchronized (this) {
3477            if (who == null) {
3478                throw new NullPointerException("ComponentName is null");
3479            }
3480            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3481            IPackageManager pm = AppGlobals.getPackageManager();
3482            long id = Binder.clearCallingIdentity();
3483            try {
3484                pm.clearCrossProfileIntentFilters(callingUserId);
3485                pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER);
3486            } catch (RemoteException re) {
3487                // Shouldn't happen
3488            } finally {
3489                restoreCallingIdentity(id);
3490            }
3491        }
3492    }
3493
3494    @Override
3495    public UserHandle createUser(ComponentName who, String name) {
3496        synchronized (this) {
3497            if (who == null) {
3498                throw new NullPointerException("ComponentName is null");
3499            }
3500            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3501
3502            long id = Binder.clearCallingIdentity();
3503            try {
3504                UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */);
3505                if (userInfo != null) {
3506                    return userInfo.getUserHandle();
3507                }
3508                return null;
3509            } finally {
3510                restoreCallingIdentity(id);
3511            }
3512        }
3513    }
3514
3515    @Override
3516    public UserHandle createAndInitializeUser(ComponentName who, String name,
3517            String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) {
3518        UserHandle user = createUser(who, name);
3519        long id = Binder.clearCallingIdentity();
3520        try {
3521            String profileOwnerPkg = profileOwnerComponent.getPackageName();
3522            final IPackageManager ipm = AppGlobals.getPackageManager();
3523            IActivityManager activityManager = ActivityManagerNative.getDefault();
3524
3525            try {
3526                // Install the profile owner if not present.
3527                if (!ipm.isPackageAvailable(profileOwnerPkg, user.getIdentifier())) {
3528                    ipm.installExistingPackageAsUser(profileOwnerPkg, user.getIdentifier());
3529                }
3530
3531                // Start user in background.
3532                activityManager.startUserInBackground(user.getIdentifier());
3533            } catch (RemoteException e) {
3534                Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e);
3535            }
3536
3537            setActiveAdmin(profileOwnerComponent, true, user.getIdentifier(), adminExtras);
3538            setProfileOwner(profileOwnerPkg, ownerName, user.getIdentifier());
3539            return user;
3540        } finally {
3541            restoreCallingIdentity(id);
3542        }
3543    }
3544
3545    @Override
3546    public boolean removeUser(ComponentName who, UserHandle userHandle) {
3547        synchronized (this) {
3548            if (who == null) {
3549                throw new NullPointerException("ComponentName is null");
3550            }
3551            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3552
3553            long id = Binder.clearCallingIdentity();
3554            try {
3555                return mUserManager.removeUser(userHandle.getIdentifier());
3556            } finally {
3557                restoreCallingIdentity(id);
3558            }
3559        }
3560    }
3561
3562    @Override
3563    public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
3564        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3565
3566        synchronized (this) {
3567            if (who == null) {
3568                throw new NullPointerException("ComponentName is null");
3569            }
3570            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3571
3572            long id = Binder.clearCallingIdentity();
3573            try {
3574                return mUserManager.getApplicationRestrictions(packageName, userHandle);
3575            } finally {
3576                restoreCallingIdentity(id);
3577            }
3578        }
3579    }
3580
3581    @Override
3582    public void setUserRestriction(ComponentName who, String key, boolean enabled) {
3583        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
3584
3585        synchronized (this) {
3586            if (who == null) {
3587                throw new NullPointerException("ComponentName is null");
3588            }
3589            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3590
3591            long id = Binder.clearCallingIdentity();
3592            try {
3593                mUserManager.setUserRestriction(key, enabled, userHandle);
3594            } finally {
3595                restoreCallingIdentity(id);
3596            }
3597        }
3598    }
3599
3600    @Override
3601    public boolean setApplicationBlocked(ComponentName who, String packageName,
3602            boolean blocked) {
3603        int callingUserId = UserHandle.getCallingUserId();
3604        synchronized (this) {
3605            if (who == null) {
3606                throw new NullPointerException("ComponentName is null");
3607            }
3608            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3609
3610            long id = Binder.clearCallingIdentity();
3611            try {
3612                IPackageManager pm = AppGlobals.getPackageManager();
3613                return pm.setApplicationBlockedSettingAsUser(packageName, blocked, callingUserId);
3614            } catch (RemoteException re) {
3615                // shouldn't happen
3616                Slog.e(LOG_TAG, "Failed to setApplicationBlockedSetting", re);
3617            } finally {
3618                restoreCallingIdentity(id);
3619            }
3620            return false;
3621        }
3622    }
3623
3624    @Override
3625    public int setApplicationsBlocked(ComponentName who, Intent intent, boolean blocked) {
3626        int callingUserId = UserHandle.getCallingUserId();
3627        synchronized (this) {
3628            if (who == null) {
3629                throw new NullPointerException("ComponentName is null");
3630            }
3631            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3632
3633            long id = Binder.clearCallingIdentity();
3634            try {
3635                IPackageManager pm = AppGlobals.getPackageManager();
3636                List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent,
3637                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
3638                        PackageManager.GET_DISABLED_COMPONENTS
3639                                | PackageManager.GET_UNINSTALLED_PACKAGES,
3640                        callingUserId);
3641
3642                if (DBG) Slog.d(LOG_TAG, "Enabling activities: " + activitiesToEnable);
3643                int numberOfAppsUnblocked = 0;
3644                if (activitiesToEnable != null) {
3645                    for (ResolveInfo info : activitiesToEnable) {
3646                        if (info.activityInfo != null) {
3647                            numberOfAppsUnblocked++;
3648                            pm.setApplicationBlockedSettingAsUser(info.activityInfo.packageName,
3649                                    blocked, callingUserId);
3650                        }
3651                    }
3652                }
3653                return numberOfAppsUnblocked;
3654            } catch (RemoteException re) {
3655                // shouldn't happen
3656                Slog.e(LOG_TAG, "Failed to setApplicationsBlockedSettingsWithIntent", re);
3657            } finally {
3658                restoreCallingIdentity(id);
3659            }
3660            return 0;
3661        }
3662    }
3663
3664    @Override
3665    public boolean isApplicationBlocked(ComponentName who, String packageName) {
3666        int callingUserId = UserHandle.getCallingUserId();
3667        synchronized (this) {
3668            if (who == null) {
3669                throw new NullPointerException("ComponentName is null");
3670            }
3671            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3672
3673            long id = Binder.clearCallingIdentity();
3674            try {
3675                IPackageManager pm = AppGlobals.getPackageManager();
3676                return pm.getApplicationBlockedSettingAsUser(packageName, callingUserId);
3677            } catch (RemoteException re) {
3678                // shouldn't happen
3679                Slog.e(LOG_TAG, "Failed to getApplicationBlockedSettingAsUser", re);
3680            } finally {
3681                restoreCallingIdentity(id);
3682            }
3683            return false;
3684        }
3685    }
3686
3687    @Override
3688    public void setAccountManagementDisabled(ComponentName who, String accountType,
3689            boolean disabled) {
3690        if (!mHasFeature) {
3691            return;
3692        }
3693        synchronized (this) {
3694            if (who == null) {
3695                throw new NullPointerException("ComponentName is null");
3696            }
3697            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
3698                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3699            if (disabled) {
3700                ap.accountTypesWithManagementDisabled.add(accountType);
3701            } else {
3702                ap.accountTypesWithManagementDisabled.remove(accountType);
3703            }
3704            saveSettingsLocked(UserHandle.getCallingUserId());
3705        }
3706    }
3707
3708    @Override
3709    public String[] getAccountTypesWithManagementDisabled() {
3710        if (!mHasFeature) {
3711            return null;
3712        }
3713        synchronized (this) {
3714            DevicePolicyData policy = getUserData(UserHandle.getCallingUserId());
3715            final int N = policy.mAdminList.size();
3716            HashSet<String> resultSet = new HashSet<String>();
3717            for (int i = 0; i < N; i++) {
3718                ActiveAdmin admin = policy.mAdminList.get(i);
3719                resultSet.addAll(admin.accountTypesWithManagementDisabled);
3720            }
3721            return resultSet.toArray(new String[resultSet.size()]);
3722        }
3723    }
3724
3725    /**
3726     * Sets which componets may enter lock task mode.
3727     *
3728     * This function can only be called by the device owner or the profile owner.
3729     * @param components The list of components allowed to enter lock task mode.
3730     */
3731    public void setLockTaskComponents(ComponentName[] components) throws SecurityException {
3732        // Get the package names of the caller.
3733        int uid = Binder.getCallingUid();
3734        String[] packageNames = mContext.getPackageManager().getPackagesForUid(uid);
3735
3736        // Check whether any of the package name is the device owner or the profile owner.
3737        for (int i=0; i<packageNames.length; i++) {
3738            String packageName = packageNames[i];
3739            int userHandle = UserHandle.getUserId(uid);
3740            String profileOwnerPackage = getProfileOwner(userHandle);
3741            if (isDeviceOwner(packageName) ||
3742                (profileOwnerPackage != null && profileOwnerPackage.equals(packageName))) {
3743
3744                // If a package name is the device owner or the profile owner,
3745                // we update the component list.
3746                DevicePolicyData policy = getUserData(userHandle);
3747                policy.mLockTaskComponents.clear();
3748                if (components != null) {
3749                    for (int j=0; j<components.length; j++) {
3750                        ComponentName component = components[j];
3751                        policy.mLockTaskComponents.add(component);
3752                    }
3753                }
3754
3755                // Store the settings persistently.
3756                saveSettingsLocked(userHandle);
3757                return;
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 ComponentName[] getLockTaskComponents() {
3767        int userHandle = UserHandle.USER_OWNER;
3768        DevicePolicyData policy = getUserData(userHandle);
3769        ComponentName[] tempArray = policy.mLockTaskComponents.toArray(new ComponentName[0]);
3770        return tempArray;
3771    }
3772
3773    /**
3774     * This function lets the caller know whether the given component is allowed to start the
3775     * lock task mode.
3776     * @param component The component to check
3777     */
3778    public boolean isLockTaskPermitted(ComponentName component) {
3779        // Get current user's devicepolicy
3780        int uid = Binder.getCallingUid();
3781        int userHandle = UserHandle.getUserId(uid);
3782        DevicePolicyData policy = getUserData(userHandle);
3783        for (int i=0; i<policy.mLockTaskComponents.size(); i++) {
3784            ComponentName lockTaskComponent = policy.mLockTaskComponents.get(i);
3785
3786            // If the given component equals one of the component stored our device-owner-set
3787            // list, we allow this component to start the lock task mode.
3788            if (lockTaskComponent.getPackageName().equals(component.getPackageName())) {
3789                return true;
3790            }
3791        }
3792        return false;
3793    }
3794
3795    @Override
3796    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
3797        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3798            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
3799        }
3800        synchronized (this) {
3801            final DevicePolicyData policy = getUserData(userHandle);
3802            Bundle adminExtras = new Bundle();
3803            adminExtras.putBoolean(DeviceAdminReceiver.EXTRA_LOCK_TASK_ENTERING, isEnabled);
3804            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
3805            for (ActiveAdmin admin : policy.mAdminList) {
3806                boolean ownsDevice = isDeviceOwner(admin.info.getPackageName());
3807                boolean ownsProfile = (getProfileOwner(userHandle) != null
3808                        && getProfileOwner(userHandle).equals(admin.info.getPackageName()));
3809                if (ownsDevice || ownsProfile) {
3810                    sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_CHANGED,
3811                            adminExtras, null);
3812                }
3813            }
3814        }
3815    }
3816
3817    @Override
3818    public void setGlobalSetting(ComponentName who, String setting, String value) {
3819        final ContentResolver contentResolver = mContext.getContentResolver();
3820
3821        synchronized (this) {
3822            if (who == null) {
3823                throw new NullPointerException("ComponentName is null");
3824            }
3825            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3826
3827            long id = Binder.clearCallingIdentity();
3828            try {
3829                Settings.Global.putString(contentResolver, setting, value);
3830            } finally {
3831                restoreCallingIdentity(id);
3832            }
3833        }
3834    }
3835
3836    @Override
3837    public void setSecureSetting(ComponentName who, String setting, String value) {
3838        int callingUserId = UserHandle.getCallingUserId();
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            long id = Binder.clearCallingIdentity();
3848            try {
3849                Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId);
3850            } finally {
3851                restoreCallingIdentity(id);
3852            }
3853        }
3854    }
3855
3856    @Override
3857    public void setMasterVolumeMuted(ComponentName who, boolean on) {
3858        final ContentResolver contentResolver = mContext.getContentResolver();
3859
3860        synchronized (this) {
3861            if (who == null) {
3862                throw new NullPointerException("ComponentName is null");
3863            }
3864            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3865
3866            IAudioService iAudioService = IAudioService.Stub.asInterface(
3867                    ServiceManager.getService(Context.AUDIO_SERVICE));
3868            try{
3869                iAudioService.setMasterMute(on, 0, who.getPackageName(), null);
3870            } catch (RemoteException re) {
3871                Slog.e(LOG_TAG, "Failed to setMasterMute", re);
3872            }
3873        }
3874    }
3875
3876    @Override
3877    public boolean isMasterVolumeMuted(ComponentName who) {
3878        final ContentResolver contentResolver = mContext.getContentResolver();
3879
3880        synchronized (this) {
3881            if (who == null) {
3882                throw new NullPointerException("ComponentName is null");
3883            }
3884            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3885
3886            AudioManager audioManager =
3887                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
3888            return audioManager.isMasterMute();
3889        }
3890    }
3891}
3892