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 
17 package android.os;
18 
19 import android.annotation.SystemApi;
20 import android.util.SparseArray;
21 
22 import java.io.PrintWriter;
23 
24 /**
25  * Representation of a user on the device.
26  */
27 public 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      */
isSameUser(int uid1, int uid2)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      */
isSameApp(int uid1, int uid2)91     public static final boolean isSameApp(int uid1, int uid2) {
92         return getAppId(uid1) == getAppId(uid2);
93     }
94 
95     /** @hide */
isIsolated(int uid)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 */
isApp(int uid)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      */
getUserId(int uid)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 */
getCallingUserId()128     public static final int getCallingUserId() {
129         return getUserId(Binder.getCallingUid());
130     }
131 
132     /** @hide */
getCallingUserHandle()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      */
getUid(int userId, int appId)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      */
getAppId(int uid)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      */
getUserGid(int userId)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      */
getSharedAppGid(int id)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. Returns -1 if the ID is invalid.
183      * @hide
184      */
getAppIdFromSharedAppGid(int gid)185     public static final int getAppIdFromSharedAppGid(int gid) {
186         final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID
187                 - Process.FIRST_SHARED_APPLICATION_GID;
188         if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) {
189             return -1;
190         }
191         return appId;
192     }
193 
194     /**
195      * Generate a text representation of the uid, breaking out its individual
196      * components -- user, app, isolated, etc.
197      * @hide
198      */
formatUid(StringBuilder sb, int uid)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      */
formatUid(int uid)224     public static String formatUid(int uid) {
225         StringBuilder sb = new StringBuilder();
226         formatUid(sb, uid);
227         return sb.toString();
228     }
229 
230     /**
231      * Generate a text representation of the uid, breaking out its individual
232      * components -- user, app, isolated, etc.
233      * @hide
234      */
formatUid(PrintWriter pw, int uid)235     public static void formatUid(PrintWriter pw, int uid) {
236         if (uid < Process.FIRST_APPLICATION_UID) {
237             pw.print(uid);
238         } else {
239             pw.print('u');
240             pw.print(getUserId(uid));
241             final int appId = getAppId(uid);
242             if (appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID) {
243                 pw.print('i');
244                 pw.print(appId - Process.FIRST_ISOLATED_UID);
245             } else if (appId >= Process.FIRST_APPLICATION_UID) {
246                 pw.print('a');
247                 pw.print(appId - Process.FIRST_APPLICATION_UID);
248             } else {
249                 pw.print('s');
250                 pw.print(appId);
251             }
252         }
253     }
254 
255     /**
256      * Returns the user id of the current process
257      * @return user id of the current process
258      * @hide
259      */
260     @SystemApi
myUserId()261     public static final int myUserId() {
262         return getUserId(Process.myUid());
263     }
264 
265     /**
266      * Returns true if this UserHandle refers to the owner user; false otherwise.
267      * @return true if this UserHandle refers to the owner user; false otherwise.
268      * @hide
269      */
270     @SystemApi
isOwner()271     public final boolean isOwner() {
272         return this.equals(OWNER);
273     }
274 
275     /** @hide */
UserHandle(int h)276     public UserHandle(int h) {
277         mHandle = h;
278     }
279 
280     /**
281      * Returns the userId stored in this UserHandle.
282      * @hide
283      */
284     @SystemApi
getIdentifier()285     public int getIdentifier() {
286         return mHandle;
287     }
288 
289     @Override
toString()290     public String toString() {
291         return "UserHandle{" + mHandle + "}";
292     }
293 
294     @Override
equals(Object obj)295     public boolean equals(Object obj) {
296         try {
297             if (obj != null) {
298                 UserHandle other = (UserHandle)obj;
299                 return mHandle == other.mHandle;
300             }
301         } catch (ClassCastException e) {
302         }
303         return false;
304     }
305 
306     @Override
hashCode()307     public int hashCode() {
308         return mHandle;
309     }
310 
describeContents()311     public int describeContents() {
312         return 0;
313     }
314 
writeToParcel(Parcel out, int flags)315     public void writeToParcel(Parcel out, int flags) {
316         out.writeInt(mHandle);
317     }
318 
319     /**
320      * Write a UserHandle to a Parcel, handling null pointers.  Must be
321      * read with {@link #readFromParcel(Parcel)}.
322      *
323      * @param h The UserHandle to be written.
324      * @param out The Parcel in which the UserHandle will be placed.
325      *
326      * @see #readFromParcel(Parcel)
327      */
writeToParcel(UserHandle h, Parcel out)328     public static void writeToParcel(UserHandle h, Parcel out) {
329         if (h != null) {
330             h.writeToParcel(out, 0);
331         } else {
332             out.writeInt(USER_NULL);
333         }
334     }
335 
336     /**
337      * Read a UserHandle from a Parcel that was previously written
338      * with {@link #writeToParcel(UserHandle, Parcel)}, returning either
339      * a null or new object as appropriate.
340      *
341      * @param in The Parcel from which to read the UserHandle
342      * @return Returns a new UserHandle matching the previously written
343      * object, or null if a null had been written.
344      *
345      * @see #writeToParcel(UserHandle, Parcel)
346      */
readFromParcel(Parcel in)347     public static UserHandle readFromParcel(Parcel in) {
348         int h = in.readInt();
349         return h != USER_NULL ? new UserHandle(h) : null;
350     }
351 
352     public static final Parcelable.Creator<UserHandle> CREATOR
353             = new Parcelable.Creator<UserHandle>() {
354         public UserHandle createFromParcel(Parcel in) {
355             return new UserHandle(in);
356         }
357 
358         public UserHandle[] newArray(int size) {
359             return new UserHandle[size];
360         }
361     };
362 
363     /**
364      * Instantiate a new UserHandle from the data in a Parcel that was
365      * previously written with {@link #writeToParcel(Parcel, int)}.  Note that you
366      * must not use this with data written by
367      * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible
368      * to handle a null UserHandle here.
369      *
370      * @param in The Parcel containing the previously written UserHandle,
371      * positioned at the location in the buffer where it was written.
372      */
UserHandle(Parcel in)373     public UserHandle(Parcel in) {
374         mHandle = in.readInt();
375     }
376 }
377