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.AppIdInt;
20 import android.annotation.NonNull;
21 import android.annotation.SystemApi;
22 import android.annotation.TestApi;
23 import android.annotation.UserIdInt;
24 import android.compat.annotation.UnsupportedAppUsage;
25 
26 import java.io.PrintWriter;
27 
28 /**
29  * Representation of a user on the device.
30  */
31 public final class UserHandle implements Parcelable {
32     // NOTE: keep logic in sync with system/core/libcutils/multiuser.c
33 
34     /**
35      * @hide Range of uids allocated for a user.
36      */
37     @UnsupportedAppUsage
38     public static final int PER_USER_RANGE = 100000;
39 
40     /** @hide A user id to indicate all users on the device */
41     @UnsupportedAppUsage
42     @TestApi
43     public static final @UserIdInt int USER_ALL = -1;
44 
45     /** @hide A user handle to indicate all users on the device */
46     @SystemApi
47     @TestApi
48     public static final @NonNull UserHandle ALL = new UserHandle(USER_ALL);
49 
50     /** @hide A user id to indicate the currently active user */
51     @UnsupportedAppUsage
52     public static final @UserIdInt int USER_CURRENT = -2;
53 
54     /** @hide A user handle to indicate the current user of the device */
55     @SystemApi
56     @TestApi
57     public static final @NonNull UserHandle CURRENT = new UserHandle(USER_CURRENT);
58 
59     /** @hide A user id to indicate that we would like to send to the current
60      *  user, but if this is calling from a user process then we will send it
61      *  to the caller's user instead of failing with a security exception */
62     @UnsupportedAppUsage
63     public static final @UserIdInt int USER_CURRENT_OR_SELF = -3;
64 
65     /** @hide A user handle to indicate that we would like to send to the current
66      *  user, but if this is calling from a user process then we will send it
67      *  to the caller's user instead of failing with a security exception */
68     @UnsupportedAppUsage
69     public static final @NonNull UserHandle CURRENT_OR_SELF = new UserHandle(USER_CURRENT_OR_SELF);
70 
71     /** @hide An undefined user id */
72     @UnsupportedAppUsage
73     @TestApi
74     public static final @UserIdInt int USER_NULL = -10000;
75 
76     private static final @NonNull UserHandle NULL = new UserHandle(USER_NULL);
77 
78     /**
79      * @hide A user id constant to indicate the "owner" user of the device
80      * @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or
81      * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
82      */
83     @UnsupportedAppUsage
84     @Deprecated
85     public static final @UserIdInt int USER_OWNER = 0;
86 
87     /**
88      * @hide A user handle to indicate the primary/owner user of the device
89      * @deprecated Consider using either {@link UserHandle#SYSTEM} constant or
90      * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
91      */
92     @UnsupportedAppUsage
93     @Deprecated
94     public static final @NonNull UserHandle OWNER = new UserHandle(USER_OWNER);
95 
96     /** @hide A user id constant to indicate the "system" user of the device */
97     @UnsupportedAppUsage
98     @TestApi
99     public static final @UserIdInt int USER_SYSTEM = 0;
100 
101     /** @hide A user serial constant to indicate the "system" user of the device */
102     @UnsupportedAppUsage
103     public static final int USER_SERIAL_SYSTEM = 0;
104 
105     /** @hide A user handle to indicate the "system" user of the device */
106     @SystemApi
107     @TestApi
108     public static final @NonNull UserHandle SYSTEM = new UserHandle(USER_SYSTEM);
109 
110     /**
111      * @hide Enable multi-user related side effects. Set this to false if
112      * there are problems with single user use-cases.
113      */
114     @UnsupportedAppUsage
115     public static final boolean MU_ENABLED = true;
116 
117     /** @hide */
118     @TestApi
119     public static final int MIN_SECONDARY_USER_ID = 10;
120 
121     /**
122      * Arbitrary user handle cache size. We use the cache even when {@link #MU_ENABLED} is false
123      * anyway, so we can always assume in CTS that UserHandle.of(10) returns a cached instance
124      * even on non-multiuser devices.
125      */
126     private static final int NUM_CACHED_USERS = 4;
127 
128     private static final UserHandle[] CACHED_USER_INFOS = new UserHandle[NUM_CACHED_USERS];
129 
130     static {
131         // Not lazily initializing the cache, so that we can share them across processes.
132         // (We'll create them in zygote.)
133         for (int i = 0; i < CACHED_USER_INFOS.length; i++) {
134             CACHED_USER_INFOS[i] = new UserHandle(MIN_SECONDARY_USER_ID + i);
135         }
136     }
137 
138     /** @hide */
139     @UnsupportedAppUsage
140     public static final int ERR_GID = -1;
141     /** @hide */
142     @UnsupportedAppUsage
143     public static final int AID_ROOT = android.os.Process.ROOT_UID;
144     /** @hide */
145     @UnsupportedAppUsage
146     public static final int AID_APP_START = android.os.Process.FIRST_APPLICATION_UID;
147     /** @hide */
148     @UnsupportedAppUsage
149     public static final int AID_APP_END = android.os.Process.LAST_APPLICATION_UID;
150     /** @hide */
151     @UnsupportedAppUsage
152     public static final int AID_SHARED_GID_START = android.os.Process.FIRST_SHARED_APPLICATION_GID;
153     /** @hide */
154     @UnsupportedAppUsage
155     public static final int AID_CACHE_GID_START = android.os.Process.FIRST_APPLICATION_CACHE_GID;
156 
157     /** The userId represented by this UserHandle. */
158     @UnsupportedAppUsage
159     final @UserIdInt int mHandle;
160 
161     /**
162      * Checks to see if the user id is the same for the two uids, i.e., they belong to the same
163      * user.
164      * @hide
165      */
isSameUser(int uid1, int uid2)166     public static boolean isSameUser(int uid1, int uid2) {
167         return getUserId(uid1) == getUserId(uid2);
168     }
169 
170     /**
171      * Checks to see if both uids are referring to the same app id, ignoring the user id part of the
172      * uids.
173      * @param uid1 uid to compare
174      * @param uid2 other uid to compare
175      * @return whether the appId is the same for both uids
176      * @hide
177      */
178     @UnsupportedAppUsage
isSameApp(int uid1, int uid2)179     public static boolean isSameApp(int uid1, int uid2) {
180         return getAppId(uid1) == getAppId(uid2);
181     }
182 
183     /**
184      * Whether a UID is an "isolated" UID.
185      * @hide
186      */
187     @UnsupportedAppUsage
isIsolated(int uid)188     public static boolean isIsolated(int uid) {
189         if (uid > 0) {
190             return Process.isIsolated(uid);
191         } else {
192             return false;
193         }
194     }
195 
196     /**
197      * Whether a UID belongs to a regular app. *Note* "Not a regular app" does not mean
198      * "it's system", because of isolated UIDs. Use {@link #isCore} for that.
199      * @hide
200      */
201     @UnsupportedAppUsage
202     @TestApi
isApp(int uid)203     public static boolean isApp(int uid) {
204         if (uid > 0) {
205             final int appId = getAppId(uid);
206             return appId >= Process.FIRST_APPLICATION_UID && appId <= Process.LAST_APPLICATION_UID;
207         } else {
208             return false;
209         }
210     }
211 
212     /**
213      * Whether a UID belongs to a system core component or not.
214      * @hide
215      */
isCore(int uid)216     public static boolean isCore(int uid) {
217         if (uid >= 0) {
218             final int appId = getAppId(uid);
219             return appId < Process.FIRST_APPLICATION_UID;
220         } else {
221             return false;
222         }
223     }
224 
225     /**
226      * Returns the user for a given uid.
227      * @param uid A uid for an application running in a particular user.
228      * @return A {@link UserHandle} for that user.
229      */
getUserHandleForUid(int uid)230     public static UserHandle getUserHandleForUid(int uid) {
231         return of(getUserId(uid));
232     }
233 
234     /**
235      * Returns the user id for a given uid.
236      * @hide
237      */
238     @UnsupportedAppUsage
239     @TestApi
getUserId(int uid)240     public static @UserIdInt int getUserId(int uid) {
241         if (MU_ENABLED) {
242             return uid / PER_USER_RANGE;
243         } else {
244             return UserHandle.USER_SYSTEM;
245         }
246     }
247 
248     /** @hide */
249     @UnsupportedAppUsage
getCallingUserId()250     public static @UserIdInt int getCallingUserId() {
251         return getUserId(Binder.getCallingUid());
252     }
253 
254     /** @hide */
getCallingAppId()255     public static @AppIdInt int getCallingAppId() {
256         return getAppId(Binder.getCallingUid());
257     }
258 
259     /** @hide */
260     @TestApi
261     @SystemApi
of(@serIdInt int userId)262     public static UserHandle of(@UserIdInt int userId) {
263         if (userId == USER_SYSTEM) {
264             return SYSTEM; // Most common.
265         }
266         // These are sequential; so use a switch. Maybe they'll be optimized to a table lookup.
267         switch (userId) {
268             case USER_ALL:
269                 return ALL;
270 
271             case USER_CURRENT:
272                 return CURRENT;
273 
274             case USER_CURRENT_OR_SELF:
275                 return CURRENT_OR_SELF;
276         }
277         if (userId >= MIN_SECONDARY_USER_ID
278                 && userId < (MIN_SECONDARY_USER_ID + CACHED_USER_INFOS.length)) {
279             return CACHED_USER_INFOS[userId - MIN_SECONDARY_USER_ID];
280         }
281         if (userId == USER_NULL) { // Not common.
282             return NULL;
283         }
284         return new UserHandle(userId);
285     }
286 
287     /**
288      * Returns the uid that is composed from the userId and the appId.
289      * @hide
290      */
291     @UnsupportedAppUsage
292     @TestApi
getUid(@serIdInt int userId, @AppIdInt int appId)293     public static int getUid(@UserIdInt int userId, @AppIdInt int appId) {
294         if (MU_ENABLED) {
295             return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
296         } else {
297             return appId;
298         }
299     }
300 
301     /**
302      * Returns the app id (or base uid) for a given uid, stripping out the user id from it.
303      * @hide
304      */
305     @TestApi
306     @SystemApi
getAppId(int uid)307     public static @AppIdInt int getAppId(int uid) {
308         return uid % PER_USER_RANGE;
309     }
310 
311     /**
312      * Returns the gid shared between all apps with this userId.
313      * @hide
314      */
getUserGid(@serIdInt int userId)315     public static int getUserGid(@UserIdInt int userId) {
316         return getUid(userId, Process.SHARED_USER_GID);
317     }
318 
319     /** @hide */
getSharedAppGid(int uid)320     public static int getSharedAppGid(int uid) {
321         return getSharedAppGid(getUserId(uid), getAppId(uid));
322     }
323 
324     /** @hide */
getSharedAppGid(@serIdInt int userId, @AppIdInt int appId)325     public static int getSharedAppGid(@UserIdInt int userId, @AppIdInt int appId) {
326         if (appId >= AID_APP_START && appId <= AID_APP_END) {
327             return (appId - AID_APP_START) + AID_SHARED_GID_START;
328         } else if (appId >= AID_ROOT && appId <= AID_APP_START) {
329             return appId;
330         } else {
331             return -1;
332         }
333     }
334 
335     /**
336      * Returns the app id for a given shared app gid. Returns -1 if the ID is invalid.
337      * @hide
338      */
339     @UnsupportedAppUsage
getAppIdFromSharedAppGid(int gid)340     public static @AppIdInt int getAppIdFromSharedAppGid(int gid) {
341         final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID
342                 - Process.FIRST_SHARED_APPLICATION_GID;
343         if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) {
344             return -1;
345         }
346         return appId;
347     }
348 
349     /** @hide */
getCacheAppGid(int uid)350     public static int getCacheAppGid(int uid) {
351         return getCacheAppGid(getUserId(uid), getAppId(uid));
352     }
353 
354     /** @hide */
getCacheAppGid(@serIdInt int userId, @AppIdInt int appId)355     public static int getCacheAppGid(@UserIdInt int userId, @AppIdInt int appId) {
356         if (appId >= AID_APP_START && appId <= AID_APP_END) {
357             return getUid(userId, (appId - AID_APP_START) + AID_CACHE_GID_START);
358         } else {
359             return -1;
360         }
361     }
362 
363     /**
364      * Generate a text representation of the uid, breaking out its individual
365      * components -- user, app, isolated, etc.
366      * @hide
367      */
formatUid(StringBuilder sb, int uid)368     public static void formatUid(StringBuilder sb, int uid) {
369         if (uid < Process.FIRST_APPLICATION_UID) {
370             sb.append(uid);
371         } else {
372             sb.append('u');
373             sb.append(getUserId(uid));
374             final int appId = getAppId(uid);
375             if (isIsolated(appId)) {
376                 if (appId > Process.FIRST_ISOLATED_UID) {
377                     sb.append('i');
378                     sb.append(appId - Process.FIRST_ISOLATED_UID);
379                 } else {
380                     sb.append("ai");
381                     sb.append(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
382                 }
383             } else if (appId >= Process.FIRST_APPLICATION_UID) {
384                 sb.append('a');
385                 sb.append(appId - Process.FIRST_APPLICATION_UID);
386             } else {
387                 sb.append('s');
388                 sb.append(appId);
389             }
390         }
391     }
392 
393     /**
394      * Generate a text representation of the uid, breaking out its individual
395      * components -- user, app, isolated, etc.
396      *
397      * @param uid The uid to format
398      * @return A string representing the UID with its individual components broken out
399      * @hide
400      */
401     @SystemApi
402     @NonNull
formatUid(int uid)403     public static String formatUid(int uid) {
404         StringBuilder sb = new StringBuilder();
405         formatUid(sb, uid);
406         return sb.toString();
407     }
408 
409     /**
410      * Generate a text representation of the uid, breaking out its individual
411      * components -- user, app, isolated, etc.
412      * @hide
413      */
414     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
formatUid(PrintWriter pw, int uid)415     public static void formatUid(PrintWriter pw, int uid) {
416         if (uid < Process.FIRST_APPLICATION_UID) {
417             pw.print(uid);
418         } else {
419             pw.print('u');
420             pw.print(getUserId(uid));
421             final int appId = getAppId(uid);
422             if (isIsolated(appId)) {
423                 if (appId > Process.FIRST_ISOLATED_UID) {
424                     pw.print('i');
425                     pw.print(appId - Process.FIRST_ISOLATED_UID);
426                 } else {
427                     pw.print("ai");
428                     pw.print(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
429                 }
430             } else if (appId >= Process.FIRST_APPLICATION_UID) {
431                 pw.print('a');
432                 pw.print(appId - Process.FIRST_APPLICATION_UID);
433             } else {
434                 pw.print('s');
435                 pw.print(appId);
436             }
437         }
438     }
439 
440     /** @hide */
parseUserArg(String arg)441     public static @UserIdInt int parseUserArg(String arg) {
442         int userId;
443         if ("all".equals(arg)) {
444             userId = UserHandle.USER_ALL;
445         } else if ("current".equals(arg) || "cur".equals(arg)) {
446             userId = UserHandle.USER_CURRENT;
447         } else {
448             try {
449                 userId = Integer.parseInt(arg);
450             } catch (NumberFormatException e) {
451                 throw new IllegalArgumentException("Bad user number: " + arg);
452             }
453         }
454         return userId;
455     }
456 
457     /**
458      * Returns the user id of the current process
459      * @return user id of the current process
460      * @hide
461      */
462     @SystemApi
463     @TestApi
myUserId()464     public static @UserIdInt int myUserId() {
465         return getUserId(Process.myUid());
466     }
467 
468     /**
469      * Returns true if this UserHandle refers to the owner user; false otherwise.
470      * @return true if this UserHandle refers to the owner user; false otherwise.
471      * @hide
472      * @deprecated please use {@link #isSystem()} or check for
473      * {@link android.content.pm.UserInfo#isPrimary()}
474      * {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case.
475      */
476     @Deprecated
477     @SystemApi
isOwner()478     public boolean isOwner() {
479         return this.equals(OWNER);
480     }
481 
482     /**
483      * @return true if this UserHandle refers to the system user; false otherwise.
484      * @hide
485      */
486     @SystemApi
isSystem()487     public boolean isSystem() {
488         return this.equals(SYSTEM);
489     }
490 
491     /** @hide */
492     @UnsupportedAppUsage
UserHandle(@serIdInt int userId)493     public UserHandle(@UserIdInt int userId) {
494         mHandle = userId;
495     }
496 
497     /**
498      * Returns the userId stored in this UserHandle.
499      * @hide
500      */
501     @SystemApi
502     @TestApi
getIdentifier()503     public @UserIdInt int getIdentifier() {
504         return mHandle;
505     }
506 
507     @Override
toString()508     public String toString() {
509         return "UserHandle{" + mHandle + "}";
510     }
511 
512     @Override
equals(Object obj)513     public boolean equals(Object obj) {
514         try {
515             if (obj != null) {
516                 UserHandle other = (UserHandle)obj;
517                 return mHandle == other.mHandle;
518             }
519         } catch (ClassCastException e) {
520         }
521         return false;
522     }
523 
524     @Override
hashCode()525     public int hashCode() {
526         return mHandle;
527     }
528 
describeContents()529     public int describeContents() {
530         return 0;
531     }
532 
writeToParcel(Parcel out, int flags)533     public void writeToParcel(Parcel out, int flags) {
534         out.writeInt(mHandle);
535     }
536 
537     /**
538      * Write a UserHandle to a Parcel, handling null pointers.  Must be
539      * read with {@link #readFromParcel(Parcel)}.
540      *
541      * @param h The UserHandle to be written.
542      * @param out The Parcel in which the UserHandle will be placed.
543      *
544      * @see #readFromParcel(Parcel)
545      */
writeToParcel(UserHandle h, Parcel out)546     public static void writeToParcel(UserHandle h, Parcel out) {
547         if (h != null) {
548             h.writeToParcel(out, 0);
549         } else {
550             out.writeInt(USER_NULL);
551         }
552     }
553 
554     /**
555      * Read a UserHandle from a Parcel that was previously written
556      * with {@link #writeToParcel(UserHandle, Parcel)}, returning either
557      * a null or new object as appropriate.
558      *
559      * @param in The Parcel from which to read the UserHandle
560      * @return Returns a new UserHandle matching the previously written
561      * object, or null if a null had been written.
562      *
563      * @see #writeToParcel(UserHandle, Parcel)
564      */
readFromParcel(Parcel in)565     public static UserHandle readFromParcel(Parcel in) {
566         int h = in.readInt();
567         return h != USER_NULL ? new UserHandle(h) : null;
568     }
569 
570     public static final @android.annotation.NonNull Parcelable.Creator<UserHandle> CREATOR
571             = new Parcelable.Creator<UserHandle>() {
572         public UserHandle createFromParcel(Parcel in) {
573             // Try to avoid allocation; use of() here. Keep this and the constructor below
574             // in sync.
575             return UserHandle.of(in.readInt());
576         }
577 
578         public UserHandle[] newArray(int size) {
579             return new UserHandle[size];
580         }
581     };
582 
583     /**
584      * Instantiate a new UserHandle from the data in a Parcel that was
585      * previously written with {@link #writeToParcel(Parcel, int)}.  Note that you
586      * must not use this with data written by
587      * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible
588      * to handle a null UserHandle here.
589      *
590      * @param in The Parcel containing the previously written UserHandle,
591      * positioned at the location in the buffer where it was written.
592      */
UserHandle(Parcel in)593     public UserHandle(Parcel in) {
594         mHandle = in.readInt(); // Keep this and createFromParcel() in sync.
595     }
596 }
597