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