UserRestrictionsUtils.java revision 3861bf7e73fab9e39e8d1f6e5194f3600ed929a0
1/*
2 * Copyright (C) 2015 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.pm;
18
19import com.google.android.collect.Sets;
20
21import com.android.internal.util.Preconditions;
22
23import android.annotation.NonNull;
24import android.annotation.Nullable;
25import android.app.ActivityManager;
26import android.app.ActivityManagerNative;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.net.Uri;
30import android.os.Binder;
31import android.os.Bundle;
32import android.os.RemoteException;
33import android.os.SystemProperties;
34import android.os.UserHandle;
35import android.os.UserManager;
36import android.telephony.SubscriptionInfo;
37import android.telephony.SubscriptionManager;
38import android.util.Log;
39
40import org.xmlpull.v1.XmlPullParser;
41import org.xmlpull.v1.XmlSerializer;
42
43import java.io.IOException;
44import java.io.PrintWriter;
45import java.util.List;
46import java.util.Set;
47
48/**
49 * Utility methods for user restrictions.
50 *
51 * <p>See {@link UserManagerService} for the method suffixes.
52 */
53public class UserRestrictionsUtils {
54    private static final String TAG = "UserRestrictionsUtils";
55
56    private UserRestrictionsUtils() {
57    }
58
59    private static Set<String> newSetWithUniqueCheck(String[] strings) {
60        final Set<String> ret = Sets.newArraySet(strings);
61
62        // Make sure there's no overlap.
63        Preconditions.checkState(ret.size() == strings.length);
64        return ret;
65    }
66
67    public static final Set<String> USER_RESTRICTIONS = newSetWithUniqueCheck(new String[] {
68            UserManager.DISALLOW_CONFIG_WIFI,
69            UserManager.DISALLOW_MODIFY_ACCOUNTS,
70            UserManager.DISALLOW_INSTALL_APPS,
71            UserManager.DISALLOW_UNINSTALL_APPS,
72            UserManager.DISALLOW_SHARE_LOCATION,
73            UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
74            UserManager.DISALLOW_CONFIG_BLUETOOTH,
75            UserManager.DISALLOW_USB_FILE_TRANSFER,
76            UserManager.DISALLOW_CONFIG_CREDENTIALS,
77            UserManager.DISALLOW_REMOVE_USER,
78            UserManager.DISALLOW_DEBUGGING_FEATURES,
79            UserManager.DISALLOW_CONFIG_VPN,
80            UserManager.DISALLOW_CONFIG_TETHERING,
81            UserManager.DISALLOW_NETWORK_RESET,
82            UserManager.DISALLOW_FACTORY_RESET,
83            UserManager.DISALLOW_ADD_USER,
84            UserManager.ENSURE_VERIFY_APPS,
85            UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
86            UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
87            UserManager.DISALLOW_APPS_CONTROL,
88            UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
89            UserManager.DISALLOW_UNMUTE_MICROPHONE,
90            UserManager.DISALLOW_ADJUST_VOLUME,
91            UserManager.DISALLOW_OUTGOING_CALLS,
92            UserManager.DISALLOW_SMS,
93            UserManager.DISALLOW_FUN,
94            UserManager.DISALLOW_CREATE_WINDOWS,
95            UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE,
96            UserManager.DISALLOW_OUTGOING_BEAM,
97            UserManager.DISALLOW_WALLPAPER,
98            UserManager.DISALLOW_SAFE_BOOT,
99            UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
100            UserManager.DISALLOW_RECORD_AUDIO,
101            UserManager.DISALLOW_CAMERA,
102            UserManager.DISALLOW_RUN_IN_BACKGROUND,
103            UserManager.DISALLOW_DATA_ROAMING,
104            UserManager.DISALLOW_SET_USER_ICON
105    });
106
107    /**
108     * Set of user restriction which we don't want to persist.
109     */
110    private static final Set<String> NON_PERSIST_USER_RESTRICTIONS = Sets.newArraySet(
111            UserManager.DISALLOW_RECORD_AUDIO
112    );
113
114    /**
115     * User restrictions that can not be set by profile owners.
116     */
117    private static final Set<String> DEVICE_OWNER_ONLY_RESTRICTIONS = Sets.newArraySet(
118            UserManager.DISALLOW_USB_FILE_TRANSFER,
119            UserManager.DISALLOW_CONFIG_TETHERING,
120            UserManager.DISALLOW_NETWORK_RESET,
121            UserManager.DISALLOW_FACTORY_RESET,
122            UserManager.DISALLOW_ADD_USER,
123            UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
124            UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
125            UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
126            UserManager.DISALLOW_SMS,
127            UserManager.DISALLOW_FUN,
128            UserManager.DISALLOW_SAFE_BOOT,
129            UserManager.DISALLOW_CREATE_WINDOWS,
130            UserManager.DISALLOW_DATA_ROAMING
131    );
132
133    /**
134     * User restrictions that can't be changed by device owner or profile owner.
135     */
136    private static final Set<String> IMMUTABLE_BY_OWNERS = Sets.newArraySet(
137            UserManager.DISALLOW_RECORD_AUDIO,
138            UserManager.DISALLOW_WALLPAPER
139    );
140
141    /**
142     * Special user restrictions that can be applied to a user as well as to all users globally,
143     * depending on callers.  When device owner sets them, they'll be applied to all users.
144     */
145    private static final Set<String> GLOBAL_RESTRICTIONS = Sets.newArraySet(
146            UserManager.DISALLOW_ADJUST_VOLUME,
147            UserManager.DISALLOW_RUN_IN_BACKGROUND,
148            UserManager.DISALLOW_UNMUTE_MICROPHONE
149    );
150
151    /**
152     * Throws {@link IllegalArgumentException} if the given restriction name is invalid.
153     */
154    public static void checkRestriction(@NonNull String restriction) {
155        if (!USER_RESTRICTIONS.contains(restriction)) {
156            throw new IllegalArgumentException("Unknown restriction: " + restriction);
157        }
158    }
159
160    public static void writeRestrictions(@NonNull XmlSerializer serializer,
161            @Nullable Bundle restrictions, @NonNull String tag) throws IOException {
162        if (restrictions == null) {
163            return;
164        }
165
166        serializer.startTag(null, tag);
167        for (String key : restrictions.keySet()) {
168            if (NON_PERSIST_USER_RESTRICTIONS.contains(key)) {
169                continue; // Don't persist.
170            }
171            if (USER_RESTRICTIONS.contains(key)) {
172                if (restrictions.getBoolean(key)) {
173                    serializer.attribute(null, key, "true");
174                }
175                continue;
176            }
177            Log.w(TAG, "Unknown user restriction detected: " + key);
178        }
179        serializer.endTag(null, tag);
180    }
181
182    public static void readRestrictions(XmlPullParser parser, Bundle restrictions)
183            throws IOException {
184        for (String key : USER_RESTRICTIONS) {
185            final String value = parser.getAttributeValue(null, key);
186            if (value != null) {
187                restrictions.putBoolean(key, Boolean.parseBoolean(value));
188            }
189        }
190    }
191
192    /**
193     * @return {@code in} itself when it's not null, or an empty bundle (which can writable).
194     */
195    public static Bundle nonNull(@Nullable Bundle in) {
196        return in != null ? in : new Bundle();
197    }
198
199    public static boolean isEmpty(@Nullable Bundle in) {
200        return (in == null) || (in.size() == 0);
201    }
202
203    /**
204     * Creates a copy of the {@code in} Bundle.  If {@code in} is null, it'll return an empty
205     * bundle.
206     *
207     * <p>The resulting {@link Bundle} is always writable. (i.e. it won't return
208     * {@link Bundle#EMPTY})
209     */
210    public static @NonNull Bundle clone(@Nullable Bundle in) {
211        return (in != null) ? new Bundle(in) : new Bundle();
212    }
213
214    public static void merge(@NonNull Bundle dest, @Nullable Bundle in) {
215        Preconditions.checkNotNull(dest);
216        Preconditions.checkArgument(dest != in);
217        if (in == null) {
218            return;
219        }
220        for (String key : in.keySet()) {
221            if (in.getBoolean(key, false)) {
222                dest.putBoolean(key, true);
223            }
224        }
225    }
226
227    /**
228     * @return true if a restriction is settable by device owner.
229     */
230    public static boolean canDeviceOwnerChange(String restriction) {
231        return !IMMUTABLE_BY_OWNERS.contains(restriction);
232    }
233
234    /**
235     * @return true if a restriction is settable by profile owner.  Note it takes a user ID because
236     * some restrictions can be changed by PO only when it's running on the system user.
237     */
238    public static boolean canProfileOwnerChange(String restriction, int userId) {
239        return !IMMUTABLE_BY_OWNERS.contains(restriction)
240                && !(userId != UserHandle.USER_SYSTEM
241                    && DEVICE_OWNER_ONLY_RESTRICTIONS.contains(restriction));
242    }
243
244    /**
245     * Takes restrictions that can be set by device owner, and sort them into what should be applied
246     * globally and what should be applied only on the current user.
247     */
248    public static void sortToGlobalAndLocal(@Nullable Bundle in, @NonNull Bundle global,
249            @NonNull Bundle local) {
250        if (in == null || in.size() == 0) {
251            return;
252        }
253        for (String key : in.keySet()) {
254            if (!in.getBoolean(key)) {
255                continue;
256            }
257            if (DEVICE_OWNER_ONLY_RESTRICTIONS.contains(key) || GLOBAL_RESTRICTIONS.contains(key)) {
258                global.putBoolean(key, true);
259            } else {
260                local.putBoolean(key, true);
261            }
262        }
263    }
264
265    /**
266     * @return true if two Bundles contain the same user restriction.
267     * A null bundle and an empty bundle are considered to be equal.
268     */
269    public static boolean areEqual(@Nullable Bundle a, @Nullable Bundle b) {
270        if (a == b) {
271            return true;
272        }
273        if (isEmpty(a)) {
274            return isEmpty(b);
275        }
276        if (isEmpty(b)) {
277            return false;
278        }
279        for (String key : a.keySet()) {
280            if (a.getBoolean(key) != b.getBoolean(key)) {
281                return false;
282            }
283        }
284        for (String key : b.keySet()) {
285            if (a.getBoolean(key) != b.getBoolean(key)) {
286                return false;
287            }
288        }
289        return true;
290    }
291
292    /**
293     * Takes a new use restriction set and the previous set, and apply the restrictions that have
294     * changed.
295     *
296     * <p>Note this method is called by {@link UserManagerService} without holding any locks.
297     */
298    public static void applyUserRestrictions(Context context, int userId,
299            Bundle newRestrictions, Bundle prevRestrictions) {
300        for (String key : USER_RESTRICTIONS) {
301            final boolean newValue = newRestrictions.getBoolean(key);
302            final boolean prevValue = prevRestrictions.getBoolean(key);
303
304            if (newValue != prevValue) {
305                applyUserRestriction(context, userId, key, newValue);
306            }
307        }
308    }
309
310    /**
311     * Apply each user restriction.
312     *
313     * <p>See also {@link
314     * com.android.providers.settings.SettingsProvider#isGlobalOrSecureSettingRestrictedForUser},
315     * which should be in sync with this method.
316     */
317    private static void applyUserRestriction(Context context, int userId, String key,
318            boolean newValue) {
319        if (UserManagerService.DBG) {
320            Log.d(TAG, "Applying user restriction: userId=" + userId
321                    + " key=" + key + " value=" + newValue);
322        }
323        // When certain restrictions are cleared, we don't update the system settings,
324        // because these settings are changeable on the Settings UI and we don't know the original
325        // value -- for example LOCATION_MODE might have been off already when the restriction was
326        // set, and in that case even if the restriction is lifted, changing it to ON would be
327        // wrong.  So just don't do anything in such a case.  If the user hopes to enable location
328        // later, they can do it on the Settings UI.
329
330        final ContentResolver cr = context.getContentResolver();
331        final long id = Binder.clearCallingIdentity();
332        try {
333            switch (key) {
334                case UserManager.DISALLOW_CONFIG_WIFI:
335                    if (newValue) {
336                        android.provider.Settings.Secure.putIntForUser(cr,
337                                android.provider.Settings.Global
338                                        .WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0, userId);
339                    }
340                    break;
341                case UserManager.DISALLOW_DATA_ROAMING:
342                    if (newValue) {
343                        // DISALLOW_DATA_ROAMING user restriction is set.
344
345                        // Multi sim device.
346                        SubscriptionManager subscriptionManager = new SubscriptionManager(context);
347                        final List<SubscriptionInfo> subscriptionInfoList =
348                            subscriptionManager.getActiveSubscriptionInfoList();
349                        if (subscriptionInfoList != null) {
350                            for (SubscriptionInfo subInfo : subscriptionInfoList) {
351                                android.provider.Settings.Global.putStringForUser(cr,
352                                    android.provider.Settings.Global.DATA_ROAMING
353                                    + subInfo.getSubscriptionId(), "0", userId);
354                            }
355                        }
356
357                        // Single sim device.
358                        android.provider.Settings.Global.putStringForUser(cr,
359                            android.provider.Settings.Global.DATA_ROAMING, "0", userId);
360                    }
361                    break;
362                case UserManager.DISALLOW_SHARE_LOCATION:
363                    if (newValue) {
364                        android.provider.Settings.Secure.putIntForUser(cr,
365                                android.provider.Settings.Secure.LOCATION_MODE,
366                                android.provider.Settings.Secure.LOCATION_MODE_OFF,
367                                userId);
368                    }
369                    // Send out notifications as some clients may want to reread the
370                    // value which actually changed due to a restriction having been
371                    // applied.
372                    final String property =
373                            android.provider.Settings.Secure.SYS_PROP_SETTING_VERSION;
374                    long version = SystemProperties.getLong(property, 0) + 1;
375                    SystemProperties.set(property, Long.toString(version));
376
377                    final String name = android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED;
378                    final Uri url = Uri.withAppendedPath(
379                            android.provider.Settings.Secure.CONTENT_URI, name);
380                    context.getContentResolver().notifyChange(url, null, true, userId);
381
382                    break;
383                case UserManager.DISALLOW_DEBUGGING_FEATURES:
384                    if (newValue) {
385                        // Only disable adb if changing for system user, since it is global
386                        // TODO: should this be admin user?
387                        if (userId == UserHandle.USER_SYSTEM) {
388                            android.provider.Settings.Global.putStringForUser(cr,
389                                    android.provider.Settings.Global.ADB_ENABLED, "0",
390                                    userId);
391                        }
392                    }
393                    break;
394                case UserManager.ENSURE_VERIFY_APPS:
395                    if (newValue) {
396                        android.provider.Settings.Global.putStringForUser(
397                                context.getContentResolver(),
398                                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, "1",
399                                userId);
400                        android.provider.Settings.Global.putStringForUser(
401                                context.getContentResolver(),
402                                android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, "1",
403                                userId);
404                    }
405                    break;
406                case UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES:
407                    if (newValue) {
408                        android.provider.Settings.Secure.putIntForUser(cr,
409                                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 0,
410                                userId);
411                    }
412                    break;
413                case UserManager.DISALLOW_RUN_IN_BACKGROUND:
414                    if (newValue) {
415                        int currentUser = ActivityManager.getCurrentUser();
416                        if (currentUser != userId && userId != UserHandle.USER_SYSTEM) {
417                            try {
418                                ActivityManagerNative.getDefault().stopUser(userId, false, null);
419                            } catch (RemoteException e) {
420                                throw e.rethrowAsRuntimeException();
421                            }
422                        }
423                    }
424            }
425        } finally {
426            Binder.restoreCallingIdentity(id);
427        }
428    }
429
430    public static void dumpRestrictions(PrintWriter pw, String prefix, Bundle restrictions) {
431        boolean noneSet = true;
432        if (restrictions != null) {
433            for (String key : restrictions.keySet()) {
434                if (restrictions.getBoolean(key, false)) {
435                    pw.println(prefix + key);
436                    noneSet = false;
437                }
438            }
439            if (noneSet) {
440                pw.println(prefix + "none");
441            }
442        } else {
443            pw.println(prefix + "null");
444        }
445    }
446}
447