UserHandle.java revision cbc3ccec61814d911f9730fd63c32a87b126eb55
1/*
2 * Copyright (C) 2011 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 android.os;
18
19import android.annotation.AppIdInt;
20import android.annotation.SystemApi;
21import android.annotation.TestApi;
22import android.annotation.UserIdInt;
23
24import java.io.PrintWriter;
25
26/**
27 * Representation of a user on the device.
28 */
29public final class UserHandle implements Parcelable {
30    // NOTE: keep logic in sync with system/core/libcutils/multiuser.c
31
32    /**
33     * @hide Range of uids allocated for a user.
34     */
35    public static final int PER_USER_RANGE = 100000;
36
37    /** @hide A user id to indicate all users on the device */
38    public static final @UserIdInt int USER_ALL = -1;
39
40    /** @hide A user handle to indicate all users on the device */
41    public static final UserHandle ALL = new UserHandle(USER_ALL);
42
43    /** @hide A user id to indicate the currently active user */
44    public static final @UserIdInt int USER_CURRENT = -2;
45
46    /** @hide A user handle to indicate the current user of the device */
47    public static final UserHandle CURRENT = new UserHandle(USER_CURRENT);
48
49    /** @hide A user id to indicate that we would like to send to the current
50     *  user, but if this is calling from a user process then we will send it
51     *  to the caller's user instead of failing with a security exception */
52    public static final @UserIdInt int USER_CURRENT_OR_SELF = -3;
53
54    /** @hide A user handle to indicate that we would like to send to the current
55     *  user, but if this is calling from a user process then we will send it
56     *  to the caller's user instead of failing with a security exception */
57    public static final UserHandle CURRENT_OR_SELF = new UserHandle(USER_CURRENT_OR_SELF);
58
59    /** @hide An undefined user id */
60    public static final @UserIdInt int USER_NULL = -10000;
61
62    /**
63     * @hide A user id constant to indicate the "owner" user of the device
64     * @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or
65     * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
66     */
67    @Deprecated
68    public static final @UserIdInt int USER_OWNER = 0;
69
70    /**
71     * @hide A user handle to indicate the primary/owner user of the device
72     * @deprecated Consider using either {@link UserHandle#SYSTEM} constant or
73     * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
74     */
75    @Deprecated
76    public static final UserHandle OWNER = new UserHandle(USER_OWNER);
77
78    /** @hide A user id constant to indicate the "system" user of the device */
79    public static final @UserIdInt int USER_SYSTEM = 0;
80
81    /** @hide A user serial constant to indicate the "system" user of the device */
82    public static final int USER_SERIAL_SYSTEM = 0;
83
84    /** @hide A user handle to indicate the "system" user of the device */
85    public static final UserHandle SYSTEM = new UserHandle(USER_SYSTEM);
86
87    /**
88     * @hide Enable multi-user related side effects. Set this to false if
89     * there are problems with single user use-cases.
90     */
91    public static final boolean MU_ENABLED = true;
92
93    /** @hide */
94    public static final int ERR_GID = -1;
95    /** @hide */
96    public static final int AID_ROOT = android.os.Process.ROOT_UID;
97    /** @hide */
98    public static final int AID_APP_START = android.os.Process.FIRST_APPLICATION_UID;
99    /** @hide */
100    public static final int AID_APP_END = android.os.Process.LAST_APPLICATION_UID;
101    /** @hide */
102    public static final int AID_SHARED_GID_START = android.os.Process.FIRST_SHARED_APPLICATION_GID;
103    /** @hide */
104    public static final int AID_CACHE_GID_START = android.os.Process.FIRST_APPLICATION_CACHE_GID;
105
106    final int mHandle;
107
108    /**
109     * Checks to see if the user id is the same for the two uids, i.e., they belong to the same
110     * user.
111     * @hide
112     */
113    public static boolean isSameUser(int uid1, int uid2) {
114        return getUserId(uid1) == getUserId(uid2);
115    }
116
117    /**
118     * Checks to see if both uids are referring to the same app id, ignoring the user id part of the
119     * uids.
120     * @param uid1 uid to compare
121     * @param uid2 other uid to compare
122     * @return whether the appId is the same for both uids
123     * @hide
124     */
125    public static boolean isSameApp(int uid1, int uid2) {
126        return getAppId(uid1) == getAppId(uid2);
127    }
128
129    /**
130     * Whether a UID is an "isolated" UID.
131     * @hide
132     */
133    public static boolean isIsolated(int uid) {
134        if (uid > 0) {
135            final int appId = getAppId(uid);
136            return appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID;
137        } else {
138            return false;
139        }
140    }
141
142    /**
143     * Whether a UID belongs to a regular app. *Note* "Not a regular app" does not mean
144     * "it's system", because of isolated UIDs. Use {@link #isCore} for that.
145     * @hide
146     */
147    public static boolean isApp(int uid) {
148        if (uid > 0) {
149            final int appId = getAppId(uid);
150            return appId >= Process.FIRST_APPLICATION_UID && appId <= Process.LAST_APPLICATION_UID;
151        } else {
152            return false;
153        }
154    }
155
156    /**
157     * Whether a UID belongs to a system core component or not.
158     * @hide
159     */
160    public static boolean isCore(int uid) {
161        if (uid >= 0) {
162            final int appId = getAppId(uid);
163            return appId < Process.FIRST_APPLICATION_UID;
164        } else {
165            return false;
166        }
167    }
168
169    /**
170     * Returns the user for a given uid.
171     * @param uid A uid for an application running in a particular user.
172     * @return A {@link UserHandle} for that user.
173     */
174    public static UserHandle getUserHandleForUid(int uid) {
175        return of(getUserId(uid));
176    }
177
178    /**
179     * Returns the user id for a given uid.
180     * @hide
181     */
182    public static @UserIdInt int getUserId(int uid) {
183        if (MU_ENABLED) {
184            return uid / PER_USER_RANGE;
185        } else {
186            return UserHandle.USER_SYSTEM;
187        }
188    }
189
190    /** @hide */
191    public static @UserIdInt int getCallingUserId() {
192        return getUserId(Binder.getCallingUid());
193    }
194
195    /** @hide */
196    public static @AppIdInt int getCallingAppId() {
197        return getAppId(Binder.getCallingUid());
198    }
199
200    /** @hide */
201    @SystemApi
202    public static UserHandle of(@UserIdInt int userId) {
203        return userId == USER_SYSTEM ? SYSTEM : new UserHandle(userId);
204    }
205
206    /**
207     * Returns the uid that is composed from the userId and the appId.
208     * @hide
209     */
210    public static int getUid(@UserIdInt int userId, @AppIdInt int appId) {
211        if (MU_ENABLED) {
212            return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
213        } else {
214            return appId;
215        }
216    }
217
218    /**
219     * Returns the app id (or base uid) for a given uid, stripping out the user id from it.
220     * @hide
221     */
222    @TestApi
223    public static @AppIdInt int getAppId(int uid) {
224        return uid % PER_USER_RANGE;
225    }
226
227    /**
228     * Returns the gid shared between all apps with this userId.
229     * @hide
230     */
231    public static int getUserGid(@UserIdInt int userId) {
232        return getUid(userId, Process.SHARED_USER_GID);
233    }
234
235    /** @hide */
236    public static int getSharedAppGid(int uid) {
237        return getSharedAppGid(getUserId(uid), getAppId(uid));
238    }
239
240    /** @hide */
241    public static int getSharedAppGid(int userId, int appId) {
242        if (appId >= AID_APP_START && appId <= AID_APP_END) {
243            return (appId - AID_APP_START) + AID_SHARED_GID_START;
244        } else if (appId >= AID_ROOT && appId <= AID_APP_START) {
245            return appId;
246        } else {
247            return -1;
248        }
249    }
250
251    /**
252     * Returns the app id for a given shared app gid. Returns -1 if the ID is invalid.
253     * @hide
254     */
255    public static @AppIdInt int getAppIdFromSharedAppGid(int gid) {
256        final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID
257                - Process.FIRST_SHARED_APPLICATION_GID;
258        if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) {
259            return -1;
260        }
261        return appId;
262    }
263
264    /** @hide */
265    public static int getCacheAppGid(int uid) {
266        return getCacheAppGid(getUserId(uid), getAppId(uid));
267    }
268
269    /** @hide */
270    public static int getCacheAppGid(int userId, int appId) {
271        if (appId >= AID_APP_START && appId <= AID_APP_END) {
272            return getUid(userId, (appId - AID_APP_START) + AID_CACHE_GID_START);
273        } else {
274            return -1;
275        }
276    }
277
278    /**
279     * Generate a text representation of the uid, breaking out its individual
280     * components -- user, app, isolated, etc.
281     * @hide
282     */
283    public static void formatUid(StringBuilder sb, int uid) {
284        if (uid < Process.FIRST_APPLICATION_UID) {
285            sb.append(uid);
286        } else {
287            sb.append('u');
288            sb.append(getUserId(uid));
289            final int appId = getAppId(uid);
290            if (appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID) {
291                sb.append('i');
292                sb.append(appId - Process.FIRST_ISOLATED_UID);
293            } else if (appId >= Process.FIRST_APPLICATION_UID) {
294                sb.append('a');
295                sb.append(appId - Process.FIRST_APPLICATION_UID);
296            } else {
297                sb.append('s');
298                sb.append(appId);
299            }
300        }
301    }
302
303    /**
304     * Generate a text representation of the uid, breaking out its individual
305     * components -- user, app, isolated, etc.
306     * @hide
307     */
308    public static String formatUid(int uid) {
309        StringBuilder sb = new StringBuilder();
310        formatUid(sb, uid);
311        return sb.toString();
312    }
313
314    /**
315     * Generate a text representation of the uid, breaking out its individual
316     * components -- user, app, isolated, etc.
317     * @hide
318     */
319    public static void formatUid(PrintWriter pw, int uid) {
320        if (uid < Process.FIRST_APPLICATION_UID) {
321            pw.print(uid);
322        } else {
323            pw.print('u');
324            pw.print(getUserId(uid));
325            final int appId = getAppId(uid);
326            if (appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID) {
327                pw.print('i');
328                pw.print(appId - Process.FIRST_ISOLATED_UID);
329            } else if (appId >= Process.FIRST_APPLICATION_UID) {
330                pw.print('a');
331                pw.print(appId - Process.FIRST_APPLICATION_UID);
332            } else {
333                pw.print('s');
334                pw.print(appId);
335            }
336        }
337    }
338
339    /** @hide */
340    public static @UserIdInt int parseUserArg(String arg) {
341        int userId;
342        if ("all".equals(arg)) {
343            userId = UserHandle.USER_ALL;
344        } else if ("current".equals(arg) || "cur".equals(arg)) {
345            userId = UserHandle.USER_CURRENT;
346        } else {
347            try {
348                userId = Integer.parseInt(arg);
349            } catch (NumberFormatException e) {
350                throw new IllegalArgumentException("Bad user number: " + arg);
351            }
352        }
353        return userId;
354    }
355
356    /**
357     * Returns the user id of the current process
358     * @return user id of the current process
359     * @hide
360     */
361    @SystemApi
362    public static @UserIdInt int myUserId() {
363        return getUserId(Process.myUid());
364    }
365
366    /**
367     * Returns true if this UserHandle refers to the owner user; false otherwise.
368     * @return true if this UserHandle refers to the owner user; false otherwise.
369     * @hide
370     * @deprecated please use {@link #isSystem()} or check for
371     * {@link android.content.pm.UserInfo#isPrimary()}
372     * {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case.
373     */
374    @Deprecated
375    @SystemApi
376    public boolean isOwner() {
377        return this.equals(OWNER);
378    }
379
380    /**
381     * @return true if this UserHandle refers to the system user; false otherwise.
382     * @hide
383     */
384    @SystemApi
385    public boolean isSystem() {
386        return this.equals(SYSTEM);
387    }
388
389    /** @hide */
390    public UserHandle(int h) {
391        mHandle = h;
392    }
393
394    /**
395     * Returns the userId stored in this UserHandle.
396     * @hide
397     */
398    @SystemApi
399    @TestApi
400    public @UserIdInt int getIdentifier() {
401        return mHandle;
402    }
403
404    @Override
405    public String toString() {
406        return "UserHandle{" + mHandle + "}";
407    }
408
409    @Override
410    public boolean equals(Object obj) {
411        try {
412            if (obj != null) {
413                UserHandle other = (UserHandle)obj;
414                return mHandle == other.mHandle;
415            }
416        } catch (ClassCastException e) {
417        }
418        return false;
419    }
420
421    @Override
422    public int hashCode() {
423        return mHandle;
424    }
425
426    public int describeContents() {
427        return 0;
428    }
429
430    public void writeToParcel(Parcel out, int flags) {
431        out.writeInt(mHandle);
432    }
433
434    /**
435     * Write a UserHandle to a Parcel, handling null pointers.  Must be
436     * read with {@link #readFromParcel(Parcel)}.
437     *
438     * @param h The UserHandle to be written.
439     * @param out The Parcel in which the UserHandle will be placed.
440     *
441     * @see #readFromParcel(Parcel)
442     */
443    public static void writeToParcel(UserHandle h, Parcel out) {
444        if (h != null) {
445            h.writeToParcel(out, 0);
446        } else {
447            out.writeInt(USER_NULL);
448        }
449    }
450
451    /**
452     * Read a UserHandle from a Parcel that was previously written
453     * with {@link #writeToParcel(UserHandle, Parcel)}, returning either
454     * a null or new object as appropriate.
455     *
456     * @param in The Parcel from which to read the UserHandle
457     * @return Returns a new UserHandle matching the previously written
458     * object, or null if a null had been written.
459     *
460     * @see #writeToParcel(UserHandle, Parcel)
461     */
462    public static UserHandle readFromParcel(Parcel in) {
463        int h = in.readInt();
464        return h != USER_NULL ? new UserHandle(h) : null;
465    }
466
467    public static final Parcelable.Creator<UserHandle> CREATOR
468            = new Parcelable.Creator<UserHandle>() {
469        public UserHandle createFromParcel(Parcel in) {
470            return new UserHandle(in);
471        }
472
473        public UserHandle[] newArray(int size) {
474            return new UserHandle[size];
475        }
476    };
477
478    /**
479     * Instantiate a new UserHandle from the data in a Parcel that was
480     * previously written with {@link #writeToParcel(Parcel, int)}.  Note that you
481     * must not use this with data written by
482     * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible
483     * to handle a null UserHandle here.
484     *
485     * @param in The Parcel containing the previously written UserHandle,
486     * positioned at the location in the buffer where it was written.
487     */
488    public UserHandle(Parcel in) {
489        mHandle = in.readInt();
490    }
491}
492