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