netlink

package module
v0.0.0-...-3b912d7 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2019 License: MIT Imports: 19 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 have any questions or you'd like some guidance, please join us on Gophers Slack in the #networking channel!

Stability

At this time, package netlink is in a pre-v1.0.0 state. Changes are being made which may impact the exported API of this package and others in its ecosystem. To follow along on the status of a v1.0.0 release, see the associated issue.

The general policy of this package is to only support the latest, stable version of Go. Compatibility shims may be added for prior versions of Go on an as-needed basis. If you would like to raise a concern, please file an issue.

If you depend on this package in your applications, please vendor it or use Go modules when building your application.

Design

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:

  • Straightforward, idiomatic API
  • Well tested
  • Well documented
  • Doesn't use package/global variables or state
  • Doesn't necessarily 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.

Ecosystem

Over time, an ecosystem of Go packages has developed around package netlink. Many of these packages provide building blocks for further interactions with various netlink families, such as NETLINK_GENERIC or NETLINK_ROUTE.

To have your package included in this diagram, please send a pull request!

netlink ecosystem

Documentation

Overview

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

If you have any questions or you'd like some guidance, please join us on Gophers Slack (https://invite.slack.golangbridge.org) in the #networking channel!

Network namespaces

This package is aware of Linux network namespaces, and can enter different network namespaces either implicitly or explicitly, depending on configuration. The Config structure passed to Dial to create a Conn controls these behaviors. See the documentation of Config.NetNS for details.

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

View Source
const (
	NLMSG_ALIGNTO = syscall.NLMSG_ALIGNTO
	NLMSG_HDRLEN  = syscall.NLMSG_HDRLEN
)

Variables

This section is empty.

Functions

func IsNotExist

func IsNotExist(err error) bool

IsNotExist determines if an error is produced as the result of querying some file, object, resource, etc. which does not exist. Users of this package should always use netlink.IsNotExist, rather than os.IsNotExist, when checking for specific netlink-related errors.

Errors types created by this package, such as OpError, can be used with IsNotExist, but this function also defers to the behavior of os.IsNotExist for unrecognized error types.

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/bpowers/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/bpowers/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 structure.
		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

	// NetNS specifies the network namespace the Conn will operate in.
	//
	// If set (non-zero), Conn will enter the specified network namespace and
	// an error will occur in Dial if the operation fails.
	//
	// If not set (zero), a best-effort attempt will be made to enter the
	// network namespace of the calling thread: this means that any changes made
	// to the calling thread's network namespace will also be reflected in Conn.
	// If this operation fails (due to lack of permissions or because network
	// namespaces are disabled by kernel configuration), Dial will not return
	// an error, and the Conn will operate in the default network namespace of
	// the process. This enables non-privileged use of Conn in applications
	// which do not require elevated privileges.
	//
	// Entering a network namespace is a privileged operation (root or
	// CAP_SYS_ADMIN are required), and most applications should leave this set
	// to 0.
	NetNS int

	// DisableNSLockThread disables package netlink's default goroutine thread locking behavior.
	//
	// By default, the library will lock the processing goroutine to its corresponding
	// thread in order to enable communication over netlink to a different namespaces.
	// In some cases, where the caller already knows that the netlink socket
	// is in the same namespace as the calling thread, this can introduce a performance
	// impact. In these cases, the caller can disable thread locking if performance
	// considerations are of interest. If disabled, it is the responsibility of
	// the caller to make sure that all threads are running in the correct namespace.
	// When DisableNSLockThread is set, the caller cannot set the NetNS value.
	DisableNSLockThread bool
}

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.

A Conn is capable of manipulating netlink subsystems from within a specific Linux network namespace, but special care must be taken when doing so. See the documentation of Config for details.

Example (Execute)

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

package main

import (
	"log"

	"github.com/bpowers/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.Request | netlink.Acknowledge,
		},
	}

	// 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/bpowers/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. Close will unblock any concurrent calls to Receive which are waiting on a response from the kernel.

func (*Conn) Execute

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

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

Execute acquires a lock for the duration of the function call which blocks concurrent calls to Send, SendMessages, and Receive, in order to ensure consistency between netlink request/reply messages.

See the documentation of Send, 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) 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) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection.

Deadline functionality is only supported on Go 1.12+. Calling this function on older versions of Go will result in an error.

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) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline associated with the connection.

Deadline functionality is only supported on Go 1.12+. Calling this function on older versions of Go will result in an error.

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) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline associated with the connection.

Deadline functionality is only supported on Go 1.12+. Calling this function on older versions of Go will result in an error.

func (*Conn) SyscallConn

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

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

On Go 1.12+, all methods of the returned syscall.RawConn are supported and the Conn is integrated with the runtime network poller. On versions of Go prior to Go 1.12, only the Control method of the returned syscall.RawConn is 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
	ExtendedAcknowledge
)

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 (

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

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

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

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

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

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

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

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

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

	// Dump requests that netlink return a complete list of all entries.
	Dump HeaderFlags = Root | Match

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

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

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

	// Append indicates request adds to the end of the object list.
	Append 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 (
	// Noop indicates that no action was taken.
	Noop HeaderType = 0x1

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

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

	// Overrun indicates that data was lost from this message.
	Overrun 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 NetlinkMessage

type NetlinkMessage = syscall.NetlinkMessage

func ParseNetlinkMessage

func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error)

ParseNetlinkMessage parses b as an array of netlink messages and returns the slice containing the NetlinkMessage structures.

type NlMsghdr

type NlMsghdr = syscall.NlMsghdr

type OpError

type OpError struct {
	// Op is the operation which caused this OpError, such as "send"
	// or "receive".
	Op string

	// Err is the underlying error which caused this OpError.
	//
	// If Err was produced by a system call error, Err will be of type
	// *os.SyscallError. If Err was produced by an error code in a netlink
	// message, Err will contain a raw error value type such as a unix.Errno.
	//
	// Most callers should inspect Err using a helper such as IsNotExist.
	Err error
}

An OpError is an error produced as the result of a failed netlink operation.

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Temporary

func (e *OpError) Temporary() bool

Temporary reports whether an operation may succeed if retried.

func (*OpError) Timeout

func (e *OpError) Timeout() bool

Timeout reports whether the error was caused by an I/O timeout.

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
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