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