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