UserHandle.java revision 1fa7680c9cd2d6a8ae44ce9e90f2ba5dee47b219
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     * @deprecated please use {@link #isSystem()} or check for
274     * {@link android.content.pm.UserInfo#isPrimary()}
275     * {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case.
276     */
277    @SystemApi
278    public boolean isOwner() {
279        return this.equals(OWNER);
280    }
281
282    /**
283     * @return true if this UserHandle refers to the system user; false otherwise.
284     * @hide
285     */
286    @SystemApi
287    public boolean isSystem() {
288        return this.equals(SYSTEM);
289    }
290
291    /** @hide */
292    public UserHandle(int h) {
293        mHandle = h;
294    }
295
296    /**
297     * Returns the userId stored in this UserHandle.
298     * @hide
299     */
300    @SystemApi
301    public int getIdentifier() {
302        return mHandle;
303    }
304
305    @Override
306    public String toString() {
307        return "UserHandle{" + mHandle + "}";
308    }
309
310    @Override
311    public boolean equals(Object obj) {
312        try {
313            if (obj != null) {
314                UserHandle other = (UserHandle)obj;
315                return mHandle == other.mHandle;
316            }
317        } catch (ClassCastException e) {
318        }
319        return false;
320    }
321
322    @Override
323    public int hashCode() {
324        return mHandle;
325    }
326
327    public int describeContents() {
328        return 0;
329    }
330
331    public void writeToParcel(Parcel out, int flags) {
332        out.writeInt(mHandle);
333    }
334
335    /**
336     * Write a UserHandle to a Parcel, handling null pointers.  Must be
337     * read with {@link #readFromParcel(Parcel)}.
338     *
339     * @param h The UserHandle to be written.
340     * @param out The Parcel in which the UserHandle will be placed.
341     *
342     * @see #readFromParcel(Parcel)
343     */
344    public static void writeToParcel(UserHandle h, Parcel out) {
345        if (h != null) {
346            h.writeToParcel(out, 0);
347        } else {
348            out.writeInt(USER_NULL);
349        }
350    }
351
352    /**
353     * Read a UserHandle from a Parcel that was previously written
354     * with {@link #writeToParcel(UserHandle, Parcel)}, returning either
355     * a null or new object as appropriate.
356     *
357     * @param in The Parcel from which to read the UserHandle
358     * @return Returns a new UserHandle matching the previously written
359     * object, or null if a null had been written.
360     *
361     * @see #writeToParcel(UserHandle, Parcel)
362     */
363    public static UserHandle readFromParcel(Parcel in) {
364        int h = in.readInt();
365        return h != USER_NULL ? new UserHandle(h) : null;
366    }
367
368    public static final Parcelable.Creator<UserHandle> CREATOR
369            = new Parcelable.Creator<UserHandle>() {
370        public UserHandle createFromParcel(Parcel in) {
371            return new UserHandle(in);
372        }
373
374        public UserHandle[] newArray(int size) {
375            return new UserHandle[size];
376        }
377    };
378
379    /**
380     * Instantiate a new UserHandle from the data in a Parcel that was
381     * previously written with {@link #writeToParcel(Parcel, int)}.  Note that you
382     * must not use this with data written by
383     * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible
384     * to handle a null UserHandle here.
385     *
386     * @param in The Parcel containing the previously written UserHandle,
387     * positioned at the location in the buffer where it was written.
388     */
389    public UserHandle(Parcel in) {
390        mHandle = in.readInt();
391    }
392}
393