netlink

package module
v0.0.0-...-2e37830 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2018 License: MIT Imports: 17 Imported by: 0

README

Package netlink provides low-level access to Linux netlink sockets. MIT Licensed.

For more information about how netlink works, check out my blog series on Linux, Netlink, and Go.

If you're looking for package genetlink, it's been moved to its own repository at github.com/mdlayher/genetlink.

Why?

A number of netlink packages are already available for Go, but I wasn't able to find one that aligned with what I wanted in a netlink package:

  • Simple, idiomatic API
  • Well tested
  • Well documented
  • Makes use of Go best practices
  • Doesn't need root to work

My goal for this package is to use it as a building block for the creation of other netlink family packages.

Documentation

Overview

Package netlink provides low-level access to Linux netlink sockets.

Debugging

This package supports rudimentary netlink connection debugging support. To enable this, run your binary with the NLDEBUG environment variable set. Debugging information will be output to stderr with a prefix of "nl:".

To use the debugging defaults, use:

$ NLDEBUG=1 ./nlctl

To configure individual aspects of the debugger, pass key/value options such as:

$ NLDEBUG=level=1 ./nlctl

Available key/value debugger options include:

level=N: specify the debugging level (only "1" is currently supported)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalAttributes

func MarshalAttributes(attrs []Attribute) ([]byte, error)

MarshalAttributes packs a slice of Attributes into a single byte slice. In most cases, the Length field of each Attribute should be set to 0, so it can be calculated and populated automatically for each Attribute.

func Validate

func Validate(request Message, replies []Message) error

Validate validates one or more reply Messages against a request Message, ensuring that they contain matching sequence numbers and PIDs.

Types

type Attribute

type Attribute struct {
	// Length of an Attribute, including this field and Type.
	Length uint16

	// The type of this Attribute, typically matched to a constant.
	Type uint16

	// An arbitrary payload which is specified by Type.
	Data []byte
}

An Attribute is a netlink attribute. Attributes are packed and unpacked to and from the Data field of Message for some netlink families.

func UnmarshalAttributes

func UnmarshalAttributes(b []byte) ([]Attribute, error)

UnmarshalAttributes unpacks a slice of Attributes from a single byte slice.

It is recommend to use the AttributeDecoder type where possible instead of calling UnmarshalAttributes and using package nlenc functions directly.

type AttributeDecoder

type AttributeDecoder struct {
	// ByteOrder defines a specific byte order to use when processing integer
	// attributes.  ByteOrder should be set immediately after creating the
	// AttributeDecoder: before any attributes are parsed.
	//
	// If not set, the native byte order will be used.
	ByteOrder binary.ByteOrder
	// contains filtered or unexported fields
}

An AttributeDecoder provides a safe, iterator-like, API around attribute decoding.

It is recommend to use an AttributeDecoder where possible instead of calling UnmarshalAttributes and using package nlenc functions directly.

The Err method must be called after the Next method returns false to determine if any errors occurred during iteration.

Example (Decode)

This example demonstrates using a netlink.AttributeDecoder to decode packed netlink attributes in a message payload.

package main

import (
	"fmt"
	"log"

	"github.com/mdlayher/netlink"
)

// decodeNested is a nested structure within decodeOut.
type decodeNested struct {
	A, B uint32
}

// decodeOut is an example structure we will use to unpack netlink attributes.
type decodeOut struct {
	Number uint16
	String string
	Nested decodeNested
}

// decode is an example function used to adapt the ad.Do method to decode an
// arbitrary structure.
func (n *decodeNested) decode() func(b []byte) error {
	return func(b []byte) error {
		// Create an internal netlink.AttributeDecoder that operates on a
		// nested set of attributes passed by the external decoder.
		ad, err := netlink.NewAttributeDecoder(b)
		if err != nil {
			return fmt.Errorf("failed to create nested attribute decoder: %v", err)
		}

		// Iterate attributes until completion, checking the type of each
		// and decoding them as appropriate.
		for ad.Next() {
			switch ad.Type() {
			// A and B are both uint32 values, so decode them as such.
			case 1:
				n.A = ad.Uint32()
			case 2:
				n.B = ad.Uint32()
			}
		}

		// Return any error encountered while decoding.
		return ad.Err()
	}
}

// This example demonstrates using a netlink.AttributeDecoder to decode packed
// netlink attributes in a message payload.
func main() {
	// Create a netlink.AttributeDecoder using some example attribute bytes
	// that are prepared for this example.
	ad, err := netlink.NewAttributeDecoder(exampleAttributes())
	if err != nil {
		log.Fatalf("failed to create attribute decoder: %v", err)
	}

	// Iterate attributes until completion, checking the type of each and
	// decoding them as appropriate.
	var out decodeOut
	for ad.Next() {
		// Check the type of the current attribute with ad.Type.  Typically you
		// will find netlink attribute types and data values in C headers as
		// constants.
		switch ad.Type() {
		case 1:
			// Number is a uint16.
			out.Number = ad.Uint16()
		case 2:
			// String is a string.
			out.String = ad.String()
		case 3:
			// Nested is a nested structure, so we will use a method on the
			// nested type along with ad.Do to decode it in a concise way.
			ad.Do(out.Nested.decode())
		}
	}

	// Any errors encountered during decoding (including any errors from
	// decoding the nested attributes) will be returned here.
	if err := ad.Err(); err != nil {
		log.Fatalf("failed to decode attributes: %v", err)
	}

	fmt.Printf(`Number: %d
String: %q
Nested:
   - A: %d
   - B: %d`,
		out.Number, out.String, out.Nested.A, out.Nested.B,
	)
}
Output:

Number: 1
String: "hello world"
Nested:
   - A: 2
   - B: 3

func NewAttributeDecoder

func NewAttributeDecoder(b []byte) (*AttributeDecoder, error)

NewAttributeDecoder creates an AttributeDecoder that unpacks Attributes from b and prepares the decoder for iteration.

func (*AttributeDecoder) Bytes

func (ad *AttributeDecoder) Bytes() []byte

Bytes returns the raw bytes of the current Attribute's data.

func (*AttributeDecoder) Do

func (ad *AttributeDecoder) Do(fn func(b []byte) error)

Do is a general purpose function which allows access to the current data pointed to by the AttributeDecoder.

Do can be used to allow parsing arbitrary data within the context of the decoder. Do is most useful when dealing with nested attributes, attribute arrays, or decoding arbitrary types (such as C structures) which don't fit cleanly into a typical unsigned integer value.

The function fn should not retain any reference to the data b outside of the scope of the function.

func (*AttributeDecoder) Err

func (ad *AttributeDecoder) Err() error

Err returns the first error encountered by the decoder.

func (*AttributeDecoder) Next

func (ad *AttributeDecoder) Next() bool

Next advances the decoder to the next netlink attribute. It returns false when no more attributes are present, or an error was encountered.

func (*AttributeDecoder) String

func (ad *AttributeDecoder) String() string

String returns the string representation of the current Attribute's data.

func (*AttributeDecoder) Type

func (ad *AttributeDecoder) Type() uint16

Type returns the Attribute.Type field of the current netlink attribute pointed to by the decoder.

func (*AttributeDecoder) Uint16

func (ad *AttributeDecoder) Uint16() uint16

Uint16 returns the uint16 representation of the current Attribute's data.

func (*AttributeDecoder) Uint32

func (ad *AttributeDecoder) Uint32() uint32

Uint32 returns the uint32 representation of the current Attribute's data.

func (*AttributeDecoder) Uint64

func (ad *AttributeDecoder) Uint64() uint64

Uint64 returns the uint64 representation of the current Attribute's data.

func (*AttributeDecoder) Uint8

func (ad *AttributeDecoder) Uint8() uint8

Uint8 returns the uint8 representation of the current Attribute's data.

type AttributeEncoder

type AttributeEncoder struct {
	// ByteOrder defines a specific byte order to use when processing integer
	// attributes.  ByteOrder should be set immediately after creating the
	// AttributeEncoder: before any attributes are encoded.
	//
	// If not set, the native byte order will be used.
	ByteOrder binary.ByteOrder
	// contains filtered or unexported fields
}

An AttributeEncoder provides a safe way to encode attributes.

It is recommended to use an AttributeEncoder where possible instead of calling MarshalAttributes or using package nlenc directly.

Errors from intermediate encoding steps are returned in the call to Encode.

Example (Encode)
package main

import (
	"encoding/hex"
	"fmt"
	"log"

	"github.com/mdlayher/netlink"
)

// encodeNested is a nested structure within out.
type encodeNested struct {
	A, B uint32
}

// encodeOut is an example structure we will use to pack netlink attributes.
type encodeOut struct {
	Number uint16
	String string
	Nested encodeNested
}

// encode is an example function used to adapt the ae.Do method
// to encode an arbitrary structure.
func (n encodeNested) encode() func() ([]byte, error) {
	return func() ([]byte, error) {
		// Create an internal, nested netlink.NewAttributeEncoder that
		// operates on the nested set of attributes.
		ae := netlink.NewAttributeEncoder()

		// Encode the fields of the nested stucture
		ae.Uint32(1, n.A)
		ae.Uint32(2, n.B)

		// Return the encoded attributes, and any error encountered.
		return ae.Encode()
	}
}

func main() {
	// Create a netlink.AttributeEncoder that encodes to the same message
	// as that decoded by the netlink.AttributeDecoder example.
	ae := netlink.NewAttributeEncoder()

	o := encodeOut{
		Number: 1,
		String: "hello world",
		Nested: encodeNested{
			A: 2,
			B: 3,
		},
	}

	// Encode the Number attribute as a uint16.
	ae.Uint16(1, o.Number)
	// Encode the String attribute as a string.
	ae.String(2, o.String)
	// Nested is a nested structure, so we will use the encodeNested type's
	// encode method with ae.Do to encode it in a concise way.
	ae.Do(3, o.Nested.encode())

	// Any errors encountered during encoding (including any errors from
	// encoding nested attributes) will be returned here.
	b, err := ae.Encode()
	if err != nil {
		log.Fatalf("failed to encode attributes: %v", err)
	}

	fmt.Printf("Encoded netlink message follows:\n%s", hex.Dump(b))

}
Output:

Encoded netlink message follows:
00000000  06 00 01 00 01 00 00 00  10 00 02 00 68 65 6c 6c  |............hell|
00000010  6f 20 77 6f 72 6c 64 00  14 00 03 00 08 00 01 00  |o world.........|
00000020  02 00 00 00 08 00 02 00  03 00 00 00              |............|

func NewAttributeEncoder

func NewAttributeEncoder() *AttributeEncoder

NewAttributeEncoder creates an AttributeEncoder that encodes Attributes.

func (*AttributeEncoder) Bytes

func (ae *AttributeEncoder) Bytes(typ uint16, b []byte)

Bytes embeds raw byte data into an Attribute specified by typ.

func (*AttributeEncoder) Do

func (ae *AttributeEncoder) Do(typ uint16, fn func() ([]byte, error))

Do is a general purpose function to encode arbitrary data into an attribute specified by typ.

Do is especially helpful in encoding nested attributes, attribute arrays, or encoding arbitrary types (such as C structures) which don't fit cleanly into an unsigned integer value.

func (*AttributeEncoder) Encode

func (ae *AttributeEncoder) Encode() ([]byte, error)

Encode returns the encoded bytes representing the attributes.

func (*AttributeEncoder) String

func (ae *AttributeEncoder) String(typ uint16, s string)

String encodes string s as a null-terminated string into an Attribute specified by typ.

func (*AttributeEncoder) Uint16

func (ae *AttributeEncoder) Uint16(typ uint16, v uint16)

Uint16 encodes uint16 data into an Attribute specified by typ.

func (*AttributeEncoder) Uint32

func (ae *AttributeEncoder) Uint32(typ uint16, v uint32)

Uint32 encodes uint32 data into an Attribute specified by typ.

func (*AttributeEncoder) Uint64

func (ae *AttributeEncoder) Uint64(typ uint16, v uint64)

Uint64 encodes uint64 data into an Attribute specified by typ.

func (*AttributeEncoder) Uint8

func (ae *AttributeEncoder) Uint8(typ uint16, v uint8)

Uint8 encodes uint8 data into an Attribute specified by typ.

type Config

type Config struct {
	// Groups is a bitmask which specifies multicast groups. If set to 0,
	// no multicast group subscriptions will be made.
	Groups uint32

	// Network namespace the Conn needs to operate in. If set to 0,
	// no network namespace will be entered.
	NetNS int
}

Config contains options for a Conn.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn is a connection to netlink. A Conn can be used to send and receives messages to and from netlink.

A Conn is safe for concurrent use, but to avoid contention in high-throughput applications, the caller should almost certainly create a pool of Conns and distribute them among workers.

Example (Execute)

This example demonstrates using a netlink.Conn to execute requests against netlink.

package main

import (
	"log"

	"github.com/mdlayher/netlink"
)

func main() {
	// Speak to generic netlink using netlink
	const familyGeneric = 16

	c, err := netlink.Dial(familyGeneric, nil)
	if err != nil {
		log.Fatalf("failed to dial netlink: %v", err)
	}
	defer c.Close()

	// Ask netlink to send us an acknowledgement, which will contain
	// a copy of the header we sent to it
	req := netlink.Message{
		Header: netlink.Header{
			// Package netlink will automatically set header fields
			// which are set to zero
			Flags: netlink.HeaderFlagsRequest | netlink.HeaderFlagsAcknowledge,
		},
	}

	// Perform a request, receive replies, and validate the replies
	msgs, err := c.Execute(req)
	if err != nil {
		log.Fatalf("failed to execute request: %v", err)
	}

	if c := len(msgs); c != 1 {
		log.Fatalf("expected 1 message, but got: %d", c)
	}

	// Decode the copied request header, starting after 4 bytes
	// indicating "success"
	var res netlink.Message
	if err := (&res).UnmarshalBinary(msgs[0].Data[4:]); err != nil {
		log.Fatalf("failed to unmarshal response: %v", err)
	}

	log.Printf("res: %+v", res)
}
Output:

Example (ListenMulticast)

This example demonstrates using a netlink.Conn to listen for multicast group messages generated by the addition and deletion of network interfaces.

package main

import (
	"log"

	"github.com/mdlayher/netlink"
)

func main() {
	const (
		// Speak to route netlink using netlink
		familyRoute = 0

		// Listen for events triggered by addition or deletion of
		// network interfaces
		rtmGroupLink = 0x1
	)

	c, err := netlink.Dial(familyRoute, &netlink.Config{
		// Groups is a bitmask; more than one group can be specified
		// by OR'ing multiple group values together
		Groups: rtmGroupLink,
	})
	if err != nil {
		log.Fatalf("failed to dial netlink: %v", err)
	}
	defer c.Close()

	for {
		// Listen for netlink messages triggered by multicast groups
		msgs, err := c.Receive()
		if err != nil {
			log.Fatalf("failed to receive messages: %v", err)
		}

		log.Printf("msgs: %+v", msgs)
	}
}
Output:

func Dial

func Dial(family int, config *Config) (*Conn, error)

Dial dials a connection to netlink, using the specified netlink family. Config specifies optional configuration for Conn. If config is nil, a default configuration will be used.

func NewConn

func NewConn(sock Socket, pid uint32) *Conn

NewConn creates a Conn using the specified Socket and PID for netlink communications.

NewConn is primarily useful for tests. Most applications should use Dial instead.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) Execute

func (c *Conn) Execute(message Message) ([]Message, error)

Execute sends a single Message to netlink using Conn.Send, receives one or more replies using Conn.Receive, and then checks the validity of the replies against the request using Validate.

See the documentation of Conn.Send, Conn.Receive, and Validate for details about each function.

func (*Conn) JoinGroup

func (c *Conn) JoinGroup(group uint32) error

JoinGroup joins a netlink multicast group by its ID.

func (*Conn) LeaveGroup

func (c *Conn) LeaveGroup(group uint32) error

LeaveGroup leaves a netlink multicast group by its ID.

func (*Conn) ReadWriteCloser

func (c *Conn) ReadWriteCloser() (io.ReadWriteCloser, error)

ReadWriteCloser returns a raw io.ReadWriteCloser backed by the connection of the Conn.

ReadWriteCloser is intended for advanced use cases, such as those that do not involve standard netlink message passing.

Once invoked, it is the caller's responsibility to ensure that operations performed using Conn and the raw io.ReadWriteCloser do not conflict with each other. In almost all scenarios, only one of the two should be used.

func (*Conn) Receive

func (c *Conn) Receive() ([]Message, error)

Receive receives one or more messages from netlink. Multi-part messages are handled transparently and returned as a single slice of Messages, with the final empty "multi-part done" message removed.

If any of the messages indicate a netlink error, that error will be returned.

func (*Conn) RemoveBPF

func (c *Conn) RemoveBPF() error

RemoveBPF removes a BPF filter from a Conn.

func (*Conn) Send

func (c *Conn) Send(message Message) (Message, error)

Send sends a single Message to netlink. In most cases, a Header's Length, Sequence, and PID fields should be set to 0, so they can be populated automatically before the Message is sent. On success, Send returns a copy of the Message with all parameters populated, for later validation.

If Header.Length is 0, it will be automatically populated using the correct length for the Message, including its payload.

If Header.Sequence is 0, it will be automatically populated using the next sequence number for this connection.

If Header.PID is 0, it will be automatically populated using a PID assigned by netlink.

func (*Conn) SendMessages

func (c *Conn) SendMessages(messages []Message) ([]Message, error)

SendMessages sends multiple Messages to netlink. The handling of a Header's Length, Sequence and PID fields is the same as when calling Send.

func (*Conn) SetBPF

func (c *Conn) SetBPF(filter []bpf.RawInstruction) error

SetBPF attaches an assembled BPF program to a Conn.

func (*Conn) SetOption

func (c *Conn) SetOption(option ConnOption, enable bool) error

SetOption enables or disables a netlink socket option for the Conn.

func (*Conn) SetReadBuffer

func (c *Conn) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer associated with the Conn.

func (*Conn) SetWriteBuffer

func (c *Conn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the Conn.

func (*Conn) SyscallConn

func (c *Conn) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw network connection. This implements the syscall.Conn interface.

Only the Control method of the returned syscall.RawConn is currently implemented.

SyscallConn is intended for advanced use cases, such as getting and setting arbitrary socket options using the netlink socket's file descriptor.

Once invoked, it is the caller's responsibility to ensure that operations performed using Conn and the syscall.RawConn do not conflict with each other.

type ConnOption

type ConnOption int

A ConnOption is a boolean option that may be set for a Conn.

const (
	PacketInfo ConnOption = iota
	BroadcastError
	NoENOBUFS
	ListenAllNSID
	CapAcknowledge
)

Possible ConnOption values. These constants are equivalent to the Linux setsockopt boolean options for netlink sockets.

type Header struct {
	// Length of a Message, including this Header.
	Length uint32

	// Contents of a Message.
	Type HeaderType

	// Flags which may be used to modify a request or response.
	Flags HeaderFlags

	// The sequence number of a Message.
	Sequence uint32

	// The process ID of the sending process.
	PID uint32
}

A Header is a netlink header. A Header is sent and received with each Message to indicate metadata regarding a Message.

type HeaderFlags

type HeaderFlags uint16

HeaderFlags specify flags which may be present in a Header.

const (

	// HeaderFlagsRequest indicates a request to netlink.
	HeaderFlagsRequest HeaderFlags = 1

	// HeaderFlagsMulti indicates a multi-part message, terminated
	// by HeaderTypeDone on the last message.
	HeaderFlagsMulti HeaderFlags = 2

	// HeaderFlagsAcknowledge requests that netlink reply with
	// an acknowledgement using HeaderTypeError and, if needed,
	// an error code.
	HeaderFlagsAcknowledge HeaderFlags = 4

	// HeaderFlagsEcho requests that netlink echo this request
	// back to the sender.
	HeaderFlagsEcho HeaderFlags = 8

	// HeaderFlagsDumpInterrupted indicates that a dump was
	// inconsistent due to a sequence change.
	HeaderFlagsDumpInterrupted HeaderFlags = 16

	// HeaderFlagsDumpFiltered indicates that a dump was filtered
	// as requested.
	HeaderFlagsDumpFiltered HeaderFlags = 32

	// HeaderFlagsRoot requests that netlink return a complete table instead
	// of a single entry.
	HeaderFlagsRoot HeaderFlags = 0x100

	// HeaderFlagsMatch requests that netlink return a list of all matching
	// entries.
	HeaderFlagsMatch HeaderFlags = 0x200

	// HeaderFlagsAtomic requests that netlink send an atomic snapshot of
	// its entries.  Requires CAP_NET_ADMIN or an effective UID of 0.
	HeaderFlagsAtomic HeaderFlags = 0x400

	// HeaderFlagsDump requests that netlink return a complete list of
	// all entries.
	HeaderFlagsDump HeaderFlags = HeaderFlagsRoot | HeaderFlagsMatch

	// HeaderFlagsReplace indicates request replaces an existing matching object.
	HeaderFlagsReplace HeaderFlags = 0x100

	// HeaderFlagsExcl  indicates request does not replace the object if it already exists.
	HeaderFlagsExcl HeaderFlags = 0x200

	// HeaderFlagsCreate indicates request creates an object if it doesn't already exist.
	HeaderFlagsCreate HeaderFlags = 0x400

	// HeaderFlagsAppend indicates request adds to the end of the object list.
	HeaderFlagsAppend HeaderFlags = 0x800
)

func (HeaderFlags) String

func (f HeaderFlags) String() string

String returns the string representation of a HeaderFlags.

type HeaderType

type HeaderType uint16

HeaderType specifies the type of a Header.

const (
	// HeaderTypeNoop indicates that no action was taken.
	HeaderTypeNoop HeaderType = 0x1

	// HeaderTypeError indicates an error code is present, which is also
	// used to indicate success when the code is 0.
	HeaderTypeError HeaderType = 0x2

	// HeaderTypeDone indicates the end of a multi-part message.
	HeaderTypeDone HeaderType = 0x3

	// HeaderTypeOverrun indicates that data was lost from this message.
	HeaderTypeOverrun HeaderType = 0x4
)

func (HeaderType) String

func (t HeaderType) String() string

String returns the string representation of a HeaderType.

type Message

type Message struct {
	Header Header
	Data   []byte
}

A Message is a netlink message. It contains a Header and an arbitrary byte payload, which may be decoded using information from the Header.

Data is encoded in the native endianness of the host system. For easier of encoding and decoding of integers, use package nlenc.

func (Message) MarshalBinary

func (m Message) MarshalBinary() ([]byte, error)

MarshalBinary marshals a Message into a byte slice.

func (*Message) UnmarshalBinary

func (m *Message) UnmarshalBinary(b []byte) error

UnmarshalBinary unmarshals the contents of a byte slice into a Message.

type Socket

type Socket interface {
	Close() error
	Send(m Message) error
	SendMessages(m []Message) error
	Receive() ([]Message, error)
}

A Socket is an operating-system specific implementation of netlink sockets used by Conn.

Directories

Path Synopsis
cmd
nlstress
Command nlstress continuously stresses the netlink package.
Command nlstress continuously stresses the netlink package.
Package nlenc implements encoding and decoding functions for netlink messages and attributes.
Package nlenc implements encoding and decoding functions for netlink messages and attributes.
Package nltest provides utilities for netlink testing.
Package nltest provides utilities for netlink testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL