Skip to content

Commit 4b4ae41

Browse files
committed
Issue 298: Found a way to get the UID using the hashCode
1 parent 4a7406c commit 4b4ae41

1 file changed

Lines changed: 26 additions & 13 deletions

File tree

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,46 @@
11
package org.freedesktop.dbus.transport.jre;
22

3+
import jdk.net.ExtendedSocketOptions;
4+
import jdk.net.UnixDomainPrincipal;
5+
36
import java.io.IOException;
47
import java.nio.channels.SocketChannel;
8+
import java.nio.file.attribute.UserPrincipal;
59

610
public final class NativeUnixSocketHelper {
711

812
private NativeUnixSocketHelper() {}
913

1014
/**
1115
* 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>
1224
*
1325
* @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
1527
*
1628
* @throws IOException when socket channel fails to read SO_PEERCRED option
1729
*/
1830
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;
3144
}
3245

3346
}

0 commit comments

Comments
 (0)