junixsocket

repository·main·Indexed 19 days ago

https://github.com/kohlschutter/junixsocket

A Java/JNI library enabling the use of Unix Domain Sockets (AF_UNIX) and other specialized socket families such as TIPC, VSOCK, and AF_SYSTEM directly from Java applications. It includes modules for Jetty integration, macOS-specific kernel communication via AF_SYSTEM, Linux cluster communication via TIPC, and virtual socket support via AF_VSOCK.

Tokens
17.2K
Snippets
52
Records
88
Agent score
67%

What's inside junixsocket

  1. Overview of junixsocket-darwin capabilities

    main

    junixsocket-darwin provides access to macOS-specific socket domains from Java:

    • AF_SYSTEM: Used for communicating with the Darwin Kernel. Supports UTUN_CONTROL for creating utun tunnel interfaces (similar to Linux tun).
    • AF_NDRV: A "Fake Ethernet" driver (macOS equivalent to Linux tap). Note: Support for this domain may be added in future versions.
    • AF_MULTIPATH: An Apple-private domain for Multipath-TCP/IP. Note: Support for this domain may be added in future versions.
  2. Overview of junixsocket capabilities

    main

    junixsocket is a Java/JNI library providing support for Unix Domain Sockets (AF_UNIX) and other address/protocol families (AF_TIPC, AF_VSOCK, AF_SYSTEM) within the Java ecosystem.

    Key Features:

    • Socket APIs: Supports both standard Java Socket API (java.net.Socket) and NIO (java.net.SocketChannel, etc.).
    • Socket Types: Supports both streams and datagrams.
    • Protocol Families: Includes AF_UNIX, TIPC (Linux), VSOCK (Linux/macOS VMs), and AF_SYSTEM (macOS).
    • Advanced Features: Supports peer credentials, file descriptor passing, the Linux abstract namespace, socketpair, and instantiating socket classes from file descriptors.
    • Integrations:
      • RMI: Supports Remote Method Invocation over AF_UNIX.
      • JDBC: Provides AFUNIXSocketFactory for PostgreSQL and a custom factory for MySQL Connector/J.
      • HTTP: Supports HTTP over UNIX sockets via NanoHTTPD, OkHttp, and Jetty.
    • Compatibility: Supports Java 8+ (with basic Java 7 support available in specific versions), JPMS/Jigsaw modules, and GraalVM native-image AOT compilation.
  3. Pass file descriptors and credentials via ancillary data

    main

    Unix sockets allow transmitting "ancillary data" (control messages) via sendmsg/recvmsg. This is used for more than just binary data:

    SCM_RIGHTS

    Used to send or receive file descriptors (access rights). This allows processes to share access to files, devices, or other sockets.

    SCM_CREDENTIALS / SCM_UCRED

    Used to send process credentials (UID, GID, etc.) for authentication.

    • Requirement: The socket must have the SO_PASSCRED or SO_RECVUCRED option enabled to receive these.
    • Platform Specifics: On FreeBSD and macOS, use SOL_LOCAL level options like LOCAL_CRED, LOCAL_PEERCRED, LOCAL_PEERPID, etc.
  4. Understand AF_VSOCK addressing (CID and Ports)

    main

    AF_VSOCK (Virtual Sockets) uses a two-parameter addressing scheme:

    1. Port: An unsigned 32-bit integer. Ports 0-1023 are privileged.
    2. CID (Context Identifier): A 32-bit integer identifying the context.

    Special CID Values:

    • VMADDR_CID_HYPERVISOR: The hypervisor running the VM.
    • VMADDR_CID_HOST: The host machine.
    • VMADDR_CID_ANY: A wildcard for any available CID.
    • VMADDR_CID_RESERVED: A local-only CID for loopback testing (supported by some implementations like Linux).

    Local CID Resolution: Junixsocket supports VMADDR_CID_HOST (=1). If the kernel lacks native support, junixsocket attempts to resolve the system's local CID automatically. You can retrieve the resolved CID using AFVSOCKSocket.getLocalCID(). If resolution fails, it falls back to VMADDR_CID_ANY (= -1), or VMADDR_CID_HOST (= 2) if access to /dev/vsock was denied.

  5. Understand Peer UUID limitations and macOS support

    main

    The getUUID() method in AFUNIXSocketCredentials returns the unique identifier of the process binary.

    Key constraints:

    • Platform Support: Currently, UUID support is only available on macOS.
    • Stability: The UUID is created by the linker. It remains stable unless the binary is recompiled.
    • JVM Scope: All Java programs running within the same JVM binary will share the same UUID.

    To inspect a binary's UUID manually on macOS, use: otool -l <path-to-binary> | grep uuid

  6. Use the Abstract Namespace (Linux, QNX, Windows 10)

    main

    Some platforms support an abstract namespace for sockets that is not connected to the filesystem.

    How to identify/use it:

    • A socket is in the abstract namespace if its name starts with a null byte.
    • Cleanup: unlink is typically not required upon destruction.
    • Permissions: chmod and chown have no effect.
    • Note: Do not use SUN_LEN to determine the length of sockaddr_un in this context, as it relies on strlen and may fail with null bytes.
  7. How junixsocket socket classes work

    main

    junixsocket extends the standard Java Socket and NIO APIs to support various address families (AF).

    • Socket API: AFSocket and AFServerSocket extend java.net.Socket and java.net.ServerSocket respectively. Protocol-specific implementations use prefixes (e.g., AFUNIXSocket for AF_UNIX).
    • NIO API: AFSocketChannel and AFServerSocketChannel extend the standard Java NIO socket channels.
    • Addresses: Socket addresses are subclasses of AFSocketAddress (e.g., AFUNIXSocketAddress for AF_UNIX or AFTIPCSocketAddress for AF_TIPC).
    • Interoperability: Unlike standard Java, junixsocket allows you to use SocketChannel and Socket APIs interchangeably (e.g., sc.socket() and sock.getChannel() always succeed).
  8. Use AF_SYSTEM for macOS Kernel communication and VPN tunnels

    main

    AF_SYSTEM allows userspace communication with the macOS (Darwin) Kernel.

    One key feature is UTUN_CONTROL, which enables setting up PtP tunnel interfaces (utun) from userspace. This is the macOS equivalent of Linux's tun functionality and can be used to implement VPNs.

    Note: Connecting via AF_SYSTEM typically requires root privileges, though you can send a file descriptor to a less privileged process to continue operations.

  9. Important considerations when using FileDescriptorCast

    main

    When working with FileDescriptorCast, be aware of the following:

    • Garbage Collection Risk: If you obtain a FileDescriptor from a junixsocket-controlled object within the same JVM, the original object might be garbage collected, closing the underlying resource. To prevent this, keep a reference to the original object (e.g., in a try-with-resources block) or use FileDescriptorCast.duplicating(FileDescriptor) to create a duplicate handle.
    • Blocking State: Casting to Socket, DatagramSocket, or ServerSocket may forcibly change the socket's state to "blocking".
    • Platform Specifics: On some platforms like Solaris or Illumos, you may need to re-apply a read timeout using Socket#setSoTimeout(int) after obtaining a socket via casting.
    • Port Information: You may lose Java port information for AFSocketAddress implementations that do not encode it directly (like AFUNIXSocketAddress).
  10. GraalVM support modes

    main

    junixsocket supports two modes of operation in GraalVM:

    1. Hotspot VM mode: GraalVM behaves similarly to a standard OpenJDK environment.
    2. Native Image/Substrate VM mode: GraalVM performs ahead-of-time (AOT) compilation to produce an executable binary.

    Important Note: Some optional features, such as junixsocket-rmi, are currently unavailable in Native Image mode. Since version 2.6.0, required Reachability Metadata is included within the junixsocket-common and junixsocket-selftest artifacts to support AOT compilation.

  11. Security considerations for the Abstract Namespace

    main

    The Abstract Namespace does not enforce filesystem-level permissions on socket names. This makes them inherently less secure than sockets specified by a file path.

    To mitigate this risk, you should implement peer credential checking in both directions immediately upon establishing a connection.