nclient4

package
v0.0.0-...-efdc7c0 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2023 License: BSD-3-Clause Imports: 16 Imported by: 0

Documentation

Overview

Package nclient4 is a small, minimum-functionality client for DHCPv4.

It only supports the 4-way DHCPv4 Discover-Offer-Request-Ack handshake as well as the Request-Ack renewal process.

Index

Constants

View Source
const (

	// DefaultTimeout is the default value for read-timeout if option WithTimeout is not set
	DefaultTimeout = 5 * time.Second

	// DefaultRetries is amount of retries will be done if no answer was received within read-timeout amount of time
	DefaultRetries = 3

	// MaxMessageSize is the value to be used for DHCP option "MaxMessageSize".
	MaxMessageSize = 1500

	// ClientPort is the port that DHCP clients listen on.
	ClientPort = 68

	// ServerPort is the port that DHCP servers and relay agents listen on.
	ServerPort = 67
)

Variables

View Source
var (
	// ErrNoResponse is returned when no response packet is received.
	ErrNoResponse = errors.New("no matching response packet received")

	// ErrNoConn is returned when NewWithConn is called with nil-value as conn.
	ErrNoConn = errors.New("conn is nil")

	// ErrNoIfaceHWAddr is returned when NewWithConn is called with nil-value as ifaceHWAddr
	ErrNoIfaceHWAddr = errors.New("ifaceHWAddr is nil")
)
View Source
var (
	// BroadcastMac is the broadcast MAC address.
	//
	// Any UDP packet sent to this address is broadcast on the subnet.
	BroadcastMac = net.HardwareAddr([]byte{255, 255, 255, 255, 255, 255})
)
View Source
var (
	// DefaultServers is the address of all link-local DHCP servers and
	// relay agents.
	DefaultServers = &net.UDPAddr{
		IP:   net.IPv4bcast,
		Port: ServerPort,
	}
)
View Source
var (
	// ErrUDPAddrIsRequired is an error used when a passed argument is not of type "*net.UDPAddr".
	ErrUDPAddrIsRequired = errors.New("must supply UDPAddr")
)

Functions

func NewBroadcastUDPConn

func NewBroadcastUDPConn(rawPacketConn net.PacketConn, boundAddr *net.UDPAddr) net.PacketConn

NewBroadcastUDPConn returns a PacketConn that marshals and unmarshals UDP packets, sending them to the broadcast MAC at on rawPacketConn.

Calls to ReadFrom will only return packets destined to boundAddr.

func NewRawUDPConn

func NewRawUDPConn(iface string, port int) (net.PacketConn, error)

NewRawUDPConn returns a UDP connection bound to the interface and port given based on a raw packet socket. All packets are broadcasted.

The interface can be completely unconfigured.

Types

type BroadcastRawUDPConn

type BroadcastRawUDPConn struct {
	// PacketConn is a raw DGRAM socket.
	net.PacketConn
	// contains filtered or unexported fields
}

BroadcastRawUDPConn uses a raw socket to send UDP packets to the broadcast MAC address.

func (*BroadcastRawUDPConn) ReadFrom

func (upc *BroadcastRawUDPConn) ReadFrom(b []byte) (int, net.Addr, error)

ReadFrom implements net.PacketConn.ReadFrom.

ReadFrom reads raw IP packets and will try to match them against upc.boundAddr. Any matching packets are returned via the given buffer.

func (*BroadcastRawUDPConn) WriteTo

func (upc *BroadcastRawUDPConn) WriteTo(b []byte, addr net.Addr) (int, error)

WriteTo implements net.PacketConn.WriteTo and broadcasts all packets at the raw socket level.

WriteTo wraps the given packet in the appropriate UDP and IP header before sending it on the packet conn.

type Client

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

Client is an IPv4 DHCP client.

func New

func New(iface string, opts ...ClientOpt) (*Client, error)

New returns a client usable with an unconfigured interface.

func NewWithConn

func NewWithConn(conn net.PacketConn, ifaceHWAddr net.HardwareAddr, opts ...ClientOpt) (*Client, error)

NewWithConn creates a new DHCP client that sends and receives packets on the given interface.

func (*Client) Close

func (c *Client) Close() error

Close closes the underlying connection.

func (*Client) DiscoverOffer

func (c *Client) DiscoverOffer(ctx context.Context, modifiers ...dhcpv4.Modifier) (offer *dhcpv4.DHCPv4, err error)

DiscoverOffer sends a DHCPDiscover message and returns the first valid offer received.

func (*Client) Inform

func (c *Client) Inform(ctx context.Context, localIP net.IP, modifiers ...dhcpv4.Modifier) (*dhcpv4.DHCPv4, error)

Inform sends an INFORM request using the given local IP. Returns the ACK response from the server on success.

func (*Client) InterfaceAddr

func (c *Client) InterfaceAddr() net.HardwareAddr

InterfaceAddr returns the MAC address of the client's interface.

func (*Client) Release

func (c *Client) Release(lease *Lease, modifiers ...dhcpv4.Modifier) error

Release send DHCPv4 release messsage to server, based on specified lease. release is sent as unicast per RFC2131, section 4.4.4. Note: some DHCP server requries of using assigned IP address as source IP, use nclient4.WithUnicast to create client for such case.

func (*Client) RemoteAddr

func (c *Client) RemoteAddr() *net.UDPAddr

RemoteAddr is the default DHCP server address this client sends messages to.

func (*Client) Renew

func (c *Client) Renew(ctx context.Context, lease *Lease, modifiers ...dhcpv4.Modifier) (*Lease, error)

Renew sends a DHCPv4 request to the server to renew the given lease. The renewal information is sourced from the initial offer in the lease, and the ACK of the lease is updated to the ACK of the latest renewal. This avoids issues with DHCP servers that omit information needed to build a completely new lease from their renewal ACK (such as the Windows DHCP Server).

func (*Client) Request

func (c *Client) Request(ctx context.Context, modifiers ...dhcpv4.Modifier) (lease *Lease, err error)

Request completes the 4-way Discover-Offer-Request-Ack handshake.

Note that modifiers will be applied *both* to Discover and Request packets.

func (*Client) RequestFromOffer

func (c *Client) RequestFromOffer(ctx context.Context, offer *dhcpv4.DHCPv4, modifiers ...dhcpv4.Modifier) (*Lease, error)

RequestFromOffer sends a Request message and waits for an response. It assumes the SELECTING state by default, see Section 4.3.2 in RFC 2131 for more details.

func (*Client) SendAndRead

func (c *Client) SendAndRead(ctx context.Context, dest *net.UDPAddr, p *dhcpv4.DHCPv4, match Matcher) (*dhcpv4.DHCPv4, error)

SendAndRead sends a packet p to a destination dest and waits for the first response matching `match` as well as its Transaction ID and ClientHWAddr.

If match is nil, the first packet matching the Transaction ID and ClientHWAddr is returned.

type ClientOpt

type ClientOpt func(c *Client) error

ClientOpt is a function that configures the Client.

func WithDebugLogger

func WithDebugLogger() ClientOpt

WithDebugLogger logs multi-line full DHCPv4 messages when sent & received.

func WithHWAddr

func WithHWAddr(hwAddr net.HardwareAddr) ClientOpt

WithHWAddr tells to the Client to receive messages destinated to selected hardware address

func WithLogger

func WithLogger(newLogger Logger) ClientOpt

WithLogger set the logger (see interface Logger).

func WithRetry

func WithRetry(r int) ClientOpt

WithRetry configures the number of retransmissions to attempt.

Default is 3.

func WithServerAddr

func WithServerAddr(n *net.UDPAddr) ClientOpt

WithServerAddr configures the address to send messages to.

func WithSummaryLogger

func WithSummaryLogger() ClientOpt

WithSummaryLogger logs one-line DHCPv4 message summaries when sent & received.

func WithTimeout

func WithTimeout(d time.Duration) ClientOpt

WithTimeout configures the retransmission timeout.

Default is 5 seconds.

func WithUnicast

func WithUnicast(srcAddr *net.UDPAddr) ClientOpt

WithUnicast forces client to send messages as unicast frames. By default client sends messages as broadcast frames even if server address is defined.

srcAddr is both: * The source address of outgoing frames. * The address to be listened for incoming frames.

type DebugLogger

type DebugLogger struct {
	// Printfer is used for actual output of the logger
	Printfer
}

DebugLogger is a wrapper for Printfer to implement interface Logger. DHCP messages are printed in the long format.

func (DebugLogger) PrintMessage

func (d DebugLogger) PrintMessage(prefix string, message *dhcpv4.DHCPv4)

PrintMessage prints a DHCP message in the long format via predefined Printfer

func (DebugLogger) Printf

func (d DebugLogger) Printf(format string, v ...interface{})

Printf prints a log message as-is via predefined Printfer

type EmptyLogger

type EmptyLogger struct{}

EmptyLogger prints nothing

func (EmptyLogger) PrintMessage

func (e EmptyLogger) PrintMessage(prefix string, message *dhcpv4.DHCPv4)

PrintMessage is just a dummy function that does nothing

func (EmptyLogger) Printf

func (e EmptyLogger) Printf(format string, v ...interface{})

Printf is just a dummy function that does nothing

type ErrNak

type ErrNak struct {
	Offer *dhcpv4.DHCPv4
	Nak   *dhcpv4.DHCPv4
}

ErrNak is returned if a DHCP server rejected our Request.

func (*ErrNak) Error

func (e *ErrNak) Error() string

Error implements error.Error.

type ErrTransactionIDInUse

type ErrTransactionIDInUse struct {
	// TransactionID is the transaction ID of the message which the error is related to.
	TransactionID dhcpv4.TransactionID
}

ErrTransactionIDInUse is returned if there were an attempt to send a message with the same TransactionID as we are already waiting an answer for.

func (*ErrTransactionIDInUse) Error

func (err *ErrTransactionIDInUse) Error() string

Error is just the method to comply interface "error".

type Lease

type Lease struct {
	Offer        *dhcpv4.DHCPv4
	ACK          *dhcpv4.DHCPv4
	CreationTime time.Time
}

Lease contains a DHCPv4 lease after DORA. note: Lease doesn't include binding interface name

type Logger

type Logger interface {
	// PrintMessage print _all_ DHCP messages
	PrintMessage(prefix string, message *dhcpv4.DHCPv4)

	// Printf is use to print the rest debugging information
	Printf(format string, v ...interface{})
}

Logger is a handler which will be used to output logging messages

type Matcher

type Matcher func(*dhcpv4.DHCPv4) bool

Matcher matches DHCP packets.

func IsAll

func IsAll(ms ...Matcher) Matcher

IsAll returns a matcher that checks for all given matchers to be true.

func IsCorrectServer

func IsCorrectServer(s net.IP) Matcher

IsCorrectServer returns a matcher that checks for the correct ServerAddress.

func IsMessageType

func IsMessageType(t dhcpv4.MessageType, tt ...dhcpv4.MessageType) Matcher

IsMessageType returns a matcher that checks for the message types.

type Printfer

type Printfer interface {
	// Printf is the function for logging output. Arguments are handled in the manner of fmt.Printf.
	Printf(format string, v ...interface{})
}

Printfer is used for actual output of the logger. For example *log.Logger is a Printfer.

type ShortSummaryLogger

type ShortSummaryLogger struct {
	// Printfer is used for actual output of the logger
	Printfer
}

ShortSummaryLogger is a wrapper for Printfer to implement interface Logger. DHCP messages are printed in the short format.

func (ShortSummaryLogger) PrintMessage

func (s ShortSummaryLogger) PrintMessage(prefix string, message *dhcpv4.DHCPv4)

PrintMessage prints a DHCP message in the short format via predefined Printfer

func (ShortSummaryLogger) Printf

func (s ShortSummaryLogger) Printf(format string, v ...interface{})

Printf prints a log message as-is via predefined Printfer

Jump to

Keyboard shortcuts

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