|
1 | 1 | package org.freedesktop.dbus.transport.jre; |
2 | 2 |
|
| 3 | +import jdk.net.ExtendedSocketOptions; |
| 4 | +import jdk.net.UnixDomainPrincipal; |
| 5 | + |
3 | 6 | import java.io.IOException; |
4 | 7 | import java.nio.channels.SocketChannel; |
| 8 | +import java.nio.file.attribute.UserPrincipal; |
5 | 9 |
|
6 | 10 | public final class NativeUnixSocketHelper { |
7 | 11 |
|
8 | 12 | private NativeUnixSocketHelper() {} |
9 | 13 |
|
10 | 14 | /** |
11 | 15 | * Get the UID of peer credentials. |
| 16 | + * <p> |
| 17 | + * Gathering the UID of SO_PEERCRED directly is not obvious when it comes to JDK native unix sockets.<br> |
| 18 | + * based on the implementation in {@code sun.nio.fs.UnixUserPrincipals.User},<br> |
| 19 | + * calling {@code hashCode()} on the {@link UserPrincipal} will give you either the UID or the hashCode of the name. |
| 20 | + * </p><p> |
| 21 | + * This method ensures that a proper UID is returned and not the hashCode of the name. |
| 22 | + * If there is no UID, -1 is returned. |
| 23 | + * </p> |
12 | 24 | * |
13 | 25 | * @param _sock socket to read from |
14 | | - * @return UID, -1 if given {@link SocketChannel} was null |
| 26 | + * @return UID, -1 if given {@link SocketChannel} was {@code null} or UID could not be determined |
15 | 27 | * |
16 | 28 | * @throws IOException when socket channel fails to read SO_PEERCRED option |
17 | 29 | */ |
18 | 30 | public static int getUid(SocketChannel _sock) throws IOException { |
19 | | - // gathering the UID of SO_PEERCRED is currently not possible using pure Java. |
20 | | - // The code below will only provide the username, not the UID. |
21 | | - // This does not comply with the DBus-Spec which wants UID. |
22 | | - return -1; |
23 | | -// if (_sock == null) { |
24 | | -// return -1; |
25 | | -// } |
26 | | -// |
27 | | -// UnixDomainPrincipal creds = _sock.getOption(ExtendedSocketOptions.SO_PEERCRED); |
28 | | -// UserPrincipal user = creds.user(); |
29 | | -// |
30 | | -// return Integer.parseInt(user.getName()); |
| 31 | + if (_sock == null) { |
| 32 | + return -1; |
| 33 | + } |
| 34 | + |
| 35 | + UnixDomainPrincipal creds = _sock.getOption(ExtendedSocketOptions.SO_PEERCRED); |
| 36 | + UserPrincipal user = creds.user(); |
| 37 | + |
| 38 | + int uid = -1; |
| 39 | + if (user != null && user.hashCode() != user.getName().hashCode()) { |
| 40 | + uid = user.hashCode(); |
| 41 | + } |
| 42 | + |
| 43 | + return uid; |
31 | 44 | } |
32 | 45 |
|
33 | 46 | } |
0 commit comments