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