slirp

package
v0.0.0-...-f57ed73 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package slirp provides user-mode TCP/IP networking. Reference: tinyemu-2019-12-21/slirp/

Index

Constants

View Source
const (
	// Port numbers
	BootpServer = 67
	BootpClient = 68

	// BOOTP operation codes
	BootpRequest = 1
	BootpReply   = 2

	// RFC 1533 options
	RFC1533Pad      = 0
	RFC1533Netmask  = 1
	RFC1533Gateway  = 3
	RFC1533DNS      = 6
	RFC1533Hostname = 12
	RFC1533End      = 255

	// RFC 2132 options
	RFC2132ReqAddr   = 50
	RFC2132LeaseTime = 51
	RFC2132MsgType   = 53
	RFC2132SrvID     = 54
	RFC2132Message   = 56

	// DHCP message types
	DHCPDiscover = 1
	DHCPOffer    = 2
	DHCPRequest  = 3
	DHCPAck      = 5
	DHCPNak      = 6

	// Sizes
	BootpVendorLen = 64
	DHCPOptLen     = 312

	// Number of BOOTP clients
	NBBootpClients = 16

	// Lease time in seconds (24 hours)
	LeaseTime = 24 * 3600
)

BOOTP/DHCP constants Reference: tinyemu-2019-12-21/slirp/bootp.h:1-93

View Source
const (
	IPVersion = 4

	// Fragment offset field flags
	IPDF      = 0x4000 // don't fragment flag
	IPMF      = 0x2000 // more fragments flag
	IPOffMask = 0x1fff // mask for fragmenting bits

	// Maximum packet size
	IPMaxPacket = 65535

	// IP type of service
	IPTOSLowDelay    = 0x10
	IPTOSThroughput  = 0x08
	IPTOSReliability = 0x04

	// Time to live
	MaxTTL    = 255 // maximum time to live (seconds)
	IPDefTTL  = 64  // default ttl, from RFC 1340
	IPFragTTL = 60  // time to live for frags, slowhz
	IPTTLDEC  = 1   // subtracted when forwarding

	// Default maximum segment size
	IPMSS = 576

	// Protocol numbers
	IPProtoICMP = 1
	IPProtoTCP  = 6
	IPProtoUDP  = 17
)

IP constants Reference: tinyemu-2019-12-21/slirp/ip.h

View Source
const (
	ICMPEchoReply     = 0  // echo reply
	ICMPUnreach       = 3  // dest unreachable
	ICMPSourceQuench  = 4  // packet lost, slow down
	ICMPRedirect      = 5  // shorter route
	ICMPEcho          = 8  // echo service
	ICMPRouterAdvert  = 9  // router advertisement
	ICMPRouterSolicit = 10 // router solicitation
	ICMPTimXceed      = 11 // time exceeded
	ICMPParamProb     = 12 // ip header bad
	ICMPTStamp        = 13 // timestamp request
	ICMPTStampReply   = 14 // timestamp reply
	ICMPIReq          = 15 // information request
	ICMPIReqReply     = 16 // information reply
	ICMPMaskReq       = 17 // address mask request
	ICMPMaskReply     = 18 // address mask reply

	ICMPMaxType = 18

	// ICMP_UNREACH codes
	ICMPUnreachNet         = 0  // bad net
	ICMPUnreachHost        = 1  // bad host
	ICMPUnreachProtocol    = 2  // bad protocol
	ICMPUnreachPort        = 3  // bad port
	ICMPUnreachNeedFrag    = 4  // IP_DF caused drop
	ICMPUnreachSrcFail     = 5  // src route failed
	ICMPUnreachNetUnknown  = 6  // unknown net
	ICMPUnreachHostUnknown = 7  // unknown host
	ICMPUnreachIsolated    = 8  // src host isolated
	ICMPUnreachNetProhib   = 9  // prohibited access
	ICMPUnreachHostProhib  = 10 // ditto
	ICMPUnreachTOSNet      = 11 // bad tos for net
	ICMPUnreachTOSHost     = 12 // bad tos for host

	// ICMP_REDIRECT codes
	ICMPRedirectNet     = 0 // for network
	ICMPRedirectHost    = 1 // for host
	ICMPRedirectTOSNet  = 2 // for tos and net
	ICMPRedirectTOSHost = 3 // for tos and host

	// ICMP_TIMXCEED codes
	ICMPTimXceedInTrans = 0 // ttl==0 in transit
	ICMPTimXceedReass   = 1 // ttl==0 in reass

	// ICMP_PARAMPROB codes
	ICMPParamProbOptAbsent = 1 // req. opt. absent

	// ICMP lengths
	ICMPMinLen  = 8                    // abs minimum
	ICMPTSLen   = 8 + 3*4              // timestamp
	ICMPMaskLen = 12                   // address mask
	ICMPAdvLen  = 8 + IPHeaderSize + 8 // min for error advice

	// ICMPMaxDataLen is the maximum data length for ICMP error payloads.
	// ICMP fragmentation is illegal per RFC 792 - all hosts must accept 576 bytes.
	// Maximum payload = IPMSS(576) - IP_header(20) - ICMP_header(8) = 548 bytes.
	// This ensures ICMP errors never exceed the minimum MTU and need no fragmentation.
	// Reference: tinyemu-2019-12-21/slirp/ip_icmp.c:183-187
	ICMPMaxDataLen = IPMSS - 28
)

ICMP types and codes. Reference: tinyemu-2019-12-21/slirp/ip_icmp.h:111-147

View Source
const (
	// MinCSize is the amount to increase mbuf if too small
	MinCSize = 4096

	// Mbuf flags
	MBufExt      = 0x01 // m_ext points to more (malloced) data
	MBufFreeList = 0x02 // mbuf is on free list
	MBufUsedList = 0x04 // mbuf is on used list (for dtom())
	MBufDoFree   = 0x08 // when m_free is called, free() it

	// Interface constants
	// Reference: tinyemu-2019-12-21/slirp/if.h
	IFMTU        = 1500
	IFMRU        = 1500
	IFMaxLinkHdr = 2 + 14 + 40 // 2 for alignment, 14 for ethernet, 40 for TCP/IP

	// MbufThresh is the threshold above which mbufs are marked for freeing
	MbufThresh = 30
)

Mbuf constants Reference: tinyemu-2019-12-21/slirp/mbuf.h

View Source
const (
	EthALen = 6  // Ethernet address length
	EthHLen = 14 // Ethernet header length

	EthPIP  = 0x0800 // IP protocol
	EthPARP = 0x0806 // ARP protocol

	ARPOpRequest = 1 // ARP request
	ARPOpReply   = 2 // ARP reply
)

Ethernet constants Reference: tinyemu-2019-12-21/slirp/slirp.c:537-544

View Source
const (
	SSNoFDRef        = 0x001 // No fd reference
	SSIsFConnecting  = 0x002 // Socket is connecting to peer
	SSIsFConnected   = 0x004 // Socket is connected to peer
	SSFCantRcvMore   = 0x008 // Socket can't receive more from peer
	SSFCantSendMore  = 0x010 // Socket can't send more to peer
	SSFWDrain        = 0x040 // We received a FIN, drain data
	SSCTL            = 0x080
	SSFAcceptConn    = 0x100  // Socket is accepting connections
	SSFAcceptOnce    = 0x200  // Socket will die after one accept
	SSPersistentMask = 0xf000 // Unremovable state bits
	SSHostFwd        = 0x1000 // Socket describes host->guest forwarding
	SSIncoming       = 0x2000 // Connection was initiated by host on internet

	// Socket expiration times
	SOExpire     = 240000
	SOExpireFast = 10000
)

Socket state bits. Reference: tinyemu-2019-12-21/slirp/socket.h:61-75

View Source
const (
	EmuNone      = 0x0
	EmuCTL       = 0x1
	EmuFTP       = 0x2
	EmuKSH       = 0x3
	EmuIRC       = 0x4
	EmuRealAudio = 0x5
	EmuRLogin    = 0x6
	EmuIdent     = 0x7
	EmuRSH       = 0x8
	EmuNoConnect = 0x10 // Don't connect
)

Protocol emulation types. Reference: tinyemu-2019-12-21/slirp/misc.h:25-37

View Source
const (
	// PRSlowHz is the number of slow timeouts per second (approximately 2).
	// Reference: tinyemu-2019-12-21/slirp/tcp.h:38
	PRSlowHz = 2

	// TCPIssIncr is the increment for tcp_iss each second.
	// Reference: tinyemu-2019-12-21/slirp/tcp.h:162
	TCPIssIncr = 125 * 1024
)
View Source
const (
	TCPSClosed      = 0  // closed
	TCPSListen      = 1  // listening for connection
	TCPSSynSent     = 2  // active, have sent syn
	TCPSSynReceived = 3  // have sent and received syn
	TCPSEstablished = 4  // established
	TCPSCloseWait   = 5  // rcvd fin, waiting for close
	TCPSFinWait1    = 6  // have closed, sent fin
	TCPSClosing     = 7  // closed xchd FIN; await FIN ACK
	TCPSLastAck     = 8  // had fin and close; await FIN ACK
	TCPSFinWait2    = 9  // have closed, fin is acked
	TCPSTimeWait    = 10 // in 2*msl quiet wait after close
)

TCP connection states. Reference: tinyemu-2019-12-21/slirp/tcp.h:122-135

View Source
const (
	TFAckNow     = 0x0001 // ack peer immediately
	TFDelAck     = 0x0002 // ack, but try to delay it
	TFNoDelay    = 0x0004 // don't delay packets to coalesce
	TFNoOpt      = 0x0008 // don't use tcp options
	TFSentFin    = 0x0010 // have sent FIN
	TFReqScale   = 0x0020 // have/will request window scaling
	TFRcvdScale  = 0x0040 // other side has requested scaling
	TFReqTstmp   = 0x0080 // have/will request timestamps
	TFRcvdTstmp  = 0x0100 // a timestamp was received in SYN
	TFSackPermit = 0x0200 // other side said I could SACK
)

TCP flag constants. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:53-62

View Source
const (
	TCPRTTScale    = 8 // multiplier for srtt; 3 bits frac.
	TCPRTTShift    = 3 // shift for srtt; 3 bits frac.
	TCPRTTVarScale = 4 // multiplier for rttvar; 2 bits
	TCPRTTVarShift = 2 // shift for rttvar; 2 bits
)

TCP RTT scaling constants. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:140-143

View Source
const (
	THFin  = 0x01
	THSyn  = 0x02
	THRst  = 0x04
	THPush = 0x08
	THAck  = 0x10
	THUrg  = 0x20
)

TCP header flags. Reference: tinyemu-2019-12-21/slirp/tcp.h:61-66

View Source
const (
	TCPOptEOL    = 0
	TCPOptNOP    = 1
	TCPOptMaxSeg = 2

	TCPOLenMaxSeg = 4 // length of MAXSEG option
)

TCP option constants. Reference: tinyemu-2019-12-21/slirp/tcp.h:74-78

View Source
const (
	TCPSndSpace = 8192
	TCPRcvSpace = 8192
)

TCP buffer space constants. Reference: tinyemu-2019-12-21/slirp/tcp.h:41-42

View Source
const (
	TCPOobHaveData = 0x01
	TCPOobHadData  = 0x02
)

Out-of-band flags. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:114-115

View Source
const (
	TCPTRexmt   = 0 // retransmit
	TCPTPersist = 1 // retransmit persistence
	TCPTKeep    = 2 // keep alive
	TCPT2MSL    = 3 // 2*msl quiet time timer
)

Timer indices. Reference: tinyemu-2019-12-21/slirp/tcp_timer.h:40-45

View Source
const (
	TCPTVMSL       = 5 * PRSlowHz        // max seg lifetime (hah!)
	TCPTVSrttBase  = 0                   // base roundtrip time; if 0, no idea yet
	TCPTVSrttDflt  = 3 * PRSlowHz        // assumed RTT if no info
	TCPTVPersMin   = 5 * PRSlowHz        // retransmit persistence
	TCPTVPersMax   = 60 * PRSlowHz       // maximum persist interval
	TCPTVKeepInit  = 75 * PRSlowHz       // initial connect keep alive
	TCPTVKeepIdle  = 120 * 60 * PRSlowHz // dflt time before probing
	TCPTVKeepIntvl = 75 * PRSlowHz       // default probe interval
	TCPTVKeepCnt   = 8                   // max probes before drop
	TCPTVMin       = 1 * PRSlowHz        // minimum allowable value
	TCPTVRexmtMax  = 12 * PRSlowHz       // max allowable REXMT value
	TCPLingerTime  = 120                 // linger at most 2 minutes
	TCPMaxRxtShift = 12                  // maximum retransmits
)

Time constants. Reference: tinyemu-2019-12-21/slirp/tcp_timer.h:86-105

View Source
const BootpMinSize = 1 + 1 + 1 + 1 + 4 + 2 + 2 + 4 + 4 + 4 + 4 + 16 + 64 + 128 + 4 // 240 bytes

BootpMinSize is the minimum BOOTP packet size we accept for input. This is the fixed BOOTP header (236 bytes) + DHCP magic cookie (4 bytes). DHCP clients may send shorter packets than the full 548-byte BOOTP structure.

View Source
const BootpSize = 1 + 1 + 1 + 1 + 4 + 2 + 2 + 4 + 4 + 4 + 4 + 16 + 64 + 128 + 312 // 548 bytes

BootpSize is the size of the BOOTP packet structure (without IP/UDP headers)

View Source
const ICMPHeaderSize = 8

ICMPHeaderSize is the size of an ICMP header (8 bytes).

View Source
const IPHeaderSize = 20

IPHeaderSize is the size of an IP header without options (20 bytes).

View Source
const MaxTCPOptLen = 32

MaxTCPOptLen is the maximum TCP options length. Reference: tinyemu-2019-12-21/slirp/tcp_output.c:50

View Source
const SOOptions = false

SOOptions controls whether keepalive is enabled. Reference: tinyemu-2019-12-21/slirp/slirp.h:253 Reference: tinyemu-2019-12-21/slirp/slirp_config.h:10 DO_KEEPALIVE is 0, so SO_OPTIONS is always false.

View Source
const TCPMaxIdle = TCPTVKeepCnt * TCPTVKeepIntvl

TCPMaxIdle is the maximum idle time before connection is dropped. Reference: tinyemu-2019-12-21/slirp/slirp.h:254

View Source
const TCPMaxSeg = IFMTU - 40 // MTU - IP header - TCP header

TCPMaxSeg is the default maximum segment size. Reference: tinyemu-2019-12-21/slirp/tcp.h:103

View Source
const TCPMaxWin = 65535

TCPMaxWin is the largest value for (unscaled) window. Reference: tinyemu-2019-12-21/slirp/tcp.h:100

View Source
const TCPMaxWinShift = 14

TCPMaxWinShift is the maximum window shift. Reference: tinyemu-2019-12-21/slirp/tcp.h:101

View Source
const TCPNStates = 11

TCPNStates is the number of TCP states. Reference: tinyemu-2019-12-21/slirp/tcp.h:120

View Source
const (
	TCPRexmtThresh = 3 // dup acks before fast retransmit
)

TCP input processing constants. Reference: tinyemu-2019-12-21/slirp/tcp_input.c:44-51

View Source
const TCPTNTimers = 4

TCPTNTimers is the number of TCP timers. Reference: tinyemu-2019-12-21/slirp/tcp_timer.h:40

View Source
const UDPHeaderSize = 8

UDPHeaderSize is the size of a UDP header

Variables

View Source
var ICMPPingMsg = []byte("This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\n")

ICMPPingMsg is the message sent when emulating PING. Reference: tinyemu-2019-12-21/slirp/ip_icmp.c:38

View Source
var LoopbackAddr = net.IPv4(127, 0, 0, 1)

LoopbackAddr is the loopback address (127.0.0.1).

View Source
var RFC1533Cookie = []byte{99, 130, 83, 99}

RFC1533Cookie is the magic cookie for DHCP options Reference: tinyemu-2019-12-21/slirp/bootp.h:9

View Source
var SpecialEthAddr = [6]byte{0x52, 0x55, 0x00, 0x00, 0x00, 0x00}

SpecialEthAddr is the special Ethernet address used by slirp. Reference: tinyemu-2019-12-21/slirp/slirp.c:30-31

View Source
var TCPBackoff = [TCPMaxRxtShift + 1]int{1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64}

TCPBackoff is the backoff multiplier table for retransmissions. Reference: tinyemu-2019-12-21/slirp/tcp_timer.c:115-116

View Source
var ZeroEthAddr = [6]byte{0, 0, 0, 0, 0, 0}

ZeroEthAddr is all zeros. Reference: tinyemu-2019-12-21/slirp/slirp.c:34

Functions

func Cksum

func Cksum(m *Mbuf, length int) uint16

Cksum computes the Internet checksum for the data in mbuf m. Returns 0xffff for nil/empty mbufs (checksum of no data is all ones). Reference: tinyemu-2019-12-21/slirp/cksum.c:48-139

func CksumData

func CksumData(data []byte) uint16

CksumData computes the Internet checksum for the given data. This implements the one's complement sum algorithm from RFC 1071.

The C version has byte_swapped handling because it casts pointers to read 16-bit words directly from memory (e.g., `sum += w[0]` where w is uint16_t*). On odd-aligned addresses, this causes shifted byte reads. Go doesn't need this because we explicitly read bytes and construct 16-bit values: `sum += uint32(data[i])<<8 | uint32(data[i+1])` - always consistent.

Reference: tinyemu-2019-12-21/slirp/cksum.c:48-139

func CksumFinish

func CksumFinish(sum uint32) uint16

CksumFinish folds and complements a partial checksum.

func CksumPartial

func CksumPartial(data []byte) uint32

CksumPartial computes a partial checksum (without final complement). Useful for combining checksums of different parts.

func ForkExec

func ForkExec() int

ForkExec is not implemented. The C code has this disabled (returns 0) via #if 1 preprocessor directive.

Reference: tinyemu-2019-12-21/slirp/misc.c:100-105 The enabled version just returns 0 (not implemented).

func GetTimeMs

func GetTimeMs() uint32

GetTimeMs returns the current time in milliseconds from a monotonic clock. This is used for timing operations like TCP retransmission and connection expiry.

Reference: tinyemu-2019-12-21/slirp/misc.c:88-95

func IPStripOptions

func IPStripOptions(m *Mbuf)

IPStripOptions strips IP options from an mbuf, leaving only the standard 20-byte IP header. The data following the options is moved up to fill the gap. Reference: tinyemu-2019-12-21/slirp/ip_input.c:671-685 (ip_stripoptions)

func Insque

func Insque(element, head *QueueHead)

Insque inserts element after head in a doubly-linked queue. This matches BSD insque() semantics exactly.

Reference: tinyemu-2019-12-21/slirp/misc.c:19-29

func Lprint

func Lprint(format string, args ...interface{})

Lprint prints a formatted message to stdout. This is a simple logging function used throughout slirp.

Reference: tinyemu-2019-12-21/slirp/misc.c:267-274

Note: In Go, use fmt.Printf or log.Printf directly. This function is provided for API compatibility during porting.

func NewEthernetDevice

func NewEthernetDevice() *virtio.EthernetDevice

NewEthernetDevice creates a new EthernetDevice backed by Slirp userspace networking. This provides network connectivity without requiring root access or TUN/TAP devices.

The network configuration matches C TinyEMU's defaults:

  • Network: 10.0.2.0/24
  • Gateway/Host: 10.0.2.2
  • DNS: 10.0.2.3
  • Guest DHCP start: 10.0.2.15

Reference: tinyemu-2019-12-21/temu.c:497-530 (slirp_open)

func NewEthernetDeviceWithConfig

func NewEthernetDeviceWithConfig(cfg SlirpConfig) *virtio.EthernetDevice

NewEthernetDeviceWithConfig creates a new EthernetDevice backed by Slirp with the given configuration.

Reference: tinyemu-2019-12-21/temu.c:497-530 (slirp_open) Reference: tinyemu-2019-12-21/slirp/slirp.c:189-226 (slirp_init)

func Poll

func Poll(es *virtio.EthernetDevice)

Poll processes pending I/O for a Slirp-backed EthernetDevice. This should be called periodically from the main emulation loop.

In the C implementation, this is handled by slirp_select_fill and slirp_select_poll using file descriptor sets and select(). In Go, we use a polling approach with non-blocking sockets.

Reference: tinyemu-2019-12-21/slirp/slirp.c:239-355 (slirp_select_fill) Reference: tinyemu-2019-12-21/slirp/slirp.c:357-534 (slirp_select_poll)

func Remque

func Remque(element *QueueHead)

Remque removes element from a doubly-linked queue. This matches BSD remque() semantics exactly.

Reference: tinyemu-2019-12-21/slirp/misc.c:31-38

func SlirpMSize

func SlirpMSize() int

SlirpMSize calculates the size of an mbuf including header space. Reference: tinyemu-2019-12-21/slirp/mbuf.c:26

func SlirpSend

func SlirpSend(so *Socket, buf []byte, flags int) int

SlirpSend sends data on a socket. This is a wrapper around the system send call. Reference: tinyemu-2019-12-21/slirp/slirp.c:773-782

func TCPCtl

func TCPCtl(so *Socket) int

TCPCtl does misc. config of SLiRP while it's running. Return 0 if this connection is to be closed, 1 otherwise, return 2 if this is a command-line connection. Reference: tinyemu-2019-12-21/slirp/tcp_subr.c:884-915

func TCPSHaveEstablished

func TCPSHaveEstablished(state int16) bool

TCPSHaveEstablished returns true if connection is established. Reference: tinyemu-2019-12-21/slirp/tcp.h:140

func TCPSHaveRcvdFin

func TCPSHaveRcvdFin(state int16) bool

TCPSHaveRcvdFin returns true if we have received FIN. Reference: tinyemu-2019-12-21/slirp/tcp.h:141

func TCPSHaveRcvdSyn

func TCPSHaveRcvdSyn(state int16) bool

TCPSHaveRcvdSyn returns true if we have received SYN. Reference: tinyemu-2019-12-21/slirp/tcp.h:139

func TCPSockClosed

func TCPSockClosed(tp *TCPCB)

TCPSockClosed handles socket closure for TCP. Reference: tinyemu-2019-12-21/slirp/tcp_subr.c:282-308

func WriteIPToMbuf

func WriteIPToMbuf(m *Mbuf, ip *IP)

WriteIPToMbuf writes the IP header to the beginning of the mbuf.

Types

type BOOTPClient

type BOOTPClient struct {
	Allocated uint16
	MACAddr   [6]byte
}

BOOTPClient represents a BOOTP/DHCP client entry. Reference: tinyemu-2019-12-21/slirp/bootp.h:115-118

type BootpT

type BootpT struct {
	// IP and UDP headers are handled separately
	Op     uint8     // packet opcode type
	Htype  uint8     // hardware addr type
	Hlen   uint8     // hardware addr length
	Hops   uint8     // gateway hops
	Xid    uint32    // transaction ID
	Secs   uint16    // seconds since boot began
	Unused uint16    // unused
	Ciaddr net.IP    // client IP address
	Yiaddr net.IP    // 'your' IP address
	Siaddr net.IP    // server IP address
	Giaddr net.IP    // gateway IP address
	Hwaddr [16]byte  // client hardware address
	Sname  [64]byte  // server host name
	File   [128]byte // boot file name
	Vend   [312]byte // vendor-specific area (DHCP options)
}

BootpT represents the BOOTP packet structure. This structure overlays the mbuf data following the IP and UDP headers. Reference: tinyemu-2019-12-21/slirp/bootp.h:95-113

func ParseBootp

func ParseBootp(data []byte) *BootpT

ParseBootp parses a BOOTP packet from mbuf data. The data should start at the BOOTP header (after IP and UDP headers). Accepts variable-length packets - DHCP clients may send shorter packets. Reference: tinyemu-2019-12-21/slirp/bootp.c

func (*BootpT) Marshal

func (bp *BootpT) Marshal(data []byte)

Marshal writes the BOOTP packet to a byte slice.

type ExList

type ExList struct {
	ExFPort uint16  // foreign port
	ExAddr  net.IP  // address
	ExPty   int     // pty mode (0, 1, 2, or 3)
	ExExec  string  // command to execute
	ExNext  *ExList // next entry
}

ExList represents an exec list entry for port forwarding. Reference: tinyemu-2019-12-21/slirp/misc.h:11-17

type ICMP

type ICMP struct {
	Type  uint8  // type of message
	Code  uint8  // type sub code
	Cksum uint16 // ones complement cksum of struct
	ID    uint16 // identifier (for echo)
	Seq   uint16 // sequence number (for echo)

}

ICMP represents an ICMP header. Reference: tinyemu-2019-12-21/slirp/ip_icmp.h:46-91

func ParseICMP

func ParseICMP(data []byte) *ICMP

ParseICMP parses an ICMP header from a byte slice.

func (*ICMP) Marshal

func (icmp *ICMP) Marshal(data []byte)

Marshal writes the ICMP header to a byte slice.

type IP

type IP struct {
	VersionIHL uint8  // version (4 bits) + header length (4 bits)
	TOS        uint8  // type of service
	Len        uint16 // total length
	ID         uint16 // identification
	Off        uint16 // fragment offset field
	TTL        uint8  // time to live
	Proto      uint8  // protocol
	Sum        uint16 // checksum
	Src        net.IP // source address (4 bytes for IPv4)
	Dst        net.IP // destination address (4 bytes for IPv4)
}

IP represents an IPv4 header. Reference: tinyemu-2019-12-21/slirp/ip.h:75-94

func IPFromMbuf

func IPFromMbuf(m *Mbuf) *IP

IPFromMbuf interprets the mbuf data as an IP header. This is equivalent to mtod(m, struct ip *) in C. Reference: tinyemu-2019-12-21/slirp/mbuf.h:45

func ParseIP

func ParseIP(data []byte) (*IP, int)

ParseIP parses an IP header from a byte slice. Returns the IP header and the number of bytes consumed.

func (*IP) HeaderLen

func (ip *IP) HeaderLen() uint8

HeaderLen returns the header length in 32-bit words.

func (*IP) HeaderLenBytes

func (ip *IP) HeaderLenBytes() int

HeaderLenBytes returns the header length in bytes.

func (*IP) Marshal

func (ip *IP) Marshal(data []byte)

Marshal writes the IP header to a byte slice. The slice must be at least IPHeaderSize bytes.

func (*IP) SetHeaderLen

func (ip *IP) SetHeaderLen(hl uint8)

SetHeaderLen sets the header length in 32-bit words.

func (*IP) SetVersion

func (ip *IP) SetVersion(v uint8)

SetVersion sets the IP version.

func (*IP) Version

func (ip *IP) Version() uint8

Version returns the IP version (should be 4).

type IPASFrag

type IPASFrag struct {
	Link QLink  // linked list
	Off  uint16 // fragment offset (in 8-byte units, then converted to bytes)
	Len  uint16 // fragment length (data only, not including IP header)
	TOS  uint8  // type of service (used for MF flag storage)
	M    *Mbuf  // mbuf holding this fragment
}

IPASFrag represents an IP header when holding a fragment. Reference: tinyemu-2019-12-21/slirp/ip.h:229-232

type IPQ

type IPQ struct {
	FragLink QLink  // to ip headers of fragments
	IPLink   QLink  // to other reass headers
	TTL      uint8  // time for reass q to live
	Proto    uint8  // protocol of this fragment
	ID       uint16 // sequence id for reassembly
	Src      net.IP // source address
	Dst      net.IP // destination address
	Slirp    *Slirp // back pointer to slirp instance
	M        *Mbuf  // mbuf holding this IPQ (for dtom)
}

IPQ represents an IP reassembly queue structure. Each fragment being reassembled is attached to one of these structures. Reference: tinyemu-2019-12-21/slirp/ip.h:215-222

type IPRaw

type IPRaw struct {
	HL    uint8
	TOS   uint8
	Len   uint16
	ID    uint16
	Off   uint16
	TTL   uint8
	Proto uint8
	Sum   uint16
	Src   net.IP
	Dst   net.IP
}

IPRaw is a raw IP header for direct byte manipulation.

func ParseIPRaw

func ParseIPRaw(data []byte) *IPRaw

ParseIPRaw parses an IP header from raw bytes. This is a simpler version that works directly with byte slice.

type Mbuf

type Mbuf struct {
	// Linked list pointers (from m_hdr)
	Next    *Mbuf // next mbuf in list
	Prev    *Mbuf // previous mbuf in list
	NextPkt *Mbuf // next packet in queue
	PrevPkt *Mbuf // previous packet

	// Flags and size
	Flags int // misc flags
	Size  int // total size of backing buffer (len(Dat))

	// Socket association
	So *Socket // associated socket

	// Data management - matches C m_dat/m_data/m_len semantics
	Dat    []byte // backing buffer (equivalent to m_dat/m_ext in C)
	Data   []byte // view of buffer from Offset: Dat[Offset:]
	Offset int    // offset of valid data start within Dat (m_data - m_dat)
	Len    int    // length of valid data (m_len)

	// Slirp context
	Slirp *Slirp // managing slirp instance
}

Mbuf represents a message buffer for network data. The design matches C mbuf semantics:

  • Dat is the backing buffer (equivalent to m_dat/m_ext)
  • Data is a view starting at Offset: Dat[Offset:]
  • Offset tracks where valid data starts within Dat (like m_data - m_dat)
  • Len is the length of valid data (like m_len)
  • Size is the total buffer size (like m_size)

This allows adjusting the data pointer without copying:

  • Trim from head: Offset += n, Len -= n, Data = Dat[Offset:]
  • Trim from tail: Len -= n
  • Prepend: Offset -= n (if room), Len += n, Data = Dat[Offset:]

Reference: tinyemu-2019-12-21/slirp/mbuf.h:85-92

func (*Mbuf) Adj

func (m *Mbuf) Adj(len int)

Adj adjusts the mbuf by trimming len bytes. Positive len trims from head (advances data pointer), negative from tail. Unlike the old implementation that copied data, this just adjusts the offset pointer, matching C semantics: m->m_data += len; m->m_len -= len; Reference: tinyemu-2019-12-21/slirp/mbuf.c:158-172

func (*Mbuf) Cat

func (m *Mbuf) Cat(n *Mbuf)

Cat appends mbuf n to mbuf m. Reference: tinyemu-2019-12-21/slirp/mbuf.c:112-125

func (*Mbuf) Copy

func (n *Mbuf) Copy(m *Mbuf, off, length int) int

Copy copies len bytes from mbuf m starting at offset off to mbuf n. Reference: tinyemu-2019-12-21/slirp/mbuf.c:178-187

func (*Mbuf) Free

func (m *Mbuf) Free()

Free frees the mbuf. Reference: tinyemu-2019-12-21/slirp/mbuf.c:78-105

func (*Mbuf) FreeRoom

func (m *Mbuf) FreeRoom() int

FreeRoom returns the free space in the mbuf (from end of valid data to end of buffer). C: M_FREEROOM(m) = M_ROOM(m) - m->m_len

M_ROOM(m) = (m->m_dat + m->m_size) - m->m_data = Size - Offset

So FreeRoom = Size - Offset - Len Reference: tinyemu-2019-12-21/slirp/mbuf.h:82

func (*Mbuf) Inc

func (m *Mbuf) Inc(size int)

Inc increases the mbuf size to at least 'size' bytes. Preserves the offset of data within the buffer, matching C semantics:

datasize = m->m_data - m->m_dat;  // save offset
memcpy(dat, m->m_dat, m->m_size); // copy ENTIRE buffer
m->m_data = m->m_ext + datasize;  // restore offset

Reference: tinyemu-2019-12-21/slirp/mbuf.c:129-154

func (*Mbuf) MFree

func (m *Mbuf) MFree()

MFree is an alias for Free (m_free and m_freem are the same in slirp). Reference: tinyemu-2019-12-21/slirp/mbuf.h:36

func (*Mbuf) MFreem

func (m *Mbuf) MFreem()

MFreem is an alias for Free (m_free and m_freem are the same in slirp). Reference: tinyemu-2019-12-21/slirp/mbuf.h:36

func (*Mbuf) MInc

func (m *Mbuf) MInc(size int)

MInc is an alias for Inc.

func (*Mbuf) Prepend

func (m *Mbuf) Prepend(n int) bool

Prepend moves the data pointer backward by n bytes, expanding the valid data region. This is the inverse of Adj for positive values - it "un-trims" from the head. The trimmed data is still in the buffer and becomes valid again. Returns true if successful, false if there's not enough room to prepend. Equivalent to C's: m->m_data -= n; m->m_len += n;

func (*Mbuf) ResetData

func (m *Mbuf) ResetData()

ResetData resets the data pointer to the beginning of the backing buffer. This is equivalent to C's m_data = m_dat.

func (*Mbuf) Room

func (m *Mbuf) Room() int

Room returns the room in the mbuf from the data start to end of buffer. C: M_ROOM(m) = (m->m_dat + m->m_size) - m->m_data = Size - Offset Reference: tinyemu-2019-12-21/slirp/mbuf.h:74-77

func (*Mbuf) SetBuffer

func (m *Mbuf) SetBuffer(data []byte)

SetBuffer replaces the mbuf's backing buffer with a new one. This should be used when code needs to completely replace the buffer, rather than directly assigning to m.Data which would break the Dat/Data invariant. The offset is reset to 0, and Len is left unchanged (caller should set it).

func (*Mbuf) SetDataOffset

func (m *Mbuf) SetDataOffset(offset int)

SetDataOffset sets the data start offset within the backing buffer. This updates both Offset and Data to maintain the invariant Data = Dat[Offset:]. Equivalent to C's m_data = m_dat + offset.

type QLink struct {
	Next *QLink
	Prev *QLink
	// contains filtered or unexported fields
}

QLink is a doubly linked list link. Reference: tinyemu-2019-12-21/slirp/ip.h:192-194

type QueueHead

type QueueHead struct {
	Link  *QueueHead // Next element (qh_link in C)
	RLink *QueueHead // Previous element (qh_rlink in C)
}

QueueHead is a doubly-linked list element. Structures that need to be queued should embed this as their first field.

Reference: tinyemu-2019-12-21/slirp/misc.c:14-17

func (*QueueHead) Init

func (q *QueueHead) Init()

Init initializes a queue head as an empty circular list. After Init, q.Link == q and q.RLink == q.

func (*QueueHead) IsEmpty

func (q *QueueHead) IsEmpty() bool

IsEmpty returns true if the queue is empty (only contains the sentinel).

type SBuf

type SBuf struct {
	SbCC      int    // actual chars in buffer
	SbDataLen int    // length of data buffer
	SbWPtr    int    // write pointer offset (where next bytes should be written)
	SbRPtr    int    // read pointer offset (where next byte should be read)
	SbData    []byte // actual data buffer
}

SBuf is a circular buffer for socket send/receive buffers. Reference: tinyemu-2019-12-21/slirp/sbuf.h:14-22

func (*SBuf) SbAppendBytes

func (sb *SBuf) SbAppendBytes(data []byte)

SbAppendBytes appends raw bytes to the sbuf. This is a helper for cases where we want to add data directly.

func (*SBuf) SbBytes

func (sb *SBuf) SbBytes() []byte

SbBytes returns a copy of the data in the buffer. This is useful for testing and debugging.

func (*SBuf) SbCopy

func (sb *SBuf) SbCopy(off, length int, to []byte)

SbCopy copies data from the sbuf to a destination buffer. Doesn't update the sbuf rptr; that's done in SbDrop when data is acked. Reference: tinyemu-2019-12-21/slirp/sbuf.c:161-181

func (*SBuf) SbDrop

func (sb *SBuf) SbDrop(num int)

SbDrop removes num bytes from the front of the buffer. Reference: tinyemu-2019-12-21/slirp/sbuf.c:19-32

func (*SBuf) SbFlush

func (sb *SBuf) SbFlush()

SbFlush drops all data in the buffer. Reference: tinyemu-2019-12-21/slirp/sbuf.h:11

func (*SBuf) SbFree

func (sb *SBuf) SbFree()

SbFree frees the buffer data. Reference: tinyemu-2019-12-21/slirp/sbuf.c:13-16

NOTE: Go version also resets all fields to zero. C only calls free(sb_data). This is safe because sbfree is always called immediately before sofree, so the stale fields in C are never accessed.

func (*SBuf) SbReserve

func (sb *SBuf) SbReserve(size int)

SbReserve allocates or reallocates the buffer to the specified size. Reference: tinyemu-2019-12-21/slirp/sbuf.c:35-55

func (*SBuf) SbSpace

func (sb *SBuf) SbSpace() int

SbSpace returns available space in the buffer. Reference: tinyemu-2019-12-21/slirp/sbuf.h:12

type SavedTCPIPHeader

type SavedTCPIPHeader struct {
	// Header contains the full TCP/IP header bytes (IP + TCP + options)
	// This is saved before headers are stripped from the mbuf
	Header []byte

	// IPTotalLen is the total IP packet length (restored for error responses)
	// Reference: tcp_input.c:274 (save_ip.ip_len += iphlen)
	IPTotalLen uint16

	// TOS is the IP Type of Service byte
	TOS uint8

	// Extracted header fields for convenience (in host byte order)
	SrcIP   uint32 // source IP address
	DstIP   uint32 // destination IP address
	SrcPort uint16 // source TCP port
	DstPort uint16 // destination TCP port
}

SavedTCPIPHeader preserves the original TCP/IP header for RST and ICMP responses. Reference: tinyemu-2019-12-21/slirp/tcp_input.c:268-274 (save_ip = *ip) The C code saves the IP header before stripping so it can be used later for tcp_respond() and icmp_error() calls at dropwithreset and other error paths.

type Slirp

type Slirp struct {
	// Virtual network configuration
	VNetworkAddr    net.IP // network address
	VNetworkMask    net.IP // network mask
	VHostAddr       net.IP // host address (gateway)
	VDHCPStartAddr  net.IP // DHCP start address
	VNameserverAddr net.IP // nameserver address

	// ARP cache for guest IP addresses
	ClientEthAddr  [6]byte
	ClientIPAddr   net.IP
	ClientHostname string

	// Configuration
	Restricted bool

	// Mbuf states
	MFreeList   Mbuf // free list head
	MUsedList   Mbuf // used list head
	MbufAlloced int  // number of mbufs allocated

	// Interface states
	IfQueued int   // number of packets queued
	IfFastQ  Mbuf  // fast queue (for interactive data)
	IfBatchQ Mbuf  // queue for non-interactive data
	NextM    *Mbuf // pointer to next mbuf to output

	// IP states
	IPID uint16 // ip packet counter, for IDs
	// IP fragment reassembly queue
	// Reference: tinyemu-2019-12-21/slirp/slirp.h:178
	IPQ IPQ // IP reassembly queue head

	// BOOTP/DHCP states
	// Reference: tinyemu-2019-12-21/slirp/slirp.h:200-202
	BootpClients  [NBBootpClients]BOOTPClient
	BootpFilename string

	// TCP states
	TCB       Socket // TCP socket list head
	TCPLastSo *Socket
	TCPIss    uint32 // tcp initial send seq #
	TCPNow    uint32 // for RFC 1323 timestamps

	// UDP states
	UDB       Socket // UDP socket list head
	UDPLastSo *Socket

	// Exec list for port forwarding
	// Reference: tinyemu-2019-12-21/slirp/slirp.h:184
	ExecList *ExList

	// Output callback - called to send packets to the virtual network interface
	// Reference: tinyemu-2019-12-21/slirp/libslirp.h:31
	OutputFunc func(opaque interface{}, pkt []byte)

	// CanOutput callback - returns true if output is currently possible
	// Reference: tinyemu-2019-12-21/slirp/if.c:165
	CanOutput func(opaque interface{}) bool

	// Opaque user data
	Opaque interface{}

	// Tracer for debug output. If set, trace messages will be logged.
	Tracer Tracer
	// contains filtered or unexported fields
}

Slirp represents a slirp networking instance. Reference: tinyemu-2019-12-21/slirp/slirp.h:168-219

func GetSlirp

func GetSlirp(es *virtio.EthernetDevice) *Slirp

GetSlirp returns the underlying Slirp instance from an EthernetDevice created by NewEthernetDevice. Returns nil if the device is not Slirp-backed.

func NewSlirp

func NewSlirp() *Slirp

NewSlirp creates a new Slirp instance with default configuration. Reference: tinyemu-2019-12-21/slirp/slirp.c:189-226 (slirp_init)

func (*Slirp) ARPInput

func (s *Slirp) ARPInput(pkt []byte)

ARPInput processes an incoming ARP packet. Reference: tinyemu-2019-12-21/slirp/slirp.c:570-626

func (*Slirp) AddExec

func (s *Slirp) AddExec(doPty int, args string, guestAddr net.IP, guestPort int) int

AddExec adds an entry to the exec list for port forwarding. Reference: tinyemu-2019-12-21/slirp/slirp.c:756-771

func (*Slirp) AddHostfwd

func (s *Slirp) AddHostfwd(isUDP bool, hostAddr net.IP, hostPort int, guestAddr net.IP, guestPort int) int

AddHostfwd adds a host port forwarding rule. is_udp: 0 for TCP, non-zero for UDP Returns 0 on success, -1 on error. Reference: tinyemu-2019-12-21/slirp/slirp.c:738-754

func (*Slirp) BootpInput

func (s *Slirp) BootpInput(m *Mbuf)

BootpInput processes an incoming BOOTP packet. Reference: tinyemu-2019-12-21/slirp/bootp.c:307-314

func (*Slirp) FindCtlSocket

func (s *Slirp) FindCtlSocket(guestAddr net.IP, guestPort int) *Socket

FindCtlSocket finds a TCP socket by guest address and port. Reference: tinyemu-2019-12-21/slirp/slirp.c:785-796

func (*Slirp) ICMPError

func (s *Slirp) ICMPError(msrc *Mbuf, icmpType, code uint8, minsize int, message string)

ICMPError sends an ICMP error message in response to a situation. msrc is used as a template but is NOT freed. Reference: tinyemu-2019-12-21/slirp/ip_icmp.c:188-300

func (*Slirp) ICMPInput

func (s *Slirp) ICMPInput(m *Mbuf, hlen int)

ICMPInput processes a received ICMP message. Reference: tinyemu-2019-12-21/slirp/ip_icmp.c:66-166

func (*Slirp) ICMPReflect

func (s *Slirp) ICMPReflect(m *Mbuf)

ICMPReflect reflects the IP packet back to the source. Reference: tinyemu-2019-12-21/slirp/ip_icmp.c:306-351

func (*Slirp) IPInput

func (s *Slirp) IPInput(m *Mbuf)

IPInput processes an incoming IP packet. Reference: tinyemu-2019-12-21/slirp/ip_input.c:71-233

func (*Slirp) IPOutput

func (s *Slirp) IPOutput(so *Socket, m *Mbuf) int

IPOutput sends an IP packet. The packet in mbuf m contains a skeletal IP header (with len, off, ttl, proto, tos, src, dst). The mbuf chain containing the packet will be freed. This delegates to ipOutput which has the full implementation including fragmentation. Reference: tinyemu-2019-12-21/slirp/ip_output.c:53-172

func (*Slirp) IPSlowtimo

func (s *Slirp) IPSlowtimo()

IPSlowtimo handles IP timer processing. If a timer expires on a reassembly queue, discard it. Reference: tinyemu-2019-12-21/slirp/ip_input.c:442-461

func (*Slirp) IfEncap

func (s *Slirp) IfEncap(ipData []byte)

IfEncap encapsulates an IP packet in an Ethernet frame and outputs it. If the client Ethernet address is unknown, sends an ARP request instead. Reference: tinyemu-2019-12-21/slirp/slirp.c:663-711

func (*Slirp) IfInit

func (s *Slirp) IfInit()

IfInit initializes the interface output queues. Reference: tinyemu-2019-12-21/slirp/if.c:29-34

func (*Slirp) IfOutput

func (s *Slirp) IfOutput(so *Socket, ifm *Mbuf)

IfOutput queues a packet for output on the network interface. There are 2 output queues: if_fastq for interactive sessions and if_batchq for bulk data. Each queue is a doubly-linked list of doubly-linked lists of mbufs, with each inner list belonging to one session (socket). Reference: tinyemu-2019-12-21/slirp/if.c:50-139

func (*Slirp) IfStart

func (s *Slirp) IfStart()

IfStart sends packets from the output queues. Packets on if_fastq get absolute priority. For if_batchq, we send one packet from each session in round-robin fashion for fairness. Reference: tinyemu-2019-12-21/slirp/if.c:154-209

func (*Slirp) Input

func (s *Slirp) Input(pkt []byte)

Input processes an incoming Ethernet packet from the guest. This is the main entry point for guest-to-host packets. Reference: tinyemu-2019-12-21/slirp/slirp.c:628-660

func (*Slirp) MGet

func (s *Slirp) MGet() *Mbuf

MGet is an alias for NewMbuf for API compatibility with C code. Reference: tinyemu-2019-12-21/slirp/mbuf.c:43-76

func (*Slirp) MInit

func (s *Slirp) MInit()

MInit initializes mbuf lists for a Slirp instance. Reference: tinyemu-2019-12-21/slirp/mbuf.c:28-33

func (*Slirp) NewMbuf

func (s *Slirp) NewMbuf() *Mbuf

NewMbuf creates a new mbuf with the default size. This is the Go equivalent of m_get(). Reference: tinyemu-2019-12-21/slirp/mbuf.c:43-76

func (*Slirp) RemoveHostfwd

func (s *Slirp) RemoveHostfwd(isUDP bool, hostAddr net.IP, hostPort int) int

RemoveHostfwd removes a host port forwarding rule. Returns 0 if found and removed, -1 if not found. Reference: tinyemu-2019-12-21/slirp/slirp.c:714-736

func (*Slirp) SoCreate

func (s *Slirp) SoCreate() *Socket

SoCreate creates a new socket. Reference: tinyemu-2019-12-21/slirp/socket.c:40-52

func (*Slirp) SoSendTo

func (s *Slirp) SoSendTo(so *Socket, m *Mbuf) error

SoSendTo sends data from an mbuf to the socket's foreign address. This is a wrapper around Socket.SoSendTo for Slirp method compatibility. Reference: tinyemu-2019-12-21/slirp/socket.c:532-573

func (*Slirp) SocketCanRecv

func (s *Slirp) SocketCanRecv(guestAddr net.IP, guestPort int) int

SocketCanRecv checks how much data can be received on a control socket. Returns 0 if the socket cannot receive, otherwise returns the available space. Reference: tinyemu-2019-12-21/slirp/slirp.c:798-813

func (*Slirp) SocketRecv

func (s *Slirp) SocketRecv(guestAddr net.IP, guestPort int, buf []byte)

SocketRecv receives data on a control socket. Reference: tinyemu-2019-12-21/slirp/slirp.c:815-828

func (*Slirp) TCPFasttimo

func (slirp *Slirp) TCPFasttimo()

TCPFasttimo is the fast timeout routine for processing delayed acks. Called every 200ms. Reference: tinyemu-2019-12-21/slirp/tcp_timer.c:40-57

func (*Slirp) TCPInput

func (s *Slirp) TCPInput(m *Mbuf, iphlen int)

TCPInput processes an incoming TCP segment. Reference: tinyemu-2019-12-21/slirp/tcp_input.c:216-1287

func (*Slirp) TCPListen

func (s *Slirp) TCPListen(haddr net.IP, hport uint16, laddr net.IP, lport uint16, flags int) *Socket

TCPListen creates a TCP listening socket for port forwarding. Returns the socket on success, nil on error. Reference: tinyemu-2019-12-21/slirp/socket.c:579-649 NOTE: Go's net.ListenTCP handles socket creation, SO_REUSEADDR, bind, and listen. The C version also sets SO_OOBINLINE which Go's net package does not expose; this should not affect normal TCP operation.

func (*Slirp) TCPSlowtimo

func (slirp *Slirp) TCPSlowtimo()

TCPSlowtimo is the TCP protocol timeout routine called every 500 ms. Updates the timers in all active tcb's and causes finite state machine actions if timers expire. Reference: tinyemu-2019-12-21/slirp/tcp_timer.c:64-101

func (*Slirp) UDPAttach

func (s *Slirp) UDPAttach(so *Socket) int

UDPAttach attaches a UDP socket to the system. Returns the socket fd on success, -1 on error. Reference: tinyemu-2019-12-21/slirp/udp.c:305-312

func (*Slirp) UDPDetach

func (s *Slirp) UDPDetach(so *Socket)

UDPDetach detaches a UDP socket. Reference: tinyemu-2019-12-21/slirp/udp.c:315-319

func (*Slirp) UDPInit

func (s *Slirp) UDPInit()

UDPInit initializes UDP state. This is called from NewSlirp. Reference: tinyemu-2019-12-21/slirp/udp.c:47-51

func (*Slirp) UDPInput

func (s *Slirp) UDPInput(m *Mbuf, iphlen int)

UDPInput processes an incoming UDP packet. m.Data points at IP packet header, m.Len is the length of the IP packet. Reference: tinyemu-2019-12-21/slirp/udp.c:57-226

func (*Slirp) UDPListen

func (s *Slirp) UDPListen(haddr net.IP, hport uint16, laddr net.IP, lport uint16, flags int) *Socket

UDPListen creates a UDP socket for port forwarding. Returns the socket on success, nil on error. Reference: tinyemu-2019-12-21/slirp/udp.c:344-386

func (*Slirp) UDPOutput

func (s *Slirp) UDPOutput(so *Socket, m *Mbuf, addr *SockaddrIn) int

UDPOutput sends a UDP datagram from a socket. Reference: tinyemu-2019-12-21/slirp/udp.c:279-302

func (*Slirp) UDPOutput2

func (s *Slirp) UDPOutput2(so *Socket, m *Mbuf, saddr, daddr *SockaddrIn, iptos int) int

UDPOutput2 sends a UDP datagram with specified source and destination. Reference: tinyemu-2019-12-21/slirp/udp.c:228-277

type SlirpConfig

type SlirpConfig struct {
	// Network is the virtual network address (default: 10.0.2.0)
	Network net.IP
	// Netmask is the virtual network mask (default: 255.255.255.0)
	Netmask net.IP
	// Host is the virtual host/gateway address (default: 10.0.2.2)
	Host net.IP
	// DHCPStart is the DHCP start address (default: 10.0.2.15)
	DHCPStart net.IP
	// DNS is the virtual DNS server address (default: 10.0.2.3)
	DNS net.IP
	// Restricted limits network access if true
	Restricted bool
}

SlirpConfig holds configuration for creating a Slirp-backed network device.

type SockaddrIn

type SockaddrIn struct {
	Addr net.IP
	Port uint16
}

SockaddrIn represents a socket address for UDP output. Reference: tinyemu-2019-12-21/slirp/slirp.h struct sockaddr_in

type Socket

type Socket struct {
	Next *Socket // next socket in list
	Prev *Socket // previous socket in list

	S int // the actual socket fd

	Slirp *Slirp // managing slirp instance

	SoM  *Mbuf  // pointer to the original SYN packet or PING reply
	SoTi []byte // pointer to original ti (for non-blocking connections)

	SoUrgc int // urgent data count

	SoFAddr net.IP // foreign host address
	SoLAddr net.IP // local host address
	SoFPort uint16 // foreign port
	SoLPort uint16 // local port

	SoIPTos uint8 // type of service
	SoEmu   uint8 // is the socket emulated?
	SoType  uint8 // type of socket (TCP or UDP)
	SoState int   // internal state flags

	SoTCPCB  interface{} // pointer to TCP protocol control block (tcpcb)
	SoExpire uint32      // when the socket will expire

	SoQueued  int // number of packets queued from this socket
	SoNQueued int // number of packets queued in a row

	// Send/receive buffers
	// Reference: tinyemu-2019-12-21/slirp/socket.h:51-52
	SoRcv SBuf
	SoSnd SBuf

	Extra interface{} // extra pointer
}

Socket represents a network socket. Reference: tinyemu-2019-12-21/slirp/socket.h:18-54

func SoLookup

func SoLookup(head *Socket, laddr net.IP, lport uint16, faddr net.IP, fport uint16) *Socket

SoLookup looks up a socket in a list by local and foreign address/port. Reference: tinyemu-2019-12-21/slirp/socket.c:15-32

func (*Socket) SbAppend

func (so *Socket) SbAppend(m *Mbuf)

SbAppend writes data to a socket. It tries to send immediately if the buffer is empty, then buffers any remainder. Reference: tinyemu-2019-12-21/slirp/sbuf.c:64-117

func (*Socket) SoFWDrain

func (so *Socket) SoFWDrain()

SoFWDrain sets write drain mode. Reference: tinyemu-2019-12-21/slirp/socket.c:716-722

func (*Socket) SoFree

func (so *Socket) SoFree()

SoFree frees a socket and removes it from any queues. Reference: tinyemu-2019-12-21/slirp/socket.c:58-77

func (*Socket) SoPrepRbuf

func (so *Socket) SoPrepRbuf() (iov [2][]byte, n int, total int)

SoPrepRbuf prepares the iovec for reading into the socket send buffer. Returns the total number of bytes that can be read. Reference: tinyemu-2019-12-21/slirp/socket.c:79-136

func (*Socket) SoRead

func (so *Socket) SoRead() int

SoRead reads from the socket fd into the send buffer. Returns bytes read, or -1 on disconnect, 0 on would-block. Reference: tinyemu-2019-12-21/slirp/socket.c:144-202

func (*Socket) SoReadBuf

func (so *Socket) SoReadBuf(buf []byte) int

SoReadBuf reads data from a buffer into the socket send buffer. Returns bytes read, or -1 on error. Reference: tinyemu-2019-12-21/slirp/socket.c:204-244

func (*Socket) SoRecvFrom

func (so *Socket) SoRecvFrom()

SoRecvFrom receives data from a UDP socket. Reference: tinyemu-2019-12-21/slirp/socket.c:431-526

func (*Socket) SoRecvOOB

func (so *Socket) SoRecvOOB()

SoRecvOOB receives out-of-band (urgent) data. Reference: tinyemu-2019-12-21/slirp/socket.c:254-274

func (*Socket) SoSendOOB

func (so *Socket) SoSendOOB() int

SoSendOOB sends urgent out-of-band data. Reference: tinyemu-2019-12-21/slirp/socket.c:281-332

func (*Socket) SoSendTo

func (so *Socket) SoSendTo(m *Mbuf) int

SoSendTo sends data to a UDP socket destination. Reference: tinyemu-2019-12-21/slirp/socket.c:532-573

func (*Socket) SoWrite

func (so *Socket) SoWrite() int

SoWrite writes data from so_rcv to the socket. Returns bytes written, -1 on error, 0 on would-block. Reference: tinyemu-2019-12-21/slirp/socket.c:339-425

type TCPCB

type TCPCB struct {
	// Reassembly queue head (sentinel for circular doubly-linked list)
	// Reference: tinyemu-2019-12-21/slirp/tcp_var.h:43-44
	// In C, seg_next/seg_prev point to tcpiphdr structs and the tcpcb itself
	// acts as the sentinel. In Go, we use an embedded TCPIPHdr as the sentinel.
	// When empty: ReassemblyHead.Next == &ReassemblyHead
	ReassemblyHead TCPIPHdr

	TState    int16              // state of this connection
	TTimer    [TCPTNTimers]int16 // tcp timers
	TRxtShift int16              // log(2) of rexmt exp. backoff
	TRxtCur   int16              // current retransmit value
	TDupAcks  int16              // consecutive dup acks recd
	TMaxSeg   uint16             // maximum segment size
	TForce    int8               // 1 if forcing out a byte
	TFlags    uint16             // flags (TF_*)

	TTemplate TCPIPHdr // static skeletal packet for xmit

	TSocket *Socket // back pointer to socket

	// Send sequence variables (RFC 783)
	SndUna uint32 // send unacknowledged
	SndNxt uint32 // send next
	SndUp  uint32 // send urgent pointer
	SndWL1 uint32 // window update seg seq number
	SndWL2 uint32 // window update seg ack number
	Iss    uint32 // initial send sequence number
	SndWnd uint32 // send window

	// Receive sequence variables
	RcvWnd uint32 // receive window
	RcvNxt uint32 // receive next
	RcvUp  uint32 // receive urgent pointer
	Irs    uint32 // initial receive sequence number

	// Additional variables for this implementation
	RcvAdv uint32 // advertised window
	SndMax uint32 // highest sequence number sent

	// Congestion control
	SndCwnd     uint32 // congestion-controlled window
	SndSsthresh uint32 // snd_cwnd size threshold for slow start

	// Transmit timing
	TIdle     int16  // inactivity time
	TRtt      int16  // round trip time
	TRtSeq    uint32 // sequence number being timed
	TSrtt     int16  // smoothed round-trip time
	TRttVar   int16  // variance in round-trip time
	TRttMin   uint16 // minimum rtt allowed
	MaxSndWnd uint32 // largest window peer has offered

	// Out-of-band data
	TOobFlags int8 // have some
	TIobc     int8 // input character

	TSoftError int16 // possible error not yet reported

	// RFC 1323 variables
	SndScale        uint8  // window scaling for send window
	RcvScale        uint8  // window scaling for recv window
	RequestRScale   uint8  // pending window scaling
	RequestedSScale uint8  // requested scale
	TsRecent        uint32 // timestamp echo data
	TsRecentAge     uint32 // when last updated
	LastAckSent     uint32 // last ack sent
}

TCPCB is the TCP control block, one per TCP connection. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:42-127

func SoToTCPCB

func SoToTCPCB(so *Socket) *TCPCB

SoToTCPCB returns the TCPCB associated with a socket. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:129

func (*TCPCB) TCPCancelTimers

func (tp *TCPCB) TCPCancelTimers()

TCPCancelTimers cancels all timers for a TCP connection. Reference: tinyemu-2019-12-21/slirp/tcp_timer.c:106-113

func (*TCPCB) TCPClose

func (tp *TCPCB) TCPClose() *TCPCB

TCPClose closes a TCP connection. Reference: tinyemu-2019-12-21/slirp/tcp_subr.c:236-265

func (*TCPCB) TCPDrop

func (tp *TCPCB) TCPDrop(errno int) *TCPCB

TCPDrop drops a TCP connection, reporting the specified error. If connection is synchronized, send a RST to peer. Reference: tinyemu-2019-12-21/slirp/tcp_subr.c:217-228

func (*TCPCB) TCPOutput

func (tp *TCPCB) TCPOutput() int

TCPOutput sends TCP output for a connection. This is the main TCP output routine that figures out what should be sent and sends it. Reference: tinyemu-2019-12-21/slirp/tcp_output.c:56-477

func (*TCPCB) TCPRespond

func (tp *TCPCB) TCPRespond(m *Mbuf, ack, seq uint32, flags int)

TCPRespond sends a TCP response. Reference: tinyemu-2019-12-21/slirp/tcp_subr.c:103

func (*TCPCB) TCPRexmtVal

func (tp *TCPCB) TCPRexmtVal() int16

TCPRexmtVal calculates the retransmission value. Reference: tinyemu-2019-12-21/slirp/tcp_var.h:158-159

func (*TCPCB) TCPSetPersist

func (tp *TCPCB) TCPSetPersist()

TCPSetPersist sets the persist timer. Reference: tinyemu-2019-12-21/slirp/tcp_output.c:479-492

type TCPIPHdr

type TCPIPHdr struct {
	// Reassembly queue linkage (for tcp_reass)
	// Reference: tinyemu-2019-12-21/slirp/tcpip.h:60-66
	Next *TCPIPHdr // next segment in reassembly queue
	Prev *TCPIPHdr // previous segment in reassembly queue

	// Overlaid IP header fields
	Mbuf *Mbuf  // back pointer to mbuf
	X1   uint8  // unused
	Pr   uint8  // protocol
	Len  uint16 // length (IP header ti_len, not TCP segment length)
	Src  uint32 // source address
	Dst  uint32 // destination address

	// TCP header fields
	Sport uint16 // source port
	Dport uint16 // destination port
	Seq   uint32 // sequence number
	Ack   uint32 // acknowledgment number
	OffX2 uint8  // data offset (upper 4 bits) + reserved
	Flags uint8  // flags
	Win   uint16 // window
	Sum   uint16 // checksum
	Urp   uint16 // urgent pointer

	// TCP segment data length (for reassembly)
	// Reference: tinyemu-2019-12-21/slirp/tcpip.h:46 (ti_len via ih_len)
	TiLen int // segment data length (not including headers)
}

TCPIPHdr represents a combined TCP/IP header. Reference: tinyemu-2019-12-21/slirp/tcpip.h:39-42

type Tracer

type Tracer interface {
	// Trace logs a trace message with the given format and arguments.
	Trace(format string, args ...interface{})
}

Tracer is an interface for trace output.

var DefaultTracer Tracer

DefaultTracer is the default tracer used for new Slirp instances. Set this before creating Slirp instances to enable tracing globally.

type WriterTracer

type WriterTracer struct {
	Writer io.Writer
	Prefix string
}

WriterTracer is a Tracer that writes to an io.Writer.

func StderrTracer

func StderrTracer() *WriterTracer

StderrTracer returns a tracer that writes to stderr.

func (*WriterTracer) Trace

func (t *WriterTracer) Trace(format string, args ...interface{})

Trace implements Tracer.

Jump to

Keyboard shortcuts

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