aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/uevent/uevent.go
blob: 12754f46df9a50b58046b20c29796b1ea9149143 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Package uevent provides userspace client for consuming events from a
// NETLINK_KOBJECT_UEVENT socket, as well as helpers for supplementing
// events received from the kernel.
package uevent

import (
	"sync/atomic"
	"syscall"

	"hakurei.app/internal/netlink"
)

type (
	// Recoverable is satisfied by errors that are safe to recover from.
	Recoverable interface{ recoverable() }
	// Nontrivial is satisfied by errors preferring a JSON encoding.
	Nontrivial interface{ nontrivial() }
)

// Conn represents a NETLINK_KOBJECT_UEVENT socket.
type Conn struct {
	conn *netlink.Conn

	// Whether currently between a call to enterExcl and exitExcl.
	excl atomic.Bool
}

// enterExcl must be called entering a critical section that interacts with conn.
func (c *Conn) enterExcl() error {
	if !c.excl.CompareAndSwap(false, true) {
		return syscall.EAGAIN
	}
	return nil
}

// exitExcl must be called exiting a critical section that interacts with conn.
func (c *Conn) exitExcl() { c.excl.Store(false) }

// Close closes the underlying socket.
func (c *Conn) Close() error { return c.conn.Close() }

// Dial returns the address of a newly connected [Conn].
func Dial() (*Conn, error) {
	// kernel group is hard coded in lib/kobject_uevent.c, undocumented
	c, err := netlink.Dial(syscall.NETLINK_KOBJECT_UEVENT, 1)
	if err != nil {
		return nil, err
	}
	return &Conn{conn: c}, err
}