nclient4

package
v0.105.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2021 License: GPL-3.0 Imports: 14 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. Originally from here: github.com/insomniacslk/dhcp/dhcpv4/nclient4

with the difference that this package can be built on UNIX (not just Linux),
because github.com/mdlayher/raw package supports it.

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
)
View Source
const (
	// IPv4MinimumSize is the minimum size of a valid IPv4 packet.
	IPv4MinimumSize = 20

	// IPv4MaximumHeaderSize is the maximum size of an IPv4 header. Given
	// that there are only 4 bits to represents the header length in 32-bit
	// units, the header cannot exceed 15*4 = 60 bytes.
	IPv4MaximumHeaderSize = 60

	// IPv4AddressSize is the size, in bytes, of an IPv4 address.
	IPv4AddressSize = 4

	// IPv4Version is the version of the ipv4 protocol.
	IPv4Version = 4
)
View Source
const (
	IPv4FlagMoreFragments = 1 << iota
	IPv4FlagDontFragment
)

Flags that may be set in an IPv4 packet.

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 (
	// IPv4Broadcast is the broadcast address of the IPv4 protocol.
	IPv4Broadcast = net.IP{0xff, 0xff, 0xff, 0xff}

	// IPv4Any is the non-routable IPv4 "any" meta address.
	IPv4Any = net.IP{0, 0, 0, 0}
)
View Source
var BroadcastMac = net.HardwareAddr([]byte{255, 255, 255, 255, 255, 255})

BroadcastMac is the broadcast MAC address.

Any UDP packet sent to this address is broadcast on the subnet.

View Source
var DefaultServers = &net.UDPAddr{
	IP:   net.IPv4bcast,
	Port: ServerPort,
}

DefaultServers is the address of all link-local DHCP servers and relay agents.

View Source
var ErrUDPAddrIsRequired = errors.New("must supply UDPAddr")

ErrUDPAddrIsRequired is an error used when a passed argument is not of type "*net.UDPAddr".

Functions

func Checksum

func Checksum(buf []byte, initial uint16) uint16

Checksum calculates the checksum (as defined in RFC 1071) of the bytes in the given byte array.

The initial checksum must have been computed on an even number of bytes.

func ChecksumCombine

func ChecksumCombine(a, b uint16) uint16

ChecksumCombine combines the two uint16 to form their checksum. This is done by adding them and the carry.

Note that checksum a must have been computed on an even number of bytes.

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.

func PseudoHeaderChecksum

func PseudoHeaderChecksum(protocol TransportProtocolNumber, srcAddr, dstAddr net.IP) uint16

PseudoHeaderChecksum calculates the pseudo-header checksum for the given destination protocol and network address, ignoring the length field. Pseudo-headers are needed by transport layers when calculating their own checksum.

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

func (c *Client) Request(ctx context.Context, modifiers ...dhcpv4.Modifier) (offer, ack *dhcpv4.DHCPv4, 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) 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 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 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 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 IPv4

type IPv4 []byte

IPv4 represents an ipv4 header stored in a byte array. Most of the methods of IPv4 access to the underlying slice without checking the boundaries and could panic because of 'index out of range'. Always call IsValid() to validate an instance of IPv4 before using other methods.

func (IPv4) CalculateChecksum

func (b IPv4) CalculateChecksum() uint16

CalculateChecksum calculates the checksum of the ipv4 header.

func (IPv4) DestinationAddress

func (b IPv4) DestinationAddress() net.IP

DestinationAddress returns the "destination address" field of the ipv4 header.

func (IPv4) Encode

func (b IPv4) Encode(i *IPv4Fields)

Encode encodes all the fields of the ipv4 header.

func (IPv4) HeaderLength

func (b IPv4) HeaderLength() uint8

HeaderLength returns the value of the "header length" field of the ipv4 header.

func (IPv4) Payload

func (b IPv4) Payload() []byte

Payload implements Network.Payload.

func (IPv4) PayloadLength

func (b IPv4) PayloadLength() uint16

PayloadLength returns the length of the payload portion of the ipv4 packet.

func (IPv4) Protocol

func (b IPv4) Protocol() uint8

Protocol returns the value of the protocol field of the ipv4 header.

func (IPv4) SetChecksum

func (b IPv4) SetChecksum(v uint16)

SetChecksum sets the checksum field of the ipv4 header.

func (IPv4) SetDestinationAddress

func (b IPv4) SetDestinationAddress(addr net.IP)

SetDestinationAddress sets the "destination address" field of the ipv4 header.

func (IPv4) SetFlagsFragmentOffset

func (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16)

SetFlagsFragmentOffset sets the "flags" and "fragment offset" fields of the ipv4 header.

func (IPv4) SetSourceAddress

func (b IPv4) SetSourceAddress(addr net.IP)

SetSourceAddress sets the "source address" field of the ipv4 header.

func (IPv4) SetTotalLength

func (b IPv4) SetTotalLength(totalLength uint16)

SetTotalLength sets the "total length" field of the ipv4 header.

func (IPv4) SourceAddress

func (b IPv4) SourceAddress() net.IP

SourceAddress returns the "source address" field of the ipv4 header.

func (IPv4) TotalLength

func (b IPv4) TotalLength() uint16

TotalLength returns the "total length" field of the ipv4 header.

func (IPv4) TransportProtocol

func (b IPv4) TransportProtocol() TransportProtocolNumber

TransportProtocol implements Network.TransportProtocol.

type IPv4Fields

type IPv4Fields struct {
	// IHL is the "internet header length" field of an IPv4 packet.
	IHL uint8

	// TOS is the "type of service" field of an IPv4 packet.
	TOS uint8

	// TotalLength is the "total length" field of an IPv4 packet.
	TotalLength uint16

	// ID is the "identification" field of an IPv4 packet.
	ID uint16

	// Flags is the "flags" field of an IPv4 packet.
	Flags uint8

	// FragmentOffset is the "fragment offset" field of an IPv4 packet.
	FragmentOffset uint16

	// TTL is the "time to live" field of an IPv4 packet.
	TTL uint8

	// Protocol is the "protocol" field of an IPv4 packet.
	Protocol uint8

	// Checksum is the "checksum" field of an IPv4 packet.
	Checksum uint16

	// SrcAddr is the "source ip address" of an IPv4 packet.
	SrcAddr net.IP

	// DstAddr is the "destination ip address" of an IPv4 packet.
	DstAddr net.IP
}

IPv4Fields contains the fields of an IPv4 packet. It is used to describe the fields of a packet that needs to be encoded.

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 IsMessageType

func IsMessageType(t dhcpv4.MessageType) Matcher

IsMessageType returns a matcher that checks for the message type.

If t is MessageTypeNone, all packets are matched.

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

type TransportProtocolNumber

type TransportProtocolNumber uint32

TransportProtocolNumber is the number of a transport protocol.

const (
	// UDPMinimumSize is the minimum size of a valid UDP packet.
	UDPMinimumSize = 8

	// UDPProtocolNumber is UDP's transport protocol number.
	UDPProtocolNumber TransportProtocolNumber = 17
)

type UDP

type UDP []byte

UDP represents a UDP header stored in a byte array.

func (UDP) CalculateChecksum

func (b UDP) CalculateChecksum(partialChecksum, totalLen uint16) uint16

CalculateChecksum calculates the checksum of the udp packet, given the total length of the packet and the checksum of the network-layer pseudo-header (excluding the total length) and the checksum of the payload.

func (UDP) Checksum

func (b UDP) Checksum() uint16

Checksum returns the "checksum" field of the udp header.

func (UDP) DestinationPort

func (b UDP) DestinationPort() uint16

DestinationPort returns the "destination port" field of the udp header.

func (UDP) Encode

func (b UDP) Encode(u *UDPFields)

Encode encodes all the fields of the udp header.

func (UDP) Length

func (b UDP) Length() uint16

Length returns the "length" field of the udp header.

func (UDP) Payload

func (b UDP) Payload() []byte

Payload returns the data contained in the UDP datagram.

func (UDP) SetChecksum

func (b UDP) SetChecksum(checksum uint16)

SetChecksum sets the "checksum" field of the udp header.

func (UDP) SetDestinationPort

func (b UDP) SetDestinationPort(port uint16)

SetDestinationPort sets the "destination port" field of the udp header.

func (UDP) SetSourcePort

func (b UDP) SetSourcePort(port uint16)

SetSourcePort sets the "source port" field of the udp header.

func (UDP) SourcePort

func (b UDP) SourcePort() uint16

SourcePort returns the "source port" field of the udp header.

type UDPFields

type UDPFields struct {
	// SrcPort is the "source port" field of a UDP packet.
	SrcPort uint16

	// DstPort is the "destination port" field of a UDP packet.
	DstPort uint16

	// Length is the "length" field of a UDP packet.
	Length uint16

	// Checksum is the "checksum" field of a UDP packet.
	Checksum uint16
}

UDPFields contains the fields of a UDP packet. It is used to describe the fields of a packet that needs to be encoded.

Jump to

Keyboard shortcuts

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