-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
IP+UDP Stack over Ethernet for DHCP #17
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
8f1d401
fix IP marshal bugs, begin adding DHCP
soypat 009c067
add tcpctl.Stack type
soypat 86deee4
fix bug in IP marshal and add test to catch it
soypat f298641
continue trying to add DHCP
soypat 24d69c6
add some more form to DoDHCP
soypat 8a3e448
move DHCPHeader to eth package
soypat 0dae965
push work up until now. packets are malformed but it's what we got so…
soypat a55e9a5
latest changes
soypat 349134b
remove useless operation
soypat d61a552
DHCP seems to be well formed now. still no response
soypat 37eed6a
add more idiomatic dhcp option encoding
soypat 244760c
fix bugs in checksum; also length calculation
soypat 625c9e4
printing DHCP responses works!
soypat 1fca2da
add extra check in rxEvent
soypat 20c23ce
stack needs API redesign by the looks of it, good exploration though
soypat e239b85
huge refactor to DHCP stack; much nicer inner workings
soypat 3fee8bd
add DHCP option parsing
soypat 936741f
redo DHCP request after 8 seconds
soypat bfa9eb4
add pretty printing of DHCP options
soypat 6903078
DHCP is working with my test setup
soypat 407ce19
Merge branch 'main' into dhcp
soypat 639421a
add tcp sockets (#19)
soypat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
package tcpctl | ||
|
||
import ( | ||
"encoding/binary" | ||
"errors" | ||
"fmt" | ||
"net" | ||
|
||
"github.com/soypat/cyw43439/internal/tcpctl/eth" | ||
) | ||
|
||
type DHCPClient struct { | ||
ourHeader eth.DHCPHeader | ||
State uint8 | ||
MAC [6]byte | ||
// The result IP of the DHCP transaction (our new IP). | ||
YourIP [4]byte | ||
// DHCP server IP | ||
ServerIP [4]byte | ||
} | ||
|
||
const ( | ||
dhcpStateNone = iota | ||
dhcpStateWaitOffer | ||
dhcpStateWaitAck | ||
dhcpStateDone | ||
) | ||
|
||
func (d *DHCPClient) HandleUDP(resp []byte, packet *UDPPacket) (_ int, err error) { | ||
const ( | ||
xid = 0x12345678 | ||
|
||
sizeSName = 64 // Server name, part of BOOTP too. | ||
sizeFILE = 128 // Boot file name, Legacy. | ||
sizeOptions = 312 | ||
dhcpOffset = eth.SizeEthernetHeader + eth.SizeIPv4Header + eth.SizeUDPHeader | ||
optionsStart = dhcpOffset + eth.SizeDHCPHeader + sizeSName + sizeFILE | ||
sizeDHCPTotal = eth.SizeDHCPHeader + sizeSName + sizeFILE + sizeOptions | ||
) | ||
// First action is used to send data without having received a packet | ||
// so hasPacket will be false. | ||
hasPacket := packet.HasPacket() | ||
incpayload := packet.Payload() | ||
switch { | ||
case len(resp) < sizeDHCPTotal: | ||
return 0, errors.New("short payload to marshall DHCP") | ||
case hasPacket && len(incpayload) < eth.SizeDHCPHeader: | ||
return 0, errors.New("short payload to parse DHCP") | ||
} | ||
|
||
var rcvHdr eth.DHCPHeader | ||
if hasPacket { | ||
rcvHdr = eth.DecodeDHCPHeader(incpayload) | ||
ptr := eth.SizeDHCPHeader + sizeSName + sizeFILE + 4 | ||
for ptr+1 < len(incpayload) && int(incpayload[ptr+1]) < len(incpayload) { | ||
if incpayload[ptr] == 0xff { | ||
break | ||
} | ||
option := eth.DHCPOption(incpayload[ptr]) | ||
optlen := incpayload[ptr+1] | ||
// optionData := incpayload[ptr+2 : ptr+2+int(optlen)] | ||
|
||
// print("DHCP Option received ", option.String()) | ||
optionData := incpayload[ptr+2 : ptr+2+int(optlen)] | ||
if d.State == dhcpStateWaitAck && option == eth.DHCP_MessageType && len(optionData) > 0 && optionData[0] == 5 { | ||
d.State = dhcpStateDone | ||
return 0, nil | ||
} | ||
println() | ||
ptr += int(optlen) + 2 | ||
} | ||
} | ||
|
||
// Switch statement prepares DHCP response depending on whether we're waiting | ||
// for offer, ack or if we still need to send a discover (StateNone). | ||
type option struct { | ||
code byte | ||
data []byte | ||
} | ||
var Options []option | ||
switch { | ||
case !hasPacket && d.State == dhcpStateNone: | ||
d.initOurHeader(xid) | ||
// DHCP options. | ||
Options = []option{ | ||
{53, []byte{1}}, // DHCP Message Type: Discover | ||
{50, []byte{192, 168, 1, 69}}, // Requested IP | ||
{55, []byte{1, 3, 15, 6}}, // Parameter request list | ||
} | ||
d.State = dhcpStateWaitOffer | ||
|
||
case hasPacket && d.State == dhcpStateWaitOffer: | ||
offer := net.IP(rcvHdr.YIAddr[:]) | ||
Options = []option{ | ||
{53, []byte{3}}, // DHCP Message Type: Request | ||
{50, offer}, // Requested IP | ||
{54, rcvHdr.SIAddr[:]}, // DHCP server IP | ||
} | ||
// Accept this server's offer. | ||
copy(d.ourHeader.SIAddr[:], rcvHdr.SIAddr[:]) | ||
copy(d.YourIP[:], offer) // Store our new IP. | ||
d.State = dhcpStateWaitAck | ||
default: | ||
err = fmt.Errorf("UNHANDLED CASE %v %+v", hasPacket, d) | ||
} | ||
if err != nil { | ||
return 0, nil | ||
} | ||
for i := dhcpOffset + 14; i < len(resp); i++ { | ||
resp[i] = 0 // Zero out BOOTP and options fields. | ||
} | ||
// Encode DHCP header + options. | ||
d.ourHeader.Put(resp[dhcpOffset:]) | ||
|
||
ptr := optionsStart | ||
binary.BigEndian.PutUint32(resp[ptr:], 0x63825363) // Magic cookie. | ||
ptr += 4 | ||
for _, opt := range Options { | ||
ptr += encodeDHCPOption(resp[ptr:], opt.code, opt.data) | ||
} | ||
resp[ptr] = 0xff // endmark | ||
// Set Ethernet+IP+UDP headers. | ||
payload := resp[dhcpOffset : dhcpOffset+sizeDHCPTotal] | ||
d.setResponseUDP(packet, payload) | ||
packet.PutHeaders(resp) | ||
return dhcpOffset + sizeDHCPTotal, nil | ||
} | ||
|
||
// initOurHeader zero's out most of header and sets the xid and MAC address along with OP=1. | ||
func (d *DHCPClient) initOurHeader(xid uint32) { | ||
dhdr := &d.ourHeader | ||
dhdr.OP = 1 | ||
dhdr.HType = 1 | ||
dhdr.HLen = 6 | ||
dhdr.HOps = 0 | ||
dhdr.Secs = 0 | ||
dhdr.Flags = 0 | ||
dhdr.Xid = xid | ||
dhdr.CIAddr = [4]byte{} | ||
dhdr.YIAddr = [4]byte{} | ||
dhdr.SIAddr = [4]byte{} | ||
dhdr.GIAddr = [4]byte{} | ||
copy(dhdr.CHAddr[:], d.MAC[:]) | ||
} | ||
|
||
func (d *DHCPClient) setResponseUDP(packet *UDPPacket, payload []byte) { | ||
const ipWordLen = 5 | ||
// Ethernet frame. | ||
copy(packet.Eth.Destination[:], eth.BroadcastHW()) | ||
copy(packet.Eth.Source[:], d.MAC[:]) | ||
packet.Eth.SizeOrEtherType = uint16(eth.EtherTypeIPv4) | ||
|
||
// IPv4 frame. | ||
copy(packet.IP.Destination[:], eth.BroadcastHW()) | ||
packet.IP.Source = [4]byte{} // Source IP is always zeroed when client sends. | ||
packet.IP.Protocol = 17 // UDP | ||
packet.IP.TTL = 64 | ||
// 16bit Xorshift for prandom IP packet ID. https://en.wikipedia.org/wiki/Xorshift | ||
packet.IP.ID ^= packet.IP.ID << 7 | ||
packet.IP.ID ^= packet.IP.ID >> 9 | ||
packet.IP.ID ^= packet.IP.ID << 8 | ||
packet.IP.VersionAndIHL = ipWordLen // Sets IHL: No IP options. Version set automatically. | ||
packet.IP.TotalLength = 4*ipWordLen + eth.SizeUDPHeader + uint16(len(payload)) | ||
packet.IP.Checksum = packet.IP.CalculateChecksum() | ||
|
||
// UDP frame. | ||
packet.UDP.DestinationPort = 67 | ||
packet.UDP.SourcePort = 68 | ||
packet.UDP.Length = packet.IP.TotalLength - 4*ipWordLen | ||
packet.UDP.Checksum = packet.UDP.CalculateChecksumIPv4(&packet.IP, payload) | ||
} | ||
|
||
func encodeDHCPOption(dst []byte, code byte, data []byte) int { | ||
if len(data)+2 > len(dst) { | ||
panic("small dst size for DHCP encoding") | ||
} | ||
dst[0] = code | ||
dst[1] = byte(len(data)) | ||
copy(dst[2:], data) | ||
return 2 + len(data) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This check is redundant with DecodeEventPacket()