Documentation
¶
Overview ¶
Package socket provides Linux message sockets, ancillary file/credential handling, and selected Netlink options. It requires Linux 7.0 or later.
Pair creates Unix datagram or seqpacket peers; ListenUnix binds datagrams; OpenNetlink binds a Netlink endpoint. Each Conn owns its descriptor. Close releases it and interrupts pending I/O. Nonblocking, close-on-exec creation and Go polling are mandatory; constructors return no resource on failure.
Send and Receive preserve message boundaries. Receive exposes payload and control truncation and returns owned *os.File values for received rights. Always close successful message.Files, even when payload truncation occurred. Files passed to Send remain caller-owned. No public raw descriptors are needed. Use net for TCP, UDP, Unix streams, and stream connection management.
See socket(7), unix(7), netlink(7), sendmsg(2), and recvmsg(2).
Index ¶
- func Pair(mode Kind) (*Conn, *Conn, error)
- type Address
- type Conn
- func (c *Conn) Close() error
- func (c *Conn) DisableCapAck() error
- func (c *Conn) DisableExtendedAck() error
- func (c *Conn) DisablePassCredentials() error
- func (c *Conn) DisableStrictCheck() error
- func (c *Conn) EnableCapAck() error
- func (c *Conn) EnableExtendedAck() error
- func (c *Conn) EnablePassCredentials() error
- func (c *Conn) EnableStrictCheck() error
- func (c *Conn) JoinGroup(group uint32) error
- func (c *Conn) LeaveGroup(group uint32) error
- func (c *Conn) LocalAddress() (Address, error)
- func (c *Conn) PeerCredentials() (Credentials, error)
- func (c *Conn) Receive(p []byte, maxFiles int) (Message, error)
- func (c *Conn) Send(p []byte, to Address, files ...*os.File) (int, error)
- func (c *Conn) SetDeadline(deadline time.Time) error
- func (c *Conn) SetReadBuffer(bytes int) error
- func (c *Conn) SetReadDeadline(deadline time.Time) error
- func (c *Conn) SetWriteBuffer(bytes int) error
- func (c *Conn) SetWriteDeadline(deadline time.Time) error
- type Credentials
- type Kind
- type Message
- type MessageFlags
- type NetlinkAddress
- type Protocol
- type UnixAddress
- type UnixAddressMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Pair ¶
Pair creates connected Unix sockets using socketpair(2). Only Datagram and SeqPacket are supported. Both returned owners must be closed. Failure closes both ends and returns neither. Invalid modes match os.ErrInvalid.
Example ¶
package main
import (
"fmt"
"time"
"github.com/alexfalkowski/go-linux/v2/socket"
)
func main() {
sender, receiver, err := socket.Pair(socket.Datagram)
if err != nil {
panic(err)
}
defer sender.Close()
defer receiver.Close()
if err := receiver.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
panic(err)
}
if _, err := sender.Send([]byte("one record"), nil); err != nil {
panic(err)
}
buffer := make([]byte, 64)
message, err := receiver.Receive(buffer, 0)
if err != nil {
panic(err)
}
fmt.Println(string(buffer[:message.N]), message.Flags&socket.Truncated != 0)
}
Output: one record false
Types ¶
type Address ¶
Address is a UnixAddress or NetlinkAddress value. It implements net.Addr; external implementations and pointers to these values are not accepted.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn owns a nonblocking, close-on-exec message socket with Go polling. Methods are safe concurrently; concurrent receivers compete for messages. Call sequences, socket options, and request/response matching require caller coordination. Do not copy a Conn after use. The zero value owns nothing and returns os.ErrInvalid; nil receivers are unsupported. Valid operations after Close match os.ErrClosed. Invalid arguments take precedence over closed state.
Conn implements io.Closer, but not net.Conn, net.PacketConn, io.Reader, or io.Writer: message boundaries, ancillary ownership, and truncation must remain visible. No underlying descriptor or raw callback is exposed.
func ListenUnix ¶
func ListenUnix(address UnixAddress) (*Conn, error)
ListenUnix binds an owned Unix datagram socket using bind(2). Empty names and filesystem names containing NULs match os.ErrInvalid. A leading @ or NUL selects the abstract namespace by default. Set UnixAddress.Interpretation to LiteralPathname for a filesystem name that starts with @. Embedded NULs are preserved in abstract names. A successful filesystem binding leaves a socket path that the caller must unlink after Close. Close never removes or replaces paths. Failure closes every acquired descriptor and returns no owner.
func OpenNetlink ¶
func OpenNetlink(protocol Protocol, address NetlinkAddress) (*Conn, error)
OpenNetlink binds an owned SOCK_RAW Netlink socket using netlink(7). PortID zero requests allocation; LocalAddress returns the assigned ID. Groups joins the legacy mask at bind time and may require privilege. Negative protocols match os.ErrInvalid. Failure closes all acquired resources.
Example ¶
package main
import (
"fmt"
"github.com/alexfalkowski/go-linux/v2/socket"
)
func main() {
conn, err := socket.OpenNetlink(socket.Route, socket.NetlinkAddress{})
if err != nil {
panic(err)
}
defer conn.Close()
if err := conn.EnableExtendedAck(); err != nil {
panic(err)
}
address, err := conn.LocalAddress()
if err != nil {
panic(err)
}
fmt.Println(address.Network(), address.(socket.NetlinkAddress).PortID != 0)
}
Output: netlink true
func (*Conn) Close ¶
Close releases this descriptor and interrupts pending Send/Receive with os.ErrClosed. It does not close sent or previously received files. Repeated Close matches os.ErrClosed. A zero Conn returns os.ErrInvalid.
func (*Conn) DisableCapAck ¶
DisableCapAck clears the NETLINK_CAP_ACK request. Other families match os.ErrInvalid.
func (*Conn) DisableExtendedAck ¶
DisableExtendedAck clears the request for NETLINK_EXT_ACK diagnostic attributes. Other families match os.ErrInvalid.
func (*Conn) DisablePassCredentials ¶
DisablePassCredentials disables SO_PASSCRED. Other families match os.ErrInvalid.
func (*Conn) DisableStrictCheck ¶
DisableStrictCheck clears the NETLINK_GET_STRICT_CHK request. Other families match os.ErrInvalid.
func (*Conn) EnableCapAck ¶
EnableCapAck requests NETLINK_CAP_ACK, allowing capped acknowledgement payloads. Other families match os.ErrInvalid. Decoders must inspect response flags.
func (*Conn) EnableExtendedAck ¶
EnableExtendedAck requests NETLINK_EXT_ACK diagnostic attributes. Other families match os.ErrInvalid. Decoding belongs to the caller.
func (*Conn) EnablePassCredentials ¶
EnablePassCredentials enables SO_PASSCRED on Unix sockets so Receive can return kernel-validated sender credentials. Linux may autobind an unnamed socket. Other families match os.ErrInvalid.
func (*Conn) EnableStrictCheck ¶
EnableStrictCheck requests NETLINK_GET_STRICT_CHK for supported route dumps. Validation remains protocol-specific. Other families match os.ErrInvalid.
func (*Conn) JoinGroup ¶
JoinGroup adds a Netlink multicast membership using NETLINK_ADD_MEMBERSHIP. Group is a positive numeric group ID, not a bitmask; joining may require privilege. Invalid IDs/families match os.ErrInvalid. Kernel errno is retained.
func (*Conn) LeaveGroup ¶
LeaveGroup drops a membership using NETLINK_DROP_MEMBERSHIP and JoinGroup's validation. Membership changes are individual kernel operations.
func (*Conn) LocalAddress ¶
LocalAddress reads getsockname(2); Unix pairs return an unnamed UnixAddress.
func (*Conn) PeerCredentials ¶
func (c *Conn) PeerCredentials() (Credentials, error)
PeerCredentials reads SO_PEERCRED on connected Unix pairs. Credentials are captured at socketpair creation, not refreshed for later changes or senders. Unconnected sockets retain Linux's result; other families match os.ErrInvalid.
func (*Conn) Receive ¶
Receive consumes one message using recvmsg(2), waiting for a message, a read deadline, or Close. MaxFiles (0..253) bounds returned SCM_RIGHTS references; invalid limits match os.ErrInvalid without consuming a message. Nil/empty p still consumes a message and reports Truncated when bytes were discarded. Payload truncation returns copied bytes and Truncated without an error.
Credentials are decoded when present (see EnablePassCredentials). Ancillary truncation or more than maxFiles rights returns EMSGSIZE and no files; all received references close, including when another decoding error occurs. Linux closes rights that do not fit the ancillary buffer. MSG_CMSG_CLOEXEC atomically protects received rights across exec. Unknown controls are ignored.
Zero-length records return N=0, nil error. SeqPacket peer shutdown also returns N=0, nil error, as recvmsg cannot distinguish it from an empty record; applications needing EOF must exclude empty records in their protocol.
func (*Conn) Send ¶
Send sends exactly one message using sendmsg(2). To is nil for a Unix pair; bound Unix datagrams require a UnixAddress, and Netlink requires a NetlinkAddress (zero selects the kernel). Wrong families and address pointers match os.ErrInvalid. Unix sockets support empty messages; Netlink rejects empty payloads with ENODATA.
Files borrows up to 253 files for SCM_RIGHTS on Unix sockets. With files, at least one payload byte is required. Nil files match os.ErrInvalid. Each input is duplicated under lifetime protection before waiting; all temporary references close on success or failure. Inputs remain caller-owned. Received references share open-file-description state. A send failure never requires caller error-path cleanup. Unix pairs wait for capacity, a deadline, or Close. Sends with an explicit Unix or Netlink destination instead return EAGAIN when capacity is unavailable: sender writability cannot track that destination's queue. Callers choose whether and when to retry. MSG_NOSIGNAL prevents SIGPIPE, and errno identity is preserved.
Example ¶
package main
import (
"fmt"
"os"
"time"
"github.com/alexfalkowski/go-linux/v2/socket"
)
func main() {
sender, receiver, err := socket.Pair(socket.SeqPacket)
if err != nil {
panic(err)
}
defer sender.Close()
defer receiver.Close()
if err := receiver.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
panic(err)
}
file, err := os.CreateTemp("", "socket-example-*")
if err != nil {
panic(err)
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteAt([]byte("shared file"), 0); err != nil {
panic(err)
}
if _, err := sender.Send([]byte("file"), nil, file); err != nil {
panic(err)
}
message, err := receiver.Receive(make([]byte, 32), 1)
if err != nil {
panic(err) // No received files need closing on error.
}
for _, received := range message.Files {
defer received.Close()
}
buffer := make([]byte, 11)
if _, err := message.Files[0].ReadAt(buffer, 0); err != nil {
panic(err)
}
fmt.Println(string(buffer))
}
Output: shared file
func (*Conn) SetDeadline ¶
SetDeadline wraps os.File.SetDeadline for pending and future message I/O. Zero clears both deadlines; expiry matches os.ErrDeadlineExceeded.
func (*Conn) SetReadBuffer ¶
SetReadBuffer requests SO_RCVBUF bytes. Linux doubles the request for bookkeeping, enforces limits, and may clamp it. Sizes outside 1..2^31-1 match os.ErrInvalid. This is not a guarantee of queue capacity or losslessness.
func (*Conn) SetReadDeadline ¶
SetReadDeadline wraps os.File.SetReadDeadline without changing write deadlines.
func (*Conn) SetWriteBuffer ¶
SetWriteBuffer requests SO_SNDBUF bytes with SetReadBuffer's validation and Linux sizing rules.
type Credentials ¶
type Credentials struct {
// PID is the kernel-validated message PID (sender PID by default),
// or the connection-time peer PID.
PID int32
// UID is the kernel-validated message UID (real UID by default),
// or the connection-time peer effective UID.
UID uint32
// GID is the kernel-validated message GID (real GID by default),
// or the connection-time peer effective GID.
GID uint32
}
Credentials contains Linux process credentials. IDs are interpreted in the receiving process's namespaces; they are observations, not authorization.
type Kind ¶
type Kind int
Kind selects a Unix socket-pair mode. Modes are exclusive, not flags.
const Datagram Kind = unix.SOCK_DGRAM
Datagram preserves independent messages (SOCK_DGRAM).
const SeqPacket Kind = unix.SOCK_SEQPACKET
SeqPacket preserves ordered messages on a connection (SOCK_SEQPACKET).
type Message ¶
type Message struct {
// From is the sender, or nil for an unnamed connected peer.
From Address
// Credentials contains kernel-validated SCM_CREDENTIALS, or nil when absent.
Credentials *Credentials
// Files are new caller-owned, close-on-exec references from SCM_RIGHTS.
// They share offsets/status flags with the sender and must each be closed.
Files []*os.File
// N is the number of bytes copied into Receive's payload buffer.
N int
// Flags contains Linux output flags; inspect Truncated even on success.
Flags MessageFlags
}
Message describes one consumed message. Payload bytes are in Receive's buffer. On any error Files is nil: the receiver never owns error-path cleanup.
type MessageFlags ¶
type MessageFlags int
MessageFlags preserves recvmsg(2) output flags, including unknown bits.
const ControlTruncated MessageFlags = unix.MSG_CTRUNC
ControlTruncated means ancillary data was discarded by Linux (MSG_CTRUNC).
const Truncated MessageFlags = unix.MSG_TRUNC
Truncated means the payload exceeded the supplied buffer (MSG_TRUNC). The unread tail was discarded; N still counts only copied bytes.
type NetlinkAddress ¶
type NetlinkAddress struct {
// PortID is the Linux nl_pid value in the current network namespace.
PortID uint32
// Groups is the legacy nl_groups bitmask; use JoinGroup for larger group IDs.
Groups uint32
}
NetlinkAddress identifies a Netlink port and the legacy 32-bit group mask. A port ID is not necessarily a process ID. Port zero selects the kernel for Send and requests automatic port allocation for OpenNetlink.
func (NetlinkAddress) String ¶
func (a NetlinkAddress) String() string
String formats the decimal port ID and group mask, separated by a colon.
type Protocol ¶
type Protocol int
Protocol selects an AF_NETLINK protocol. Nonnegative Linux protocol numbers are accepted; unavailable protocols fail with their original errno.
const Generic Protocol = unix.NETLINK_GENERIC
Generic selects NETLINK_GENERIC for Generic Netlink families.
const Route Protocol = unix.NETLINK_ROUTE
Route selects NETLINK_ROUTE for routing and link messages.
const Usersock Protocol = unix.NETLINK_USERSOCK
Usersock selects NETLINK_USERSOCK for user-space messaging.
type UnixAddress ¶
type UnixAddress struct {
// Name is a filesystem path or abstract socket name, limited by sockaddr_un.
Name string
// Interpretation selects UnixAddressShorthand or LiteralPathname. Receive
// and LocalAddress select LiteralPathname for leading-@ or full-length
// (108-byte) pathnames so replies preserve them.
Interpretation UnixAddressMode
}
UnixAddress names a Unix datagram endpoint or an unnamed Unix pair. Like net.UnixAddr on Linux, Name "@app" selects the abstract socket whose kernel name is "\x00app"; an initial NUL is also accepted. Abstract sockets create no filesystem entry. Use LiteralPathname for literal filesystem names such as "@app".
Empty means unnamed on received addresses and is invalid for ListenUnix. Preserve the complete address returned in Message.From when replying: Name alone cannot distinguish a leading-@ filesystem path from an abstract name.
func (UnixAddress) String ¶
func (a UnixAddress) String() string
String returns the display name. Use the complete UnixAddress when sending a reply so the interpretation is preserved.
type UnixAddressMode ¶
type UnixAddressMode uint8
UnixAddressMode controls how a Unix address name is interpreted.
const LiteralPathname UnixAddressMode = 1
LiteralPathname interprets the whole name as a filesystem path, including a leading @. NUL bytes are invalid.
const UnixAddressShorthand UnixAddressMode = 0
UnixAddressShorthand treats a leading @ or NUL as an abstract address. Other names are filesystem paths. This is the default.