Skip to content

Commit

Permalink
add TCP keepalive: TCB methods for detecting and creating TCP keepali…
Browse files Browse the repository at this point in the history
…ves; fix TCPConn.Close bug that would make an unopened connection enter FinWait1 forever until opened
  • Loading branch information
soypat committed May 9, 2024
1 parent d1b5854 commit ff83b37
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
20 changes: 20 additions & 0 deletions control_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,3 +251,23 @@ func (tcb *ControlBlock) SetRecvWindow(wnd Size) {
func (tcb *ControlBlock) SetLogger(log *slog.Logger) {
tcb.log = log
}

// IncomingIsKeepalive checks if an incoming segment is a keepalive segment.
// Segments which are keepalives should not be passed into Recv or Send methods.
func (tcb *ControlBlock) IncomingIsKeepalive(incomingSegment Segment) bool {
return incomingSegment.SEQ == tcb.rcv.NXT-1 &&
incomingSegment.Flags == FlagACK &&
incomingSegment.ACK == tcb.snd.NXT && incomingSegment.DATALEN == 0
}

// MakeKeepalive creates a TCP keepalive segment. This segment
// should not be passed into Recv or Send methods.
func (tcb *ControlBlock) MakeKeepalive() Segment {
return Segment{
SEQ: tcb.snd.NXT - 1,
ACK: tcb.rcv.NXT,
Flags: FlagACK,
WND: tcb.rcv.WND,
DATALEN: 0,
}
}
7 changes: 5 additions & 2 deletions stacks/tcpconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,13 +300,13 @@ func (sock *TCPConn) open(state seqs.State, localPortNum uint16, iss seqs.Value,

func (sock *TCPConn) Close() error {
toSend := sock.tx.Buffered()
sock.closing = true
if toSend == 0 {
err := sock.scb.Close()
if err != nil {
return err
}
}
sock.closing = true
sock.stack.FlagPendingTCP(sock.localPort)
return nil
}
Expand Down Expand Up @@ -342,7 +342,10 @@ func (sock *TCPConn) recv(pkt *TCPPacket) (err error) {
// By this point we know that the packet is valid and contains data, we process it.
payload := pkt.Payload()
segIncoming := pkt.TCP.Segment(len(payload))

if sock.scb.IncomingIsKeepalive(segIncoming) {
sock.trace("TCPConn.recv:keepalive")
return nil
}
err = sock.scb.Recv(segIncoming)
if err != nil {
if sock.scb.State() == seqs.StateClosed {
Expand Down

0 comments on commit ff83b37

Please sign in to comment.