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