clean up tcp package; add Abort method

This commit is contained in:
soypat
2025-02-24 09:25:55 -03:00
parent d996040d92
commit d04d287ab6
6 changed files with 139 additions and 68 deletions
+56 -41
View File
@@ -56,40 +56,39 @@ func main() {
if err != nil {
log.Fatal(err)
}
tap := NewHTTPTap("http://127.0.0.1:7070")
// tap, err := internal.NewTap("tap0", iface)
if err != nil {
log.Fatal(err)
}
defer tap.Close()
fmt.Println("hosting server at ", addrPort.String())
var buf [mtu]byte
for {
n, err := tap.Read(buf[:])
nread, err := tap.Read(buf[:])
if err != nil {
slogger.error("tap-err", slog.String("err", err.Error()))
log.Fatal(err)
} else if n > 0 {
err = lStack.RecvEth(buf[:n])
} else if nread > 0 {
err = lStack.RecvEth(buf[:nread])
if err != nil {
slogger.error("recv", slog.String("err", err.Error()), slog.Int("plen", n))
slogger.error("recv", slog.String("err", err.Error()), slog.Int("plen", nread))
} else {
slogger.info("recv", slog.Int("plen", n))
slogger.info("recv", slog.Int("plen", nread))
}
} else if n == 0 {
time.Sleep(250 * time.Millisecond)
}
n, err = lStack.HandleEth(buf[:])
nw, err := lStack.HandleEth(buf[:])
if err != nil {
slogger.error("handle", slog.String("err", err.Error()))
} else if n > 0 {
_, err = tap.Write(buf[:n])
} else if nw > 0 {
_, err = tap.Write(buf[:nw])
if err != nil {
log.Fatal(err)
} else {
slogger.info("write", slog.Int("plen", n))
slogger.info("write", slog.Int("plen", nw))
}
}
if nread == 0 && nw == 0 {
time.Sleep(5 * time.Millisecond)
}
}
}
@@ -337,6 +336,10 @@ func (is *IPv4Stack) Handle(ethFrame []byte, ipOff int) (int, error) {
ifrm.SetFlags(dontFrag)
ifrm.SetTTL(64)
ifrm.SetCRC(ifrm.CalculateHeaderCRC())
if ifrm.Protocol() == lneto2.IPProtoTCP {
tfrm, _ := tcp.NewFrame(ifrm.Payload())
is.info("IPv4Stack:send", slog.String("ip", ifrm.String()), slog.String("tcp", tfrm.String()))
}
return totalLen, nil
}
}
@@ -347,7 +350,6 @@ type TCPStack struct {
validator lneto2.Validator
handlers []handler
logger
crc lneto2.CRC791
}
func (ts *TCPStack) Protocol() uint32 { return uint32(lneto2.IPProtoTCP) }
@@ -389,20 +391,9 @@ func (ts *TCPStack) Recv(ipFrame []byte, tcpOff int) error {
if err = ts.validator.Err(); err != nil {
return err
}
ts.crc.Reset()
switch ipVersion {
case 4:
ifrm, _ := ipv4.NewFrame(ipFrame)
ifrm.CRCWriteTCPPseudo(&ts.crc)
ts.log.Info("tcpStack:recv", slog.String("ipfrm", ifrm.String()), slog.String("frame", tfrm.String()))
case 6:
i6frm, _ := ipv6.NewFrame(ipFrame)
i6frm.CRCWritePseudo(&ts.crc)
}
tfrm.CRCWrite(&ts.crc)
crc := ts.crc.Sum16()
crc := tcpChecksum(ipFrame, len(tfrm.RawData()))
gotCRC := tfrm.CRC()
if ts.crc.Sum16() != gotCRC {
if crc != gotCRC {
ts.error("TCPStack:Recv:crc-mismatch", slog.Uint64("lport", uint64(lport)), slog.Uint64("want", uint64(crc)), slog.Uint64("got", uint64(gotCRC)))
return errors.New("TCP crc mismatch")
}
@@ -428,6 +419,7 @@ func (ts *TCPStack) Handle(ipFrame []byte, tcpOff int) (n int, err error) {
}
}
if n > 0 {
ipFrame = ipFrame[:tcpOff+n]
break
}
}
@@ -435,24 +427,14 @@ func (ts *TCPStack) Handle(ipFrame []byte, tcpOff int) (n int, err error) {
return 0, err
}
// TCP packet written.
tfrm, _ := tcp.NewFrame(ipFrame[tcpOff : tcpOff+n])
tfrm, _ := tcp.NewFrame(ipFrame[tcpOff:])
ts.validator.ResetErr()
tfrm.ValidateSize(&ts.validator) // Perform basic validation.
if err = ts.validator.Err(); err != nil {
return 0, err
}
ts.crc.Reset()
switch ipVersion {
case 4:
ifrm, _ := ipv4.NewFrame(ipFrame)
ifrm.CRCWriteTCPPseudo(&ts.crc)
ts.log.Info("tcpStack:send", slog.String("ipfrm", ifrm.String()), slog.String("frame", tfrm.String()))
case 6:
i6frm, _ := ipv6.NewFrame(ipFrame)
i6frm.CRCWritePseudo(&ts.crc)
}
crc := ts.crc.Sum16()
crc := tcpChecksum(ipFrame, n)
tfrm.SetCRC(crc)
return n, nil
}
@@ -554,6 +536,12 @@ func NewHTTPTap(baseURL string) *HTTPTap {
return &h
}
type TAPNop struct{}
func (h *TAPNop) Read(b []byte) (int, error) { return 0, nil }
func (h *TAPNop) Write(b []byte) (int, error) { return 0, nil }
func (h *TAPNop) Close() error { return nil }
type HTTPTap struct {
c http.Client
recvurl string
@@ -590,3 +578,30 @@ func (h *HTTPTap) Write(b []byte) (int, error) {
}
func (h *HTTPTap) Close() error { return nil }
func tcpChecksum(ipFrame []byte, tcpPayload int) uint16 {
version := ipFrame[0] >> 4
var tfrm tcp.Frame
var crc lneto2.CRC791
switch version {
case 4:
ifrm, _ := ipv4.NewFrame(ipFrame)
crc.Write(ifrm.SourceAddr()[:])
crc.Write(ifrm.DestinationAddr()[:])
crc.AddUint16(uint16(tcpPayload))
crc.AddUint16(6)
tfrm, _ = tcp.NewFrame(ifrm.Payload())
case 6:
i6frm, _ := ipv6.NewFrame(ipFrame)
crc.Write(i6frm.SourceAddr()[:])
crc.Write(i6frm.DestinationAddr()[:])
crc.AddUint32(uint32(tcpPayload))
crc.AddUint32(6)
i6frm.CRCWritePseudo(&crc)
tfrm, _ = tcp.NewFrame(i6frm.Payload())
default:
panic("invalid IP version")
}
tfrm.CRCWrite(&crc)
return crc.Sum16()
}
+41
View File
@@ -0,0 +1,41 @@
package main
import (
"testing"
"github.com/soypat/lneto/ethernet"
"github.com/soypat/lneto/ipv4"
"github.com/soypat/lneto/tcp"
)
func TestChecksum(t *testing.T) {
for _, epacket := range ethpackets {
efrm, _ := ethernet.NewFrame(epacket)
ifrm, _ := ipv4.NewFrame(efrm.Payload())
ipPayload := ifrm.Payload()
tfrm, _ := tcp.NewFrame(ipPayload)
crc := tcpChecksum(ifrm.RawData(), len(ipPayload))
wantCRC := tfrm.CRC()
if crc != wantCRC {
t.Fatalf("crc mismatch, got %x, want %x", crc, wantCRC)
}
}
}
var ethpackets = [][]byte{
{
0xc0, 0xff, 0xee, 0x00, 0xde, 0xad, 0x3a, 0xd1, 0x6d, 0x82, 0x6b, 0x1a, 0x08, 0x00, 0x45, 0x00,
0x00, 0x3c, 0xe3, 0xc6, 0x40, 0x00, 0x40, 0x06, 0xc1, 0xa1, 0xc0, 0xa8, 0x0a, 0x01, 0xc0, 0xa8,
0x0a, 0x02, 0xd5, 0x70, 0x00, 0x50, 0xc4, 0x10, 0x30, 0x49, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x02,
0xfa, 0xf0, 0x2c, 0x80, 0x00, 0x00, 0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0xe8, 0x22,
0xd8, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x07,
},
{
0xc0, 0xff, 0xee, 0x00, 0xde, 0xad, 0xc0, 0xff, 0xee, 0x00, 0xde, 0xad, 0x08, 0x00, 0x45, 0x00,
0x00, 0x28, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0x70, 0x26, 0xc0, 0xa8, 0x0a, 0x02, 0x00, 0x00,
0x00, 0x00, 0x00, 0x50, 0xa5, 0xb8, 0x00, 0x00, 0x00, 0x64, 0x2f, 0x46, 0x4c, 0xe5, 0x50, 0x12,
0x08, 0x00, 0xBA, 0x90, 0x00, 0x00,
},
}
+1 -1
View File
@@ -1,3 +1,3 @@
module github.com/soypat/lneto
go 1.20
go 1.21
+25 -22
View File
@@ -153,17 +153,18 @@ func (tcb *ControlBlock) Open(iss Value, wnd Size) (err error) {
tcb.logerr("tcb:open", slog.String("err", err.Error()))
return err
}
tcb._state = StateListen
tcb.prepareToHandshake(iss, wnd)
tcb.prepareToHandshake(iss, wnd, StateListen)
tcb.trace("tcb:open-server")
return nil
}
// prepareToHandshake initializes the TCB send/receive spaces with initial send sequence number and local window.
func (tcb *ControlBlock) prepareToHandshake(iss Value, wnd Size) {
func (tcb *ControlBlock) prepareToHandshake(iss Value, wnd Size, newState State) {
tcb.reset()
tcb.resetRcv(wnd, 0)
tcb.resetSnd(iss, 1)
tcb.pending = [2]Flags{}
tcb._state = newState
}
// HasPending returns true if there is a pending control segment to send. Calls to Send will advance the pending queue.
@@ -256,7 +257,7 @@ func (tcb *ControlBlock) Recv(seg Segment) (err error) {
case StateCloseWait:
case StateLastAck:
if seg.Flags.HasAny(FlagACK) {
tcb.close()
tcb.Abort()
}
case StateClosing:
// Thanks to @knieriem for finding and reporting this bug.
@@ -309,11 +310,10 @@ func (tcb *ControlBlock) Send(seg Segment) error {
switch tcb._state {
case StateClosed:
if seg.Flags == FlagSYN {
tcb._state = StateSynSent
tcb.prepareToHandshake(seg.SEQ, seg.WND)
tcb.prepareToHandshake(seg.SEQ, seg.WND, StateSynSent)
tcb.trace("tcb:open-client")
}
case StateSynRcvd:
case StateSynRcvd, StateEstablished:
if hasFIN {
tcb._state = StateFinWait1 // RFC 9293: 3.10.4 CLOSE call.
}
@@ -321,10 +321,6 @@ func (tcb *ControlBlock) Send(seg Segment) error {
if hasACK {
tcb._state = StateTimeWait
}
case StateEstablished:
if hasFIN {
tcb._state = StateFinWait1
}
case StateCloseWait:
if hasFIN {
tcb._state = StateLastAck
@@ -494,7 +490,7 @@ func (tcb *ControlBlock) handleRST(seq Value) error {
tcb.resetSnd(tcb.snd.ISS+tcb.rstJump(), tcb.snd.WND)
tcb.resetRcv(tcb.rcv.WND, 3_14159_2653^tcb.rcv.IRS)
} else {
tcb.close() // Enter closed state and return.
tcb.Abort() // Enter closed state and return.
return net.ErrClosed
}
return errDropSegment
@@ -504,13 +500,17 @@ func (tcb *ControlBlock) rstJump() Value {
return 100
}
// close sets ControlBlock state to closed and resets all sequence numbers and pending flag.
func (tcb *ControlBlock) close() {
tcb._state = StateClosed
tcb.pending = [2]Flags{}
tcb.resetRcv(0, 0)
tcb.resetSnd(0, 0)
tcb.debug("tcb:close")
// Abort sets ControlBlock state to Closed and resets all sequence numbers and pending flag.
// No more data can be sent nor received after the connection is aborted until opened again.
func (tcb *ControlBlock) Abort() {
tcb.reset()
tcb.debug("tcb:abort")
}
func (tcb *ControlBlock) reset() {
*tcb = ControlBlock{
logger: tcb.logger,
}
}
// Close implements a passive/active closing of a connection. It does not immediately
@@ -521,15 +521,18 @@ func (tcb *ControlBlock) Close() (err error) {
// See RFC 9293: 3.10.4 CLOSE call.
switch tcb._state {
case StateClosed:
err = errConnNotexist
err = errConnNotExist
case StateCloseWait:
tcb._state = StateLastAck
tcb.pending = [2]Flags{FlagFIN, FlagACK}
case StateListen, StateSynSent:
tcb.close()
// In Listen State there is no established connection.
// In SynSent the remote endpoint is not yet synchronized and upon receiving an RST will abort connection.
tcb.Abort()
case StateSynRcvd, StateEstablished:
// We suppose user has no more pending data to send, so we flag FIN to be sent.
// Users of this API should call Close only when they have no more data to send.
// When FIN is sent SCB will transition to FinWait1.
tcb.pending[0] = (tcb.pending[0] & FlagACK) | FlagFIN
case StateFinWait2, StateTimeWait:
err = errConnectionClosing
+15 -3
View File
@@ -19,7 +19,7 @@ var (
errBufferTooSmall = errors.New("buffer too small")
errNeedClosedTCBToOpen = errors.New("need closed TCB to call open")
errInvalidState = errors.New("invalid state")
errConnNotexist = errors.New("connection does not exist")
errConnNotExist = errors.New("connection does not exist")
errConnectionClosing = errors.New("connection closing")
errExpectedSYN = errors.New("seqs:expected SYN")
errBadSegack = errors.New("seqs:bad segack")
@@ -286,7 +286,7 @@ func (s State) IsPreestablished() bool {
// IsClosing returns true if the connection is in a closing state but not yet terminated (relieved of remote connection state).
// Returns false for Closed pseudo state.
func (s State) IsClosing() bool {
return !(s <= StateEstablished)
return s == StateFinWait1 || s == StateFinWait2 || s == StateClosing || s == StateLastAck || s == StateCloseWait
}
// IsClosed returns true if the connection closed and can possibly relieved of
@@ -297,7 +297,19 @@ func (s State) IsClosed() bool {
// IsSynchronized returns true if the connection has gone through the Established state.
func (s State) IsSynchronized() bool {
return s >= StateEstablished
return s >= StateEstablished && !s.IsClosed()
}
// txOpen returns true if the TCP state machine allows data to be sent by user.
func (s State) txOpen() bool {
// In CloseWait state the remote endpoint has closed
// our receive hald of the connection but we can still transmit indefinitely.
return s == StateEstablished || s == StateCloseWait
}
// rxOpen returns true if the TCP state machine allows data to be received from remote endpoint.
func (s State) rxOpen() bool {
return s == StateEstablished || s == StateFinWait1 || s == StateFinWait2
}
// IsDataOpen returns true if the connection allows sending and receiving of data.
+1 -1
View File
@@ -128,7 +128,7 @@ func (tfrm Frame) Payload() []byte {
// Segment returns the [Segment] representation of the TCP header and data length.
func (tfrm Frame) Segment(payloadSize int) Segment {
if payloadSize > math.MaxUint32 {
if payloadSize > math.MaxInt32 {
panic("TCP overflow payload size")
}
return Segment{