mirror of
https://github.com/soypat/lneto.git
synced 2026-09-08 07:49:05 +00:00
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 48de260013 | |||
| cf6b7e6201 | |||
| 2dda96b610 | |||
| 3eb1f39f1d | |||
| 07afcfd924 | |||
| d7f3924489 | |||
| d219daa2c4 | |||
| 75f1e02a20 | |||
| ab9d3ee691 | |||
| e6a5be3628 | |||
| 56f943ed30 | |||
| c879d0497c | |||
| 6313b1570d | |||
| 21f477b86e | |||
| 263b1ecf11 | |||
| ab91d08f41 |
@@ -1,3 +1,12 @@
|
|||||||
|
coverage:
|
||||||
|
status:
|
||||||
|
project:
|
||||||
|
default:
|
||||||
|
target: 62% # Ensure we don't accumulate too much debt.
|
||||||
|
patch:
|
||||||
|
default:
|
||||||
|
informational: true # Shows the patch metric but never turns red/fails the PR
|
||||||
|
|
||||||
ignore:
|
ignore:
|
||||||
- "examples/**"
|
- "examples/**"
|
||||||
- "**/stringers.go"
|
- "**/stringers.go"
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
name: Benchmark Comment
|
|
||||||
|
|
||||||
# Rationale: This more privileged workflow runs in the base repo's
|
|
||||||
# context (with a write token) only after the 'untrusted' CI workflow finishes.
|
|
||||||
# It does NOT check out or execute PR code; it only consumes the benchmark
|
|
||||||
# report artifact as inert, validated data.
|
|
||||||
on:
|
|
||||||
workflow_run:
|
|
||||||
workflows: [CI]
|
|
||||||
types: [completed]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
comment:
|
|
||||||
# Only for PR-triggered CI runs that succeeded to suppress noise
|
|
||||||
if: >
|
|
||||||
github.event.workflow_run.event == 'pull_request' &&
|
|
||||||
github.event.workflow_run.conclusion == 'success'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
pull-requests: write # needed to comment
|
|
||||||
steps:
|
|
||||||
- name: Download generated benchmark report
|
|
||||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.1
|
|
||||||
with:
|
|
||||||
name: bench-report
|
|
||||||
path: bench-report
|
|
||||||
run-id: ${{ github.event.workflow_run.id }}
|
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Validate report and upsert PR comment
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
REPO: ${{ github.repository }}
|
|
||||||
PR_NUMBER: ${{ github.event.workflow_run.pull_requests[0].number }}
|
|
||||||
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
|
|
||||||
HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }}
|
|
||||||
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
report="bench-report/bench-report.md"
|
|
||||||
marker='<!-- lneto-bench -->'
|
|
||||||
|
|
||||||
# Treat the artifact as untrusted input: it was produced by a job that
|
|
||||||
# ran PR code. Basic validation before posting. TODO: Make more robust.
|
|
||||||
test -f "$report"
|
|
||||||
size="$(wc -c < "$report")"
|
|
||||||
if [ "$size" -le 0 ] || [ "$size" -gt 1000000 ]; then
|
|
||||||
echo "::error::benchmark report has unexpected size: ${size} bytes"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
if ! grep -qF "$marker" "$report"; then
|
|
||||||
echo "::error::benchmark report missing marker ${marker}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Prefer the PR number from the workflow_run payload, which ties this
|
|
||||||
# privileged workflow to the PR-triggered CI run. Fall back to the
|
|
||||||
# run's head SHA/branch only when GitHub does not populate it.
|
|
||||||
pr="$PR_NUMBER"
|
|
||||||
if [ -z "$pr" ]; then
|
|
||||||
pr="$(gh api "repos/${REPO}/commits/${HEAD_SHA}/pulls" \
|
|
||||||
--jq 'map(select(.state == "open")) | .[0].number // empty')"
|
|
||||||
fi
|
|
||||||
if [ -z "$pr" ]; then
|
|
||||||
pr="$(gh api --method GET "repos/${REPO}/pulls" \
|
|
||||||
-f state=open \
|
|
||||||
-f head="${HEAD_OWNER}:${HEAD_BRANCH}" \
|
|
||||||
--jq '.[0].number // empty')"
|
|
||||||
fi
|
|
||||||
if [ -z "$pr" ]; then
|
|
||||||
echo "No open PR found for ${HEAD_SHA}; nothing to comment."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
comment_id="$(
|
|
||||||
gh api "repos/${REPO}/issues/${pr}/comments" --paginate \
|
|
||||||
--jq ".[] | select(.body | contains(\"${marker}\")) | .id" | head -n1
|
|
||||||
)"
|
|
||||||
if [ -n "$comment_id" ]; then
|
|
||||||
gh api --method PATCH "repos/${REPO}/issues/comments/${comment_id}" \
|
|
||||||
--input - < <(jq -n --rawfile body "$report" '{body: $body}')
|
|
||||||
else
|
|
||||||
gh api --method POST "repos/${REPO}/issues/${pr}/comments" \
|
|
||||||
--input - < <(jq -n --rawfile body "$report" '{body: $body}')
|
|
||||||
fi
|
|
||||||
+11
-28
@@ -100,38 +100,21 @@ jobs:
|
|||||||
- name: Test (race + shuffle)
|
- name: Test (race + shuffle)
|
||||||
run: go test -race -shuffle=on -count=1 -timeout=10m ./...
|
run: go test -race -shuffle=on -count=1 -timeout=10m ./...
|
||||||
|
|
||||||
benchmark:
|
memci:
|
||||||
needs: [test]
|
needs: [test]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
- uses: actions/checkout@v6
|
||||||
|
- uses: actions/setup-go@v6
|
||||||
- uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
|
|
||||||
with:
|
with:
|
||||||
go-version: "1.26"
|
go-version: "1.26"
|
||||||
|
# Needed because a build command in memci.json names tinygo. Keep the two
|
||||||
- name: Run benchmarks
|
# versions in step: TinyGo 0.42 builds with Go 1.25 through 1.27 and
|
||||||
run: go test -bench=. -benchmem -count=5 -shuffle=on -run='^$' -timeout=15m ./... | tee bench-results.txt
|
# refuses to run outside that window, in either direction.
|
||||||
|
- uses: acifani/setup-tinygo@v2
|
||||||
- name: Generate benchmark report
|
|
||||||
run: |
|
|
||||||
go run ./internal/benchci -current bench-results.txt -out bench-report.md
|
|
||||||
cat bench-report.md >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
|
|
||||||
- name: Upload generated benchmark report
|
|
||||||
if: github.event_name == 'pull_request'
|
|
||||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
|
||||||
with:
|
with:
|
||||||
name: bench-report
|
tinygo-version: "0.42.0"
|
||||||
path: bench-report.md
|
- uses: soypat/memci@main
|
||||||
retention-days: 30
|
|
||||||
|
|
||||||
- name: Upload raw benchmark results
|
|
||||||
if: always()
|
|
||||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
|
||||||
with:
|
with:
|
||||||
name: bench-results
|
args: -kind package
|
||||||
path: bench-results.txt
|
targets: .github/workflows/memci.json
|
||||||
retention-days: 30
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
name: memci comment
|
||||||
|
|
||||||
|
# Runs in the base repo's context with a write token, after the untrusted memci
|
||||||
|
# workflow finishes. It never checks out or runs PR code; it only consumes the
|
||||||
|
# report artifact as inert data.
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_run:
|
||||||
|
workflows: [CI]
|
||||||
|
types: [completed]
|
||||||
|
|
||||||
|
permissions: read-all
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
comment:
|
||||||
|
if: github.event.workflow_run.event == 'pull_request'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
|
steps:
|
||||||
|
- uses: soypat/memci/comment@main
|
||||||
|
with:
|
||||||
|
run-id: ${{ github.event.workflow_run.id }}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"name":"Stack MWE",
|
||||||
|
"build":"go build -o=mwe.elf -tags=noslog ./examples/min-working-example",
|
||||||
|
"elf":"mwe.elf"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name":"Stack MWE pico",
|
||||||
|
"build":"tinygo build -o=mwe-pico.elf -target=pico -tags=noslog -panic=trap ./examples/min-working-example",
|
||||||
|
"elf":"mwe-pico.elf",
|
||||||
|
"mem":true
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -81,3 +81,6 @@ local
|
|||||||
|
|
||||||
# If running a python script.
|
# If running a python script.
|
||||||
*/__pycache__/*
|
*/__pycache__/*
|
||||||
|
|
||||||
|
# memci targets
|
||||||
|
!.github/workflows/memci.json
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
# lneto
|
# lneto
|
||||||
[](https://pkg.go.dev/github.com/soypat/lneto)
|
[](https://pkg.go.dev/github.com/soypat/lneto)
|
||||||
[](https://goreportcard.com/report/github.com/soypat/lneto)
|
|
||||||
[](https://codecov.io/gh/soypat/lneto)
|
[](https://codecov.io/gh/soypat/lneto)
|
||||||
[](https://github.com/soypat/lneto/actions/workflows/ci.yaml)
|
[](https://github.com/soypat/lneto/actions/workflows/ci.yaml)
|
||||||
[](https://github.com/soypat/lneto/network/dependents)
|
[](https://github.com/soypat/lneto/network/dependents)
|
||||||
@@ -291,3 +290,11 @@ The document has moved
|
|||||||
</BODY></HTML>
|
</BODY></HTML>
|
||||||
success
|
success
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
### Build tags
|
||||||
|
|
||||||
|
- `debugheaplog`: All logging calls are enabled and all will print out heap information. Warning: Heavy cost on some TinyGo garbage collectors which do not cache the GC statistics
|
||||||
|
- `noslog`: All slog package logging calls omitted.
|
||||||
|
- `xnetdebug`: Packet capture printing to standard output enabled on `xnet.StackAsync` Ethernet and IP receive and send methods
|
||||||
|
|||||||
+19
-20
@@ -2,12 +2,10 @@ package arp
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
"github.com/soypat/lneto/ethernet"
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
"github.com/soypat/lneto/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewFrame returns a Frame with data set to buf.
|
// NewFrame returns a Frame with data set to buf.
|
||||||
@@ -145,23 +143,24 @@ func (afrm Frame) ValidateSize(v *lneto.Validator) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// String returns a basic human readable represetation of ARP frame.
|
||||||
func (afrm Frame) String() string {
|
func (afrm Frame) String() string {
|
||||||
opstr := afrm.Operation().String()
|
opstr := afrm.Operation().String()
|
||||||
hwt, _ := afrm.Hardware()
|
rawbuf := make([]byte, 0, 128)
|
||||||
ptt, _ := afrm.Protocol()
|
b := append(rawbuf[:0], "ARP "...)
|
||||||
sndhw, sndpt := afrm.Sender()
|
b = append(b, opstr...)
|
||||||
tgthw, tgtpt := afrm.Target()
|
htyp, hlen := afrm.Hardware()
|
||||||
var sndstr, tgtstr string
|
b = internal.AppendStrDecimal(b, " htyp=", int64(htyp))
|
||||||
if ptt == ethernet.TypeIPv4 || ptt == ethernet.TypeIPv6 {
|
b = internal.AppendStrDecimal(b, " hlen=", int64(hlen))
|
||||||
sender, _ := netip.AddrFromSlice(sndpt)
|
ptyp, plen := afrm.Protocol()
|
||||||
target, _ := netip.AddrFromSlice(tgtpt)
|
b = internal.AppendStrDecimal(b, " plen=", int64(plen))
|
||||||
sndstr = sender.String()
|
b = append(b, " proto="...)
|
||||||
tgtstr = target.String()
|
b = append(b, ptyp.String()...)
|
||||||
} else {
|
hw, proto := afrm.Target()
|
||||||
sndstr = net.HardwareAddr(sndpt).String()
|
b = internal.AppendStrHexData(b, " htgt=", hw...)
|
||||||
tgtstr = net.HardwareAddr(tgtpt).String()
|
b = internal.AppendStrHexData(b, " ptgt=", proto...)
|
||||||
}
|
hw, proto = afrm.Sender()
|
||||||
return fmt.Sprintf("ARP %s HW=(%d,SENDER=%s,TARGET=%s) PROTO=(%s,SENDER=%s,TARGET=%s)",
|
b = internal.AppendStrHexData(b, " hsnd=", hw...)
|
||||||
opstr, hwt, net.HardwareAddr(sndhw).String(), net.HardwareAddr(tgthw).String(),
|
b = internal.AppendStrHexData(b, " psnd=", proto...)
|
||||||
ptt.String(), sndstr, tgtstr)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package dhcpv4
|
|||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
"github.com/soypat/lneto/internal"
|
"github.com/soypat/lneto/internal"
|
||||||
@@ -220,10 +219,10 @@ func (sv *Server) Demux(carrierData []byte, frameOffset int) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf("unhandled message type %s", msgType.String())
|
err = errors.New("unhandled message type: " + msgType.String())
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("msgtype=%s client=%+v: %w", msgType.String(), client, err)
|
return errors.New("dhcpv4 server demux fail on " + msgType.String())
|
||||||
}
|
}
|
||||||
sv.hosts[clientIDRaw] = client
|
sv.hosts[clientIDRaw] = client
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
+11
-2
@@ -24,6 +24,11 @@ type ResolveConfig struct {
|
|||||||
Questions []Question
|
Questions []Question
|
||||||
Additional []Resource
|
Additional []Resource
|
||||||
EnableRecursion bool
|
EnableRecursion bool
|
||||||
|
// MaxResponseAnswers limits how many answer records are decoded from the
|
||||||
|
// DNS response. If zero it defaults to the number of Questions. Answers
|
||||||
|
// are decoded in wire order regardless of type, so a response resolved
|
||||||
|
// through CNAMEs needs room for the CNAME records as well as the addresses.
|
||||||
|
MaxResponseAnswers uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sudp *Client) Protocol() uint64 { return uint64(lneto.IPProtoUDP) }
|
func (sudp *Client) Protocol() uint64 { return uint64(lneto.IPProtoUDP) }
|
||||||
@@ -34,11 +39,15 @@ func (sudp *Client) ConnectionID() *uint64 { return &sudp.connID }
|
|||||||
|
|
||||||
func (c *Client) StartResolve(localPort, txid uint16, cfg ResolveConfig) error {
|
func (c *Client) StartResolve(localPort, txid uint16, cfg ResolveConfig) error {
|
||||||
nd := len(cfg.Questions)
|
nd := len(cfg.Questions)
|
||||||
if nd > math.MaxUint16 {
|
if nd > math.MaxUint16 || nd == 0 {
|
||||||
return lneto.ErrInvalidConfig
|
return lneto.ErrInvalidConfig
|
||||||
}
|
}
|
||||||
|
maxAns := cfg.MaxResponseAnswers
|
||||||
|
if maxAns == 0 {
|
||||||
|
maxAns = uint16(nd)
|
||||||
|
}
|
||||||
c.reset(localPort, txid, CQueryPending, cfg.EnableRecursion)
|
c.reset(localPort, txid, CQueryPending, cfg.EnableRecursion)
|
||||||
c.msg.LimitResourceDecoding(uint16(nd), uint16(nd), 0, 0)
|
c.msg.LimitResourceDecoding(uint16(nd), maxAns, 0, 0)
|
||||||
c.msg.AddQuestions(cfg.Questions)
|
c.msg.AddQuestions(cfg.Questions)
|
||||||
c.msg.AddAdditionals(cfg.Additional)
|
c.msg.AddAdditionals(cfg.Additional)
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -197,6 +197,8 @@ const (
|
|||||||
TypeALL Type = 255 // ALL
|
TypeALL Type = 255 // ALL
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func (tp Type) IsIPAddr() bool { return tp == TypeA || tp == TypeAAAA }
|
||||||
|
|
||||||
// A Class is a type of network.
|
// A Class is a type of network.
|
||||||
type Class uint16
|
type Class uint16
|
||||||
|
|
||||||
|
|||||||
+165
-19
@@ -3,6 +3,7 @@ package dns
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"encoding/hex"
|
||||||
"math"
|
"math"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -99,6 +100,12 @@ func NamesEqual(a, b Name) bool {
|
|||||||
return internal.BytesEqual(a.data, b.data)
|
return internal.BytesEqual(a.data, b.data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NamesEqualFold reports whether two DNS names are equal under ASCII case
|
||||||
|
// folding, which is how DNS labels compare per RFC 1035 section 2.3.3.
|
||||||
|
func NamesEqualFold(a, b Name) bool {
|
||||||
|
return internal.BytesEqualFoldASCII(a.data, b.data)
|
||||||
|
}
|
||||||
|
|
||||||
type ZFlags uint16
|
type ZFlags uint16
|
||||||
|
|
||||||
func NewResource(name Name, typ Type, class Class, ttl uint32, data []byte) Resource {
|
func NewResource(name Name, typ Type, class Class, ttl uint32, data []byte) Resource {
|
||||||
@@ -299,27 +306,57 @@ func (m *Message) AppendTo(buf []byte, txid uint16, flags HeaderFlags) (_ []byte
|
|||||||
return buf, nil
|
return buf, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteAnswers writes the addresses answering host into dst, following the
|
||||||
|
// CNAME chain rooted at host. It returns the number of addresses written.
|
||||||
func (m *Message) WriteAnswers(dst []netip.Addr, host string) (n uint16, err error) {
|
func (m *Message) WriteAnswers(dst []netip.Addr, host string) (n uint16, err error) {
|
||||||
for i := range m.Answers {
|
// Each round resolves one CNAME, which consumes an answer. Bounding the
|
||||||
if int(n) >= len(dst) {
|
// walk by the answer count is thus enough to reach the addresses, and
|
||||||
return n, lneto.ErrExhausted
|
// terminates on cyclic chains.
|
||||||
|
var alias Name // Canonical name reached so far; zero means host itself.
|
||||||
|
for range m.Answers {
|
||||||
|
var next Name
|
||||||
|
for i := range m.Answers {
|
||||||
|
ans := &m.Answers[i]
|
||||||
|
if !ans.header.ownedBy(alias, host) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case ans.header.Type.IsIPAddr():
|
||||||
|
if int(n) >= len(dst) {
|
||||||
|
return n, lneto.ErrExhausted
|
||||||
|
}
|
||||||
|
addr, ok := netip.AddrFromSlice(ans.RawData())
|
||||||
|
if !ok {
|
||||||
|
err = lneto.ErrInvalidAddr
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dst[n] = addr
|
||||||
|
n++
|
||||||
|
case ans.header.Type == TypeCNAME:
|
||||||
|
if cname := ans.CNAMEView(); cname.Len() != 0 {
|
||||||
|
next = cname
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ans := &m.Answers[i]
|
if n > 0 || next.Len() == 0 {
|
||||||
hdr := ans.Header()
|
break
|
||||||
if !hdr.Name.EqualString(host) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var ok bool
|
|
||||||
dst[n], ok = netip.AddrFromSlice(ans.RawData())
|
|
||||||
if !ok {
|
|
||||||
err = lneto.ErrInvalidAddr
|
|
||||||
} else {
|
|
||||||
n++
|
|
||||||
}
|
}
|
||||||
|
alias = next
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ownedBy reports whether the record's owner name is the name being resolved:
|
||||||
|
// the alias reached by following CNAMEs, or host at the root of the chain.
|
||||||
|
func (h *ResourceHeader) ownedBy(alias Name, host string) bool {
|
||||||
|
if alias.Len() == 0 {
|
||||||
|
return h.Name.EqualString(host)
|
||||||
|
}
|
||||||
|
// Fold: the server chooses the case of both the CNAME target and the owner
|
||||||
|
// name of the records it aliases, and may randomize it (DNS 0x20).
|
||||||
|
return NamesEqualFold(h.Name, alias)
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Message) Len() uint16 {
|
func (m *Message) Len() uint16 {
|
||||||
return SizeHeader + m.lenResources()
|
return SizeHeader + m.lenResources()
|
||||||
}
|
}
|
||||||
@@ -390,10 +427,64 @@ func (m *Message) Reset() {
|
|||||||
m.Additionals = m.Additionals[:0]
|
m.Additionals = m.Additionals[:0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AppendText appends a human readable representation of the Message's resources
|
||||||
|
// to b and returns the resulting slice. It implements [encoding.TextAppender].
|
||||||
|
func (m *Message) AppendText(b []byte) (_ []byte, err error) {
|
||||||
|
if len(m.Questions) > 0 {
|
||||||
|
b = append(b, "-- Questions\n"...)
|
||||||
|
for i := range m.Questions {
|
||||||
|
b, err = m.Questions[i].AppendText(b)
|
||||||
|
if err != nil {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
b = append(b, '\n')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b, err = appendResourcesText(b, "-- Answers\n", m.Answers)
|
||||||
|
if err != nil {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
b, err = appendResourcesText(b, "-- Authorities\n", m.Authorities)
|
||||||
|
if err != nil {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
return appendResourcesText(b, "-- Additionals\n", m.Additionals)
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendResourcesText(b []byte, title string, resources []Resource) (_ []byte, err error) {
|
||||||
|
if len(resources) == 0 {
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
b = append(b, title...)
|
||||||
|
for i := range resources {
|
||||||
|
b, err = resources[i].AppendText(b)
|
||||||
|
if err != nil {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
b = append(b, '\n')
|
||||||
|
}
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
|
||||||
// String returns a string representation of the header.
|
// String returns a string representation of the header.
|
||||||
func (h *ResourceHeader) String() string {
|
func (h *ResourceHeader) String() string {
|
||||||
return h.Name.String() + " " + h.Type.String() + " " + h.Class.String() +
|
b, _ := h.AppendText(make([]byte, 0, 64))
|
||||||
" ttl=" + strconv.FormatUint(uint64(h.TTL), 10) + " len=" + strconv.FormatUint(uint64(h.Length), 10)
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendText appends a human readable representation of the header to b and
|
||||||
|
// returns the resulting slice. It implements [encoding.TextAppender].
|
||||||
|
func (h *ResourceHeader) AppendText(b []byte) ([]byte, error) {
|
||||||
|
b = h.Name.AppendDottedTo(b)
|
||||||
|
b = append(b, ' ')
|
||||||
|
b = append(b, h.Type.String()...)
|
||||||
|
b = append(b, ' ')
|
||||||
|
b = append(b, h.Class.String()...)
|
||||||
|
b = append(b, " ttl="...)
|
||||||
|
b = strconv.AppendUint(b, uint64(h.TTL), 10)
|
||||||
|
b = append(b, " len="...)
|
||||||
|
b = strconv.AppendUint(b, uint64(h.Length), 10)
|
||||||
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Resource) Reset() {
|
func (r *Resource) Reset() {
|
||||||
@@ -411,6 +502,38 @@ func (r *Resource) RawData() []byte {
|
|||||||
return r.data[:length]
|
return r.data[:length]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CNAMEView returns the canonical name held by a CNAME record, aliasing the
|
||||||
|
// Resource's buffer. It returns a zero Name for any other record type.
|
||||||
|
func (r *Resource) CNAMEView() Name {
|
||||||
|
if r.header.Type != TypeCNAME {
|
||||||
|
return Name{}
|
||||||
|
}
|
||||||
|
return Name{data: r.RawData()}
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a string representation of the Resource: its header followed by
|
||||||
|
// the record's data.
|
||||||
|
func (r *Resource) String() string {
|
||||||
|
b, _ := r.AppendText(make([]byte, 0, 96))
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendText appends a human readable representation of the Resource to b: the
|
||||||
|
// header followed by the record's data, in dotted format for CNAME records and
|
||||||
|
// hexadecimal otherwise. It implements [encoding.TextAppender].
|
||||||
|
func (r *Resource) AppendText(b []byte) (_ []byte, err error) {
|
||||||
|
b, err = r.header.AppendText(b)
|
||||||
|
if err != nil {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
b = append(b, " data="...)
|
||||||
|
if r.header.Type == TypeCNAME {
|
||||||
|
cname := r.CNAMEView()
|
||||||
|
return cname.AppendDottedTo(b), nil
|
||||||
|
}
|
||||||
|
return hex.AppendEncode(b, r.RawData()), nil
|
||||||
|
}
|
||||||
|
|
||||||
func (q *Question) Reset() {
|
func (q *Question) Reset() {
|
||||||
q.Name.Reset()
|
q.Name.Reset()
|
||||||
*q = Question{Name: q.Name} // Reuse Name's buffer.
|
*q = Question{Name: q.Name} // Reuse Name's buffer.
|
||||||
@@ -449,7 +572,19 @@ func (q *Question) appendTo(buf []byte) (_ []byte, err error) {
|
|||||||
|
|
||||||
// String returns a string representation of the Question with the Name in dotted format.
|
// String returns a string representation of the Question with the Name in dotted format.
|
||||||
func (q *Question) String() string {
|
func (q *Question) String() string {
|
||||||
return q.Name.String() + " " + q.Type.String() + " " + q.Class.String()
|
b, _ := q.AppendText(make([]byte, 0, 32))
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendText appends a human readable representation of the Question to b with
|
||||||
|
// the Name in dotted format. It implements [encoding.TextAppender].
|
||||||
|
func (q *Question) AppendText(b []byte) ([]byte, error) {
|
||||||
|
b = q.Name.AppendDottedTo(b)
|
||||||
|
b = append(b, ' ')
|
||||||
|
b = append(b, q.Type.String()...)
|
||||||
|
b = append(b, ' ')
|
||||||
|
b = append(b, q.Class.String()...)
|
||||||
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Resource) Decode(b []byte, off uint16) (uint16, error) {
|
func (r *Resource) Decode(b []byte, off uint16) (uint16, error) {
|
||||||
@@ -460,8 +595,19 @@ func (r *Resource) Decode(b []byte, off uint16) (uint16, error) {
|
|||||||
if r.header.Length > uint16(len(b[off:])) {
|
if r.header.Length > uint16(len(b[off:])) {
|
||||||
return off, errResourceLen
|
return off, errResourceLen
|
||||||
}
|
}
|
||||||
r.data = append(r.data[:0], b[off:off+r.header.Length]...)
|
end := off + r.header.Length
|
||||||
return off + r.header.Length, nil
|
if r.header.Type == TypeCNAME {
|
||||||
|
// CNAME data is a name which may use message compression. Expand it now
|
||||||
|
// since r.data is detached from b, leaving pointers unresolvable later.
|
||||||
|
cname := Name{data: r.data[:0]}
|
||||||
|
if _, derr := cname.Decode(b, off); derr == nil {
|
||||||
|
r.data = cname.data
|
||||||
|
r.header.Length = uint16(len(r.data))
|
||||||
|
return end, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.data = append(r.data[:0], b[off:end]...)
|
||||||
|
return end, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Resource) appendTo(buf []byte) (_ []byte, err error) {
|
func (r *Resource) appendTo(buf []byte) (_ []byte, err error) {
|
||||||
|
|||||||
+233
-89
@@ -1,7 +1,6 @@
|
|||||||
package dns
|
package dns
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -195,33 +194,8 @@ func TestMessageAppendEncodeIncompleteOK(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Message) String() string {
|
func (m *Message) String() string {
|
||||||
// s := fmt.Sprintf("Message: %#v\n", &m.Header)
|
b, _ := m.AppendText(nil)
|
||||||
var s strings.Builder
|
return string(b)
|
||||||
if len(m.Questions) > 0 {
|
|
||||||
s.WriteString("-- Questions\n")
|
|
||||||
for _, q := range m.Questions {
|
|
||||||
s.WriteString(fmt.Sprintf("%#v\n", q))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(m.Answers) > 0 {
|
|
||||||
s.WriteString("-- Answers\n")
|
|
||||||
for _, a := range m.Answers {
|
|
||||||
s.WriteString(fmt.Sprintf("%#v\n", a))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(m.Authorities) > 0 {
|
|
||||||
s.WriteString("-- Authorities\n")
|
|
||||||
for _, ns := range m.Authorities {
|
|
||||||
s.WriteString(fmt.Sprintf("%#v\n", ns))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(m.Additionals) > 0 {
|
|
||||||
s.WriteString("-- Additionals\n")
|
|
||||||
for _, e := range m.Additionals {
|
|
||||||
s.WriteString(fmt.Sprintf("%#v\n", e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDecodeMessage(t *testing.T) {
|
func TestDecodeMessage(t *testing.T) {
|
||||||
@@ -239,80 +213,250 @@ func TestDecodeMessage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClient_ReceivesDNSResponse(t *testing.T) {
|
// Regression test for CNAME-following: a response for www.yahoo.co.jp
|
||||||
const hostname = "example.com"
|
// contains a CNAME record to edge12.g.yimg.jp (with compressed labels in its
|
||||||
const txid = uint16(12345)
|
// RDATA) followed by the A record for the canonical name. The CNAME RDATA
|
||||||
|
// must not be interpreted as an IP address and the A record must be returned.
|
||||||
|
func TestClient_CNAMEResponse(t *testing.T) {
|
||||||
|
const hostname = "www.yahoo.co.jp"
|
||||||
|
const txid = uint16(0x1234)
|
||||||
const clientPort = uint16(54321)
|
const clientPort = uint16(54321)
|
||||||
wantIP := [4]byte{93, 184, 216, 34}
|
response := []byte{
|
||||||
|
// Header: txid 0x1234, QR|RD|RA, QD=1 AN=2 NS=0 AR=0.
|
||||||
// Build a DNS response message.
|
0x12, 0x34, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
// Question: www.yahoo.co.jp A IN.
|
||||||
|
0x03, 'w', 'w', 'w', 0x05, 'y', 'a', 'h', 'o', 'o', 0x02, 'c', 'o', 0x02, 'j', 'p', 0x00,
|
||||||
|
0x00, 0x01, 0x00, 0x01,
|
||||||
|
// Answer 1: (ptr to question) CNAME IN ttl=842 rdlen=16
|
||||||
|
// rdata: edge12.g.yimg.jp with "jp" as compression pointer to offset 0x19.
|
||||||
|
0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x03, 0x4a, 0x00, 0x10,
|
||||||
|
0x06, 'e', 'd', 'g', 'e', '1', '2', 0x01, 'g', 0x04, 'y', 'i', 'm', 'g', 0xc0, 0x19,
|
||||||
|
// Answer 2: (ptr into CNAME rdata) A IN ttl=36 rdlen=4 182.22.23.124.
|
||||||
|
0xc0, 0x2d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x04, 0xb6, 0x16, 0x17, 0x7c,
|
||||||
|
}
|
||||||
name := MustNewName(hostname)
|
name := MustNewName(hostname)
|
||||||
responseMsg := Message{
|
var client Client
|
||||||
|
err := client.StartResolve(clientPort, txid, ResolveConfig{
|
||||||
Questions: []Question{{
|
Questions: []Question{{
|
||||||
Name: name,
|
Name: name,
|
||||||
Type: TypeA,
|
Type: TypeA,
|
||||||
Class: ClassINET,
|
Class: ClassINET,
|
||||||
}},
|
}},
|
||||||
Answers: []Resource{
|
EnableRecursion: true,
|
||||||
NewResource(name, TypeA, ClassINET, 300, wantIP[:]),
|
MaxResponseAnswers: 6,
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Response flags: QR=1 (response), RD=1, RA=1.
|
|
||||||
responseFlags := HeaderFlags(1<<15 | 1<<8 | 1<<7)
|
|
||||||
|
|
||||||
var buf [512]byte
|
|
||||||
dnsPayload, err := responseMsg.AppendTo(buf[:0], txid, responseFlags)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("failed to build DNS response:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up the DNS client.
|
|
||||||
var client Client
|
|
||||||
client.StartResolve(clientPort, txid, ResolveConfig{
|
|
||||||
Questions: []Question{{
|
|
||||||
Name: MustNewName(hostname),
|
|
||||||
Type: TypeA,
|
|
||||||
Class: ClassINET,
|
|
||||||
}},
|
|
||||||
EnableRecursion: true,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Simulate sending by calling Encapsulate (changes state to AwaitResponse).
|
|
||||||
var dummy [512]byte
|
|
||||||
client.Encapsulate(dummy[:], 0, 0)
|
|
||||||
|
|
||||||
// Call Demux with DNS payload.
|
|
||||||
err = client.Demux(dnsPayload, 0)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("Client Demux error:", err)
|
t.Fatal("failed to start DNS resolve:", err)
|
||||||
|
}
|
||||||
|
var queryBuf [512]byte
|
||||||
|
_, err = client.Encapsulate(queryBuf[:], 0, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to encapsulate DNS query:", err)
|
||||||
|
}
|
||||||
|
if err := client.Demux(response, 0); err != nil {
|
||||||
|
t.Fatal("failed to demux DNS response:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check the client received the answer.
|
|
||||||
var addrs [4]netip.Addr
|
var addrs [4]netip.Addr
|
||||||
answers, err := client.ResponseAnswerLookup(addrs[:], hostname)
|
n, err := client.ResponseAnswerLookup(addrs[:], hostname)
|
||||||
if answers != 1 {
|
|
||||||
t.Fatalf("expected 1 answer, got %d", answers)
|
|
||||||
}
|
|
||||||
addr := addrs[0]
|
|
||||||
if !addr.Is4() {
|
|
||||||
t.Fatalf("expected 4 bytes in answer, got %d", addr.BitLen()/8)
|
|
||||||
}
|
|
||||||
if addr.As4() != wantIP {
|
|
||||||
t.Errorf("expected IP %v, got %v", wantIP, addr.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test MessageCopyTo as well.
|
|
||||||
var lookup Message
|
|
||||||
lookup.LimitResourceDecoding(1, 1, 0, 0)
|
|
||||||
done, err := client.ResponseCopyTo(&lookup)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("MessageCopyTo error:", err)
|
t.Fatal("failed to look up DNS response answers:", err)
|
||||||
}
|
}
|
||||||
if !done {
|
if n != 1 {
|
||||||
t.Fatal("expected done=true")
|
t.Fatalf("expected 1 answer, got %d: %v", n, addrs[:n])
|
||||||
}
|
}
|
||||||
if len(lookup.Answers) != 1 {
|
if addrs[0] != (netip.AddrFrom4([4]byte{182, 22, 23, 124})) {
|
||||||
t.Fatalf("MessageCopyTo: expected 1 answer, got %d", len(lookup.Answers))
|
t.Fatalf("expected 182.22.23.124, got %v", addrs[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Table-driven tests for Message.WriteAnswers covering answer reordering
|
||||||
|
// and cyclic CNAME aliases.
|
||||||
|
func TestMessage_WriteAnswers(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
host string
|
||||||
|
response []byte
|
||||||
|
want []netip.Addr
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "A record before its CNAME",
|
||||||
|
host: "www.yahoo.co.jp",
|
||||||
|
// Answer 1 is the A record for edge12.g.yimg.jp, spelled out with
|
||||||
|
// a trailing compression pointer to "jp" in the question. Answer 2
|
||||||
|
// is the CNAME from www.yahoo.co.jp whose RDATA is a single
|
||||||
|
// backward compression pointer to answer 1's owner name.
|
||||||
|
response: []byte{
|
||||||
|
// Header: txid 0x1234, QR|RD|RA, QD=1 AN=2 NS=0 AR=0.
|
||||||
|
0x12, 0x34, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
// Question: www.yahoo.co.jp A IN.
|
||||||
|
0x03, 'w', 'w', 'w', 0x05, 'y', 'a', 'h', 'o', 'o', 0x02, 'c', 'o', 0x02, 'j', 'p', 0x00,
|
||||||
|
0x00, 0x01, 0x00, 0x01,
|
||||||
|
// Answer 1: edge12.g.yimg.jp A IN ttl=36 rdlen=4 182.22.23.124.
|
||||||
|
0x06, 'e', 'd', 'g', 'e', '1', '2', 0x01, 'g', 0x04, 'y', 'i', 'm', 'g', 0xc0, 0x19,
|
||||||
|
0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x04, 0xb6, 0x16, 0x17, 0x7c,
|
||||||
|
// Answer 2: (ptr to question) CNAME IN ttl=842 rdlen=2, target
|
||||||
|
// is a pointer to answer 1's owner name at offset 0x21.
|
||||||
|
0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x03, 0x4a, 0x00, 0x02, 0xc0, 0x21,
|
||||||
|
},
|
||||||
|
want: []netip.Addr{netip.AddrFrom4([4]byte{182, 22, 23, 124})},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CNAME cycle terminates",
|
||||||
|
host: "a.com",
|
||||||
|
response: []byte{
|
||||||
|
// Header: txid 0xabcd, QR|RD|RA, QD=1 AN=2 NS=0 AR=0.
|
||||||
|
0xab, 0xcd, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
// Question: a.com A IN.
|
||||||
|
0x01, 'a', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x01, 0x00, 0x01,
|
||||||
|
// Answer 1: a.com CNAME b.com.
|
||||||
|
0x01, 'a', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x07, 0x01, 'b', 0x03, 'c', 'o', 'm', 0x00,
|
||||||
|
// Answer 2: b.com CNAME a.com.
|
||||||
|
0x01, 'b', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x07, 0x01, 'a', 0x03, 'c', 'o', 'm', 0x00,
|
||||||
|
},
|
||||||
|
want: nil,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CNAME target case differs from owner name",
|
||||||
|
host: "a.com",
|
||||||
|
// A server picks the case of both the CNAME target and the owner
|
||||||
|
// name of the record it aliases, and may randomize it (DNS 0x20),
|
||||||
|
// so the two must compare under ASCII case folding.
|
||||||
|
response: []byte{
|
||||||
|
// Header: txid 0xabcd, QR|RD|RA, QD=1 AN=2 NS=0 AR=0.
|
||||||
|
0xab, 0xcd, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
// Question: a.com A IN.
|
||||||
|
0x01, 'a', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x01, 0x00, 0x01,
|
||||||
|
// Answer 1: a.com CNAME B.CoM.
|
||||||
|
0x01, 'a', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x07, 0x01, 'B', 0x03, 'C', 'o', 'M', 0x00,
|
||||||
|
// Answer 2: b.com A IN ttl=10 rdlen=4 1.2.3.4.
|
||||||
|
0x01, 'b', 0x03, 'c', 'o', 'm', 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04,
|
||||||
|
},
|
||||||
|
want: []netip.Addr{netip.AddrFrom4([4]byte{1, 2, 3, 4})},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
var msg Message
|
||||||
|
msg.LimitResourceDecoding(1, 4, 0, 0)
|
||||||
|
_, incomplete, err := msg.Decode(tt.response)
|
||||||
|
if incomplete || err != nil {
|
||||||
|
t.Fatal("decode:", incomplete, err)
|
||||||
|
}
|
||||||
|
var addrs [4]netip.Addr
|
||||||
|
n, err := msg.WriteAnswers(addrs[:], tt.host)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("write answers:", err)
|
||||||
|
}
|
||||||
|
if n != uint16(len(tt.want)) {
|
||||||
|
t.Fatalf("expected %d addresses, got %d: %v", len(tt.want), n, addrs[:n])
|
||||||
|
}
|
||||||
|
for i, want := range tt.want {
|
||||||
|
if addrs[i] != want {
|
||||||
|
t.Errorf("address %d: expected %v, got %v", i, want, addrs[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClient_ReceivesDNSResponse(t *testing.T) {
|
||||||
|
const hostname = "example.com"
|
||||||
|
const txid = uint16(12345)
|
||||||
|
const clientPort = uint16(54321)
|
||||||
|
const maxAnswers = 4
|
||||||
|
allIPs := [5][4]byte{
|
||||||
|
{192, 0, 2, 1},
|
||||||
|
{192, 0, 2, 2},
|
||||||
|
{192, 0, 2, 3},
|
||||||
|
{192, 0, 2, 4},
|
||||||
|
{192, 0, 2, 5},
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
responseIPs [][4]byte
|
||||||
|
wantAnswers int // Addresses returned by ResponseAnswerLookup and copied by ResponseCopyTo.
|
||||||
|
}{
|
||||||
|
{name: "single_answer", responseIPs: allIPs[:1], wantAnswers: 1},
|
||||||
|
{name: "multiple_answers", responseIPs: allIPs[:4], wantAnswers: 4},
|
||||||
|
{name: "answer_limit", responseIPs: allIPs[:5], wantAnswers: maxAnswers},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
name := MustNewName(hostname)
|
||||||
|
responseMsg := Message{
|
||||||
|
Questions: []Question{{
|
||||||
|
Name: name,
|
||||||
|
Type: TypeA,
|
||||||
|
Class: ClassINET,
|
||||||
|
}},
|
||||||
|
Answers: make([]Resource, len(tt.responseIPs)),
|
||||||
|
}
|
||||||
|
for i := range tt.responseIPs {
|
||||||
|
responseMsg.Answers[i] = NewResource(name, TypeA, ClassINET, 300, tt.responseIPs[i][:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response flags: QR=1 (response), RD=1, RA=1.
|
||||||
|
responseFlags := HeaderFlags(1<<15 | 1<<8 | 1<<7)
|
||||||
|
var responseBuf [512]byte
|
||||||
|
dnsPayload, err := responseMsg.AppendTo(responseBuf[:0], txid, responseFlags)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to build DNS response:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var client Client
|
||||||
|
err = client.StartResolve(clientPort, txid, ResolveConfig{
|
||||||
|
Questions: []Question{{
|
||||||
|
Name: name,
|
||||||
|
Type: TypeA,
|
||||||
|
Class: ClassINET,
|
||||||
|
}},
|
||||||
|
EnableRecursion: true,
|
||||||
|
MaxResponseAnswers: maxAnswers,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to start DNS resolve:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encapsulate the query to move the client into the outstanding state.
|
||||||
|
var queryBuf [512]byte
|
||||||
|
_, err = client.Encapsulate(queryBuf[:], 0, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to encapsulate DNS query:", err)
|
||||||
|
}
|
||||||
|
if err := client.Demux(dnsPayload, 0); err != nil {
|
||||||
|
t.Fatal("failed to demux DNS response:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var addrs [maxAnswers]netip.Addr
|
||||||
|
answers, err := client.ResponseAnswerLookup(addrs[:], hostname)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to look up DNS response answers:", err)
|
||||||
|
}
|
||||||
|
if int(answers) != tt.wantAnswers {
|
||||||
|
t.Fatalf("expected %d answers, got %d", tt.wantAnswers, answers)
|
||||||
|
}
|
||||||
|
for i := 0; i < tt.wantAnswers; i++ {
|
||||||
|
addr := addrs[i]
|
||||||
|
if !addr.Is4() {
|
||||||
|
t.Errorf("answer %d: expected IPv4 address, got %v", i, addr)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if addr.As4() != tt.responseIPs[i] {
|
||||||
|
t.Errorf("answer %d: expected IP %v, got %v", i, tt.responseIPs[i], addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var lookup Message
|
||||||
|
done, err := client.ResponseCopyTo(&lookup)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to copy DNS response:", err)
|
||||||
|
}
|
||||||
|
if !done {
|
||||||
|
t.Fatal("expected done=true")
|
||||||
|
}
|
||||||
|
if len(lookup.Answers) != tt.wantAnswers {
|
||||||
|
t.Fatalf("expected %d copied answers, got %d", tt.wantAnswers, len(lookup.Answers))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"errors"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
@@ -46,7 +46,7 @@ func main() {
|
|||||||
var stack xnet.StackAsync
|
var stack xnet.StackAsync
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
if err := run(ctx, &stack); err != nil {
|
if err := run(ctx, &stack); err != nil {
|
||||||
fmt.Println(err)
|
os.Stdout.WriteString(err.Error())
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,7 +71,7 @@ func run(ctx context.Context, stack *xnet.StackAsync) error {
|
|||||||
HardwareAddress: hwaddr,
|
HardwareAddress: hwaddr,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("configuring stack: %w", err)
|
return makeMsgErr("configuring stack", err)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -82,18 +82,18 @@ func run(ctx context.Context, stack *xnet.StackAsync) error {
|
|||||||
rstack := stack.StackRetrying(stackBackoff)
|
rstack := stack.StackRetrying(stackBackoff)
|
||||||
results, err := rstack.DoDHCPv4([4]byte{}, protoTimeout, protoRetries)
|
results, err := rstack.DoDHCPv4([4]byte{}, protoTimeout, protoRetries)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("doing DHCP: %w", err)
|
return makeMsgErr("doing DHCP", err)
|
||||||
}
|
}
|
||||||
err = stack.AssimilateDHCPResults(results)
|
err = stack.AssimilateDHCPResults(results)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("assimilating DHCP: %w", err)
|
return makeMsgErr("assimilating DHCP", err)
|
||||||
}
|
}
|
||||||
gateway, err := rstack.DoResolveHardwareAddress6(results.Router, protoTimeout, protoRetries)
|
gateway, err := rstack.DoResolveHardwareAddress6(results.Router, protoTimeout, protoRetries)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("resolving router MAC: %w", err)
|
return makeMsgErr("resolving Router MAC", err)
|
||||||
}
|
}
|
||||||
stack.SetGatewayHardwareAddr(gateway)
|
stack.SetGatewayHardwareAddr(gateway)
|
||||||
berkstack := stack.StackBlocking(stackBackoff).StackGo(xnet.StackGoConfig{
|
gostack := stack.StackBlocking(stackBackoff).StackGo(xnet.StackGoConfig{
|
||||||
ListenerPoolConfig: xnet.TCPPoolConfig{
|
ListenerPoolConfig: xnet.TCPPoolConfig{
|
||||||
PoolSize: tcpConnPoolSize,
|
PoolSize: tcpConnPoolSize,
|
||||||
QueueSize: tcpPacketQueueSize,
|
QueueSize: tcpPacketQueueSize,
|
||||||
@@ -109,16 +109,16 @@ func run(ctx context.Context, stack *xnet.StackAsync) error {
|
|||||||
laddr := net.TCPAddrFromAddrPort(netip.AddrPortFrom(netip.AddrFrom4(results.AssignedAddr4), 80))
|
laddr := net.TCPAddrFromAddrPort(netip.AddrPortFrom(netip.AddrFrom4(results.AssignedAddr4), 80))
|
||||||
// raddr := net.TCPAddr{} // If active (client) connection then set raddr in which case a net.Conn type is returned.
|
// raddr := net.TCPAddr{} // If active (client) connection then set raddr in which case a net.Conn type is returned.
|
||||||
const sockstream = 0x1
|
const sockstream = 0x1
|
||||||
c, err := berkstack.Socket(ctx, "tcp", syscall.AF_INET, sockstream, laddr, nil)
|
c, err := gostack.Socket(ctx, "tcp", syscall.AF_INET, sockstream, laddr, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("creating AF_INET stream socket: %w", err)
|
return makeMsgErr("creating AF_INET stream socket", err)
|
||||||
}
|
}
|
||||||
listener := c.(net.Listener)
|
listener := c.(net.Listener)
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
time.Sleep(pollTime)
|
time.Sleep(pollTime)
|
||||||
conn, err := listener.Accept()
|
conn, err := listener.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("conn failed:", err)
|
return makeMsgErr("listener.Accept failed", err)
|
||||||
}
|
}
|
||||||
go handleConn(conn)
|
go handleConn(conn)
|
||||||
}
|
}
|
||||||
@@ -145,18 +145,18 @@ func stackLoop(ctx context.Context, stack *xnet.StackAsync) {
|
|||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
nwrite, err := stack.EgressEthernet(buf[:])
|
nwrite, err := stack.EgressEthernet(buf[:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("encaps err:", err)
|
os.Stderr.WriteString(err.Error())
|
||||||
} else if nwrite > 0 {
|
} else if nwrite > 0 {
|
||||||
network.SendEth(buf[:nwrite])
|
network.SendEth(buf[:nwrite])
|
||||||
cap.PrintEthernet("OUT", buf[:nwrite])
|
cap.PrintEthernet("OUT", buf[:nwrite])
|
||||||
}
|
}
|
||||||
nread, err := network.RecvEth(buf[:])
|
nread, err := network.RecvEth(buf[:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("network read err:", err)
|
os.Stderr.WriteString(err.Error())
|
||||||
} else if nread > 0 {
|
} else if nread > 0 {
|
||||||
err = stack.IngressEthernet(buf[:nread])
|
err = stack.IngressEthernet(buf[:nread])
|
||||||
if err != nil && err != lneto.ErrPacketDrop {
|
if err != nil && err != lneto.ErrPacketDrop {
|
||||||
fmt.Println("demux err:", err)
|
os.Stderr.WriteString(err.Error())
|
||||||
} else {
|
} else {
|
||||||
cap.PrintEthernet("IN ", buf[:nread])
|
cap.PrintEthernet("IN ", buf[:nread])
|
||||||
}
|
}
|
||||||
@@ -191,3 +191,7 @@ func tcpBackoff(consecutiveBackoffs uint) time.Duration {
|
|||||||
wait := min(shifted, maxWait)
|
wait := min(shifted, maxWait)
|
||||||
return time.Duration(wait)
|
return time.Duration(wait)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func makeMsgErr(msg string, err error) error {
|
||||||
|
return errors.New(msg + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
mn := &mockNetwork{
|
||||||
|
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
|
||||||
|
}
|
||||||
|
network = mn
|
||||||
|
}
|
||||||
|
|
||||||
|
type mockNetwork struct {
|
||||||
|
rng *rand.Rand
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *mockNetwork) SendEth(frame []byte) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (m *mockNetwork) RecvEth(dst []byte) (int, error) {
|
||||||
|
n := m.rng.Int() % ethernet.MaxFrameLength
|
||||||
|
if n < ethernet.MinimumFrameLength {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
n, _ = m.rng.Read(dst[:min(len(dst), n)])
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
func (m *mockNetwork) HardwareAddress6() ([6]byte, error) {
|
||||||
|
return [6]byte{0xde, 0xad, 0xbe, 0xef, 0x00, 0x00}, nil
|
||||||
|
}
|
||||||
|
func (m *mockNetwork) MaxFrameLength() (int, error) {
|
||||||
|
return ethernet.MaxFrameLength, nil
|
||||||
|
}
|
||||||
@@ -300,25 +300,7 @@ func (kvb *kvBuffer) getFoldIdx(key string) int {
|
|||||||
// EqualFoldASCII reports whether a and b are equal under ASCII case folding.
|
// EqualFoldASCII reports whether a and b are equal under ASCII case folding.
|
||||||
// Unlike strings.EqualFold it does not fold non-ASCII runes, so no multi-byte
|
// Unlike strings.EqualFold it does not fold non-ASCII runes, so no multi-byte
|
||||||
// rune such as U+212A KELVIN SIGN can alias a header key.
|
// rune such as U+212A KELVIN SIGN can alias a header key.
|
||||||
func EqualFoldASCII(a, b string) bool {
|
func EqualFoldASCII(a, b string) bool { return internal.EqualFoldASCII(a, b) }
|
||||||
if len(a) != len(b) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
const asciiCapDiff = 'a' - 'A'
|
|
||||||
for i := 0; i < len(a); i++ {
|
|
||||||
ca, cb := a[i], b[i]
|
|
||||||
if ca >= 'A' && ca <= 'Z' {
|
|
||||||
ca += asciiCapDiff
|
|
||||||
}
|
|
||||||
if cb >= 'A' && cb <= 'Z' {
|
|
||||||
cb += asciiCapDiff
|
|
||||||
}
|
|
||||||
if ca != cb {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// reserve ensures need free bytes are available in the buffer, growing it when
|
// reserve ensures need free bytes are available in the buffer, growing it when
|
||||||
// permitted. It accounts for the byte-0 reservation on an empty buffer (see
|
// permitted. It accounts for the byte-0 reservation on an empty buffer (see
|
||||||
|
|||||||
@@ -253,20 +253,7 @@ func trimOWS(b []byte) []byte {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// equalFold compares b to the ASCII lowercase key, case insensitively.
|
// equalFold compares b to key, case insensitively.
|
||||||
func equalFold(b []byte, key string) bool {
|
func equalFold(b []byte, key string) bool {
|
||||||
if len(b) != len(key) {
|
return EqualFoldASCII(b2s(b), key)
|
||||||
return false
|
|
||||||
}
|
|
||||||
const asciiCapDiff = 'a' - 'A'
|
|
||||||
for i := range b {
|
|
||||||
c := b[i]
|
|
||||||
if c >= 'A' && c <= 'Z' {
|
|
||||||
c += asciiCapDiff
|
|
||||||
}
|
|
||||||
if c != key[i] {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func LogEnabled(l *slog.Logger, lvl slog.Level) bool {
|
func LogEnabled(l *slog.Logger, lvl slog.Level) bool {
|
||||||
return true
|
return logEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
func logAttrsAndAllocs(allocmsg string, l *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr) {
|
func logAttrsAndAllocs(allocmsg string, l *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr) {
|
||||||
|
|||||||
@@ -10,14 +10,14 @@ import (
|
|||||||
const HeapAllocDebugging = false
|
const HeapAllocDebugging = false
|
||||||
|
|
||||||
func LogEnabled(l *slog.Logger, lvl slog.Level) bool {
|
func LogEnabled(l *slog.Logger, lvl slog.Level) bool {
|
||||||
return l != nil && l.Handler().Enabled(context.Background(), lvl)
|
return logEnabled && l != nil && l.Handler().Enabled(context.Background(), lvl)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LogAttrs is a helper function that is used by all package loggers and that
|
// LogAttrs is a helper function that is used by all package loggers and that
|
||||||
// can be switched out with the `debugheaplog` build tag for a non-allocating
|
// can be switched out with the `debugheaplog` build tag for a non-allocating
|
||||||
// logger that prints out when heap allocations occur.
|
// logger that prints out when heap allocations occur.
|
||||||
func LogAttrs(l *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr) {
|
func LogAttrs(l *slog.Logger, level slog.Level, msg string, attrs ...slog.Attr) {
|
||||||
if l != nil {
|
if logEnabled && l != nil {
|
||||||
l.LogAttrs(context.Background(), level, msg, attrs...)
|
l.LogAttrs(context.Background(), level, msg, attrs...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build noslog
|
||||||
|
|
||||||
|
package internal
|
||||||
|
|
||||||
|
const logEnabled = false
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//go:build !noslog
|
||||||
|
|
||||||
|
package internal
|
||||||
|
|
||||||
|
const logEnabled = true
|
||||||
@@ -15,33 +15,57 @@ import (
|
|||||||
// from the test thread, or vice versa.
|
// from the test thread, or vice versa.
|
||||||
func NewSched(t testing.TB) *Sched {
|
func NewSched(t testing.TB) *Sched {
|
||||||
return &Sched{
|
return &Sched{
|
||||||
t: t,
|
t: t,
|
||||||
goroYieldSignal: make(chan struct{}),
|
timeout: time.Second,
|
||||||
goroContinueSignal: make(chan struct{}),
|
|
||||||
finishChan: make(chan error, 1),
|
|
||||||
timeout: time.Second,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sched is the shared state behind a [SchedGoro]/[SchedDriver] pair. It exposes no
|
// Sched is the shared state behind a [SchedGoro]/[SchedDriver] pair. It exposes no
|
||||||
// handoff methods directly; obtain a handle with [Sched.Goro] (for the
|
// handoff methods directly; obtain a handle with [Sched.Goro] (for the
|
||||||
// scheduled goroutine) or [Sched.Driver] (for the test thread).
|
// scheduled goroutine) or [Sched.Driver] (for the test thread).
|
||||||
|
//
|
||||||
|
// A Sched may schedule more than one goroutine: call [Sched.Goro] once per
|
||||||
|
// goroutine and drive them as a barrier with [Sched.AwaitAllParked] and
|
||||||
|
// [Sched.YieldToAllParked]. The single-goroutine methods ([Sched.AwaitGoroYield],
|
||||||
|
// [Sched.AwaitGoroYieldOrDone], [Sched.YieldToGoro] and [Sched.Done]) address the
|
||||||
|
// first handle handed out and are the right tool when there is only one.
|
||||||
type Sched struct {
|
type Sched struct {
|
||||||
t testing.TB
|
t testing.TB
|
||||||
|
goros []*schedGoro
|
||||||
|
finishcalled atomic.Bool
|
||||||
|
timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// schedGoro is the per-goroutine handoff state. The channels are shared with the
|
||||||
|
// scheduled goroutine; parked, finished and err are driver-side bookkeeping and
|
||||||
|
// must only ever be touched from the test thread.
|
||||||
|
type schedGoro struct {
|
||||||
// when stack backs off it signals here and waits until channel read or timeout.
|
// when stack backs off it signals here and waits until channel read or timeout.
|
||||||
goroYieldSignal chan struct{}
|
yieldSignal chan struct{}
|
||||||
// when main goroutine is ready for more information this channel is written to to signal waiting on stack activity.
|
// when main goroutine is ready for more information this channel is written to to signal waiting on stack activity.
|
||||||
goroContinueSignal chan struct{}
|
continueSignal chan struct{}
|
||||||
finishChan chan error
|
finishChan chan error
|
||||||
finishcalled atomic.Bool
|
|
||||||
coroCalls atomic.Int32
|
parked bool // goroutine is suspended inside Yield, awaiting a continue.
|
||||||
timeout time.Duration
|
finished bool // goroutine terminated via FinishWithErr.
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// goro0 returns the first handed-out goroutine state, which the single-goroutine
|
||||||
|
// driver methods address.
|
||||||
|
func (ss *Sched) goro0() *schedGoro {
|
||||||
|
if len(ss.goros) == 0 {
|
||||||
|
panic("Sched.Goro must be called before driving the scheduler")
|
||||||
|
}
|
||||||
|
return ss.goros[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
// AwaitGoroYield blocks until the coroutine suspends itself via [SchedGoro.Yield].
|
// AwaitGoroYield blocks until the coroutine suspends itself via [SchedGoro.Yield].
|
||||||
func (ss *Sched) AwaitGoroYield() {
|
func (ss *Sched) AwaitGoroYield() {
|
||||||
|
g := ss.goro0()
|
||||||
select {
|
select {
|
||||||
case <-ss.goroYieldSignal:
|
case <-g.yieldSignal:
|
||||||
|
g.parked = true
|
||||||
case <-time.After(ss.timeout):
|
case <-time.After(ss.timeout):
|
||||||
ss.t.Fatal("timeout waiting for stack to backoff")
|
ss.t.Fatal("timeout waiting for stack to backoff")
|
||||||
}
|
}
|
||||||
@@ -54,10 +78,13 @@ func (ss *Sched) AwaitGoroYield() {
|
|||||||
// the same select, avoiding the deadlock of guessing whether the goroutine will yield
|
// the same select, avoiding the deadlock of guessing whether the goroutine will yield
|
||||||
// again. Do not mix with [Sched.Done] on the same scheduler.
|
// again. Do not mix with [Sched.Done] on the same scheduler.
|
||||||
func (ss *Sched) AwaitGoroYieldOrDone() (done bool, err error) {
|
func (ss *Sched) AwaitGoroYieldOrDone() (done bool, err error) {
|
||||||
|
g := ss.goro0()
|
||||||
select {
|
select {
|
||||||
case <-ss.goroYieldSignal:
|
case <-g.yieldSignal:
|
||||||
|
g.parked = true
|
||||||
return false, nil
|
return false, nil
|
||||||
case err = <-ss.finishChan:
|
case err = <-g.finishChan:
|
||||||
|
g.finished, g.err = true, err
|
||||||
return true, err
|
return true, err
|
||||||
case <-time.After(ss.timeout):
|
case <-time.After(ss.timeout):
|
||||||
ss.t.Fatal("timeout waiting for stack to yield or finish")
|
ss.t.Fatal("timeout waiting for stack to yield or finish")
|
||||||
@@ -67,34 +94,103 @@ func (ss *Sched) AwaitGoroYieldOrDone() (done bool, err error) {
|
|||||||
|
|
||||||
// YieldToGoro wakes a coroutine parked in [SchedGoro.Yield], letting the goroutine run on.
|
// YieldToGoro wakes a coroutine parked in [SchedGoro.Yield], letting the goroutine run on.
|
||||||
func (ss *Sched) YieldToGoro() {
|
func (ss *Sched) YieldToGoro() {
|
||||||
|
g := ss.goro0()
|
||||||
select {
|
select {
|
||||||
case ss.goroContinueSignal <- struct{}{}:
|
case g.continueSignal <- struct{}{}:
|
||||||
|
g.parked = false
|
||||||
case <-time.After(ss.timeout):
|
case <-time.After(ss.timeout):
|
||||||
ss.t.Fatal("timeout while trying to yield to stack")
|
ss.t.Fatal("timeout while trying to yield to stack")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AwaitAllParked blocks until every scheduled goroutine has either suspended
|
||||||
|
// itself in [SchedGoro.Yield] or terminated via [SchedGoro.FinishWithErr]. Once it
|
||||||
|
// returns, no scheduled goroutine is runnable, so the driver may touch state they
|
||||||
|
// share — pumping frames between stacks, advancing a simulated clock — without
|
||||||
|
// racing them. Pair it with [Sched.YieldToAllParked] to step the whole set.
|
||||||
|
//
|
||||||
|
// allFinished reports that every goroutine has terminated, which is the loop's
|
||||||
|
// exit condition; err is the first non-nil terminal error handed over so far.
|
||||||
|
func (ss *Sched) AwaitAllParked() (allFinished bool, err error) {
|
||||||
|
ss.goro0() // Panics if the scheduler has no goroutines to drive.
|
||||||
|
for _, g := range ss.goros {
|
||||||
|
if g.parked || g.finished {
|
||||||
|
continue // Already accounted for; waiting again would deadlock.
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-g.yieldSignal:
|
||||||
|
g.parked = true
|
||||||
|
case gerr := <-g.finishChan:
|
||||||
|
g.finished, g.err = true, gerr
|
||||||
|
case <-time.After(ss.timeout):
|
||||||
|
ss.t.Fatal("timeout waiting for scheduled goroutines to park or finish")
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
allFinished = true
|
||||||
|
for _, g := range ss.goros {
|
||||||
|
if !g.finished {
|
||||||
|
allFinished = false
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = g.err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return allFinished, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// YieldToAllParked wakes every goroutine currently parked in [SchedGoro.Yield],
|
||||||
|
// letting them all run on until they park again. Goroutines that have already
|
||||||
|
// terminated are skipped, so it is safe to call until [Sched.AwaitAllParked]
|
||||||
|
// reports every goroutine finished.
|
||||||
|
func (ss *Sched) YieldToAllParked() {
|
||||||
|
ss.goro0() // Panics if the scheduler has no goroutines to drive.
|
||||||
|
for _, g := range ss.goros {
|
||||||
|
if !g.parked {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case g.continueSignal <- struct{}{}:
|
||||||
|
g.parked = false
|
||||||
|
case <-time.After(ss.timeout):
|
||||||
|
ss.t.Fatal("timeout while trying to yield to scheduled goroutine")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Done returns the channel that receives the coroutine's terminal error from
|
// Done returns the channel that receives the coroutine's terminal error from
|
||||||
// [SchedGoro.FinishWithErr]. It may only be called once.
|
// [SchedGoro.FinishWithErr]. It may only be called once.
|
||||||
func (ss *Sched) Done() <-chan error {
|
func (ss *Sched) Done() <-chan error {
|
||||||
|
g := ss.goro0()
|
||||||
if ss.finishcalled.CompareAndSwap(false, true) {
|
if ss.finishcalled.CompareAndSwap(false, true) {
|
||||||
return ss.finishChan
|
return g.finishChan
|
||||||
}
|
}
|
||||||
panic("Done called twice")
|
panic("Done called twice")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Goro returns the handle whose methods must be called from inside the
|
// Goro returns the handle whose methods must be called from inside the
|
||||||
// scheduled (stack) goroutine.
|
// scheduled (stack) goroutine. Call it once per goroutine to be scheduled, from
|
||||||
|
// the test thread and before those goroutines start: the handles are handed out
|
||||||
|
// unsynchronized. The first handle is the one the single-goroutine driver methods
|
||||||
|
// address; drive two or more with [Sched.AwaitAllParked] and [Sched.YieldToAllParked].
|
||||||
func (ss *Sched) Goro() SchedGoro {
|
func (ss *Sched) Goro() SchedGoro {
|
||||||
if !ss.coroCalls.CompareAndSwap(0, 1) {
|
g := &schedGoro{
|
||||||
panic("only one goroutine supported for now")
|
yieldSignal: make(chan struct{}),
|
||||||
|
continueSignal: make(chan struct{}),
|
||||||
|
finishChan: make(chan error, 1),
|
||||||
}
|
}
|
||||||
return SchedGoro{ss: ss}
|
ss.goros = append(ss.goros, g)
|
||||||
|
return SchedGoro{ss: ss, g: g}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SchedGoro is the coroutine-side handle of a [Sched]. Every method MUST be
|
// SchedGoro is the coroutine-side handle of a [Sched]. Every method MUST be
|
||||||
// called from inside the scheduled goroutine and never from the test thread.
|
// called from inside the scheduled goroutine and never from the test thread.
|
||||||
type SchedGoro struct{ ss *Sched }
|
// It holds its own handoff state directly so the goroutine never reads the
|
||||||
|
// scheduler's handle list, which the test thread may still be appending to.
|
||||||
|
type SchedGoro struct {
|
||||||
|
ss *Sched
|
||||||
|
g *schedGoro
|
||||||
|
}
|
||||||
|
|
||||||
// Yield suspends the goroutine at a backoff point and parks until the driver
|
// Yield suspends the goroutine at a backoff point and parks until the driver
|
||||||
// calls [SchedDriver.YieldToGoro]. Its signature satisfies [lneto.BackoffStrategy] so it
|
// calls [SchedDriver.YieldToGoro]. Its signature satisfies [lneto.BackoffStrategy] so it
|
||||||
@@ -103,12 +199,12 @@ func (c SchedGoro) Yield(consecutiveBackoffs uint) time.Duration {
|
|||||||
ss := c.ss
|
ss := c.ss
|
||||||
timeout := time.After(ss.timeout)
|
timeout := time.After(ss.timeout)
|
||||||
select {
|
select {
|
||||||
case ss.goroYieldSignal <- struct{}{}:
|
case c.g.yieldSignal <- struct{}{}:
|
||||||
case <-timeout:
|
case <-timeout:
|
||||||
ss.t.Fatal("timeout backing off, possible race condition? Multiple stacks using same backoff is unexpected pattern")
|
ss.t.Fatal("timeout backing off, possible race condition? Multiple stacks using same backoff is unexpected pattern")
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case <-ss.goroContinueSignal:
|
case <-c.g.continueSignal:
|
||||||
case <-timeout:
|
case <-timeout:
|
||||||
ss.t.Fatal("timeout waiting for continue")
|
ss.t.Fatal("timeout waiting for continue")
|
||||||
}
|
}
|
||||||
@@ -119,10 +215,10 @@ func (c SchedGoro) Yield(consecutiveBackoffs uint) time.Duration {
|
|||||||
// channel. It must be called at most once.
|
// channel. It must be called at most once.
|
||||||
func (c SchedGoro) FinishWithErr(err error) {
|
func (c SchedGoro) FinishWithErr(err error) {
|
||||||
ss := c.ss
|
ss := c.ss
|
||||||
if len(ss.finishChan) != 0 {
|
if len(c.g.finishChan) != 0 {
|
||||||
ss.t.Fatal("Coro.FinishWithErr can be called once only")
|
ss.t.Fatal("Coro.FinishWithErr can be called once only")
|
||||||
}
|
}
|
||||||
ss.finishChan <- err
|
c.g.finishChan <- err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finish is just shorthand for c.FinishWithErr(nil).
|
// Finish is just shorthand for c.FinishWithErr(nil).
|
||||||
|
|||||||
+14
-2
@@ -157,7 +157,7 @@ func (r *Ring) ReadDiscard(n int) error {
|
|||||||
case n > buffered:
|
case n > buffered:
|
||||||
return errDiscardExceeds
|
return errDiscardExceeds
|
||||||
case n == buffered:
|
case n == buffered:
|
||||||
r.Reset()
|
r.emptied()
|
||||||
case n+r.Off > len(r.Buf):
|
case n+r.Off > len(r.Buf):
|
||||||
r.Off = n - (len(r.Buf) - r.Off)
|
r.Off = n - (len(r.Buf) - r.Off)
|
||||||
default:
|
default:
|
||||||
@@ -224,6 +224,18 @@ func (r *Ring) Reset() {
|
|||||||
r.End = 0
|
r.End = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// emptied marks the ring empty keeping the write position where it is, unlike
|
||||||
|
// [Ring.Reset] which rewinds it to index 0. Bytes staged past that position with
|
||||||
|
// [Ring.PeekWrite] are addressed relative to it, so moving it makes a later
|
||||||
|
// [Ring.Commit] hand back the wrong bytes.
|
||||||
|
func (r *Ring) emptied() {
|
||||||
|
off := r.End
|
||||||
|
if off == len(r.Buf) {
|
||||||
|
off = 0 // Tail exhausted, next write wraps.
|
||||||
|
}
|
||||||
|
r.Off, r.End = off, 0
|
||||||
|
}
|
||||||
|
|
||||||
// Size returns the capacity of the ring buffer.
|
// Size returns the capacity of the ring buffer.
|
||||||
func (r *Ring) Size() int {
|
func (r *Ring) Size() int {
|
||||||
return len(r.Buf)
|
return len(r.Buf)
|
||||||
@@ -306,7 +318,7 @@ func (r *Ring) onReadEnd(totalRead int) {
|
|||||||
}
|
}
|
||||||
newOff := r.addOff(r.Off, totalRead)
|
newOff := r.addOff(r.Off, totalRead)
|
||||||
if newOff == r.End {
|
if newOff == r.End {
|
||||||
r.Reset()
|
r.emptied()
|
||||||
} else if newOff == len(r.Buf) {
|
} else if newOff == len(r.Buf) {
|
||||||
r.Off = 0 // Optimization case.
|
r.Off = 0 // Optimization case.
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -661,3 +661,40 @@ func TestRingPeekWriteRejects(t *testing.T) {
|
|||||||
t.Error("Commit beyond free must error")
|
t.Error("Commit beyond free must error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRingPeekWriteSurvivesEmptyRead checks bytes staged with [Ring.PeekWrite]
|
||||||
|
// survive the ring being read empty, an event the stager does not control.
|
||||||
|
func TestRingPeekWriteSurvivesEmptyRead(t *testing.T) {
|
||||||
|
r := &Ring{Buf: make([]byte, 16)}
|
||||||
|
if _, err := r.Write([]byte("AAAA")); err != nil {
|
||||||
|
t.Fatal("first write:", err)
|
||||||
|
}
|
||||||
|
// Stage "CCCC" one 4-byte gap past the write position.
|
||||||
|
if !r.PeekWrite([]byte("CCCC"), 4) {
|
||||||
|
t.Fatal("PeekWrite should fit")
|
||||||
|
}
|
||||||
|
// Drain everything readable: ring goes empty, staged bytes still pending.
|
||||||
|
got := make([]byte, 16)
|
||||||
|
n, err := r.Read(got)
|
||||||
|
if err != nil || string(got[:n]) != "AAAA" {
|
||||||
|
t.Fatalf("drain read %q (%v), want AAAA", got[:n], err)
|
||||||
|
}
|
||||||
|
if !r.IsEmpty() {
|
||||||
|
t.Fatal("ring should be empty after draining")
|
||||||
|
}
|
||||||
|
// Fill the gap and commit the staged tail.
|
||||||
|
if _, err := r.Write([]byte("BBBB")); err != nil {
|
||||||
|
t.Fatal("gap write:", err)
|
||||||
|
}
|
||||||
|
if err := r.Commit(4); err != nil {
|
||||||
|
t.Fatal("commit:", err)
|
||||||
|
}
|
||||||
|
n, err = r.Read(got)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("read:", err)
|
||||||
|
}
|
||||||
|
if string(got[:n]) != "BBBBCCCC" {
|
||||||
|
t.Fatalf("read %q, want BBBBCCCC: the staged bytes were committed from the wrong offset", got[:n])
|
||||||
|
}
|
||||||
|
testRingSanity(t, r)
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,40 @@ func BytesEqual(a, b []byte) bool {
|
|||||||
return unsafe.String(&a[0], len(a)) == unsafe.String(&b[0], len(b))
|
return unsafe.String(&a[0], len(a)) == unsafe.String(&b[0], len(b))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EqualFoldASCII reports whether a and b are equal under ASCII case folding.
|
||||||
|
// Unlike [strings.EqualFold] it does not fold non-ASCII runes, so no multi-byte
|
||||||
|
// rune such as U+212A KELVIN SIGN can alias an ASCII key.
|
||||||
|
func EqualFoldASCII(a, b string) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const asciiCapDiff = 'a' - 'A'
|
||||||
|
for i := 0; i < len(a); i++ {
|
||||||
|
ca, cb := a[i], b[i]
|
||||||
|
if ca >= 'A' && ca <= 'Z' {
|
||||||
|
ca += asciiCapDiff
|
||||||
|
}
|
||||||
|
if cb >= 'A' && cb <= 'Z' {
|
||||||
|
cb += asciiCapDiff
|
||||||
|
}
|
||||||
|
if ca != cb {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// BytesEqualFoldASCII is the []byte form of [EqualFoldASCII]. Like [BytesEqual]
|
||||||
|
// it is heapless in tinygo, unlike [bytes.EqualFold] which also folds non-ASCII.
|
||||||
|
func BytesEqualFoldASCII(a, b []byte) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
} else if len(a) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return EqualFoldASCII(unsafe.String(&a[0], len(a)), unsafe.String(&b[0], len(b)))
|
||||||
|
}
|
||||||
|
|
||||||
// IsZeroed returns true if all arguments are set to their zero value.
|
// IsZeroed returns true if all arguments are set to their zero value.
|
||||||
func IsZeroed[T comparable](a ...T) bool {
|
func IsZeroed[T comparable](a ...T) bool {
|
||||||
var z T
|
var z T
|
||||||
|
|||||||
@@ -1,5 +1,26 @@
|
|||||||
package internal
|
package internal
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AppendStrDecimal appends pfx followed by value in base 10 to dst and returns
|
||||||
|
// the resulting slice. It condenses the prefixed-number pattern common to
|
||||||
|
// AppendString/AppendText methods, i.e. `internal.AppendStrDecimal(b, " len=", 4)`.
|
||||||
|
func AppendStrDecimal(dst []byte, pfx string, value int64) []byte {
|
||||||
|
dst = append(dst, pfx...)
|
||||||
|
return strconv.AppendInt(dst, value, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppendStrHexData appends pfx followed by data as hexadecimaldata.
|
||||||
|
//
|
||||||
|
// dst = internal.AppendStrHexData(dst, "data=0x", data...) // data=0xdeadbeef
|
||||||
|
func AppendStrHexData(dst []byte, pfx string, data ...byte) []byte {
|
||||||
|
dst = append(dst, pfx...)
|
||||||
|
return hex.AppendEncode(dst, data)
|
||||||
|
}
|
||||||
|
|
||||||
// IntLen returns the number of bytes [strconv.AppendInt] emits for value in the
|
// IntLen returns the number of bytes [strconv.AppendInt] emits for value in the
|
||||||
// given base, including a leading minus sign for negatives. Lets callers size a
|
// given base, including a leading minus sign for negatives. Lets callers size a
|
||||||
// buffer, or test whether a value fits an existing slot, before writing a byte.
|
// buffer, or test whether a value fits an existing slot, before writing a byte.
|
||||||
|
|||||||
@@ -987,16 +987,13 @@ func (frm Frame) AppendString(b []byte) []byte {
|
|||||||
bitlen := frm.LenBits()
|
bitlen := frm.LenBits()
|
||||||
b = append(b, frm.Protocol...)
|
b = append(b, frm.Protocol...)
|
||||||
if bitlen%8 == 0 {
|
if bitlen%8 == 0 {
|
||||||
b = append(b, " len="...)
|
b = internal.AppendStrDecimal(b, " len=", int64(bitlen/8))
|
||||||
b = strconv.AppendInt(b, int64(bitlen/8), 10)
|
|
||||||
} else {
|
} else {
|
||||||
b = append(b, " bits="...)
|
b = internal.AppendStrDecimal(b, " bits=", int64(bitlen))
|
||||||
b = strconv.AppendInt(b, int64(bitlen), 10)
|
|
||||||
}
|
}
|
||||||
iopt, err := frm.FieldByClass(FieldClassOptions)
|
iopt, err := frm.FieldByClass(FieldClassOptions)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
b = append(b, " optlen="...)
|
b = internal.AppendStrDecimal(b, " optlen=", int64((frm.Fields[iopt].BitLength+7)/8))
|
||||||
b = strconv.AppendInt(b, int64((frm.Fields[iopt].BitLength+7)/8), 10)
|
|
||||||
}
|
}
|
||||||
for _, err := range frm.Errors {
|
for _, err := range frm.Errors {
|
||||||
b = append(b, ' ')
|
b = append(b, ' ')
|
||||||
|
|||||||
+15
-12
@@ -2,10 +2,9 @@ package ipv4
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
|
"github.com/soypat/lneto/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewFrame returns a new [Frame] with data set to buf.
|
// NewFrame returns a new [Frame] with data set to buf.
|
||||||
@@ -238,14 +237,18 @@ func (ifrm Frame) ValidateExceptCRC(v *lneto.Validator) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ifrm Frame) String() string {
|
func (ifrm Frame) String() string {
|
||||||
dst := netip.AddrFrom4(*ifrm.DestinationAddr())
|
proto := ifrm.Protocol().String()
|
||||||
src := netip.AddrFrom4(*ifrm.SourceAddr())
|
b := make([]byte, 0, 91+len(proto))
|
||||||
|
b = append(b, "IP ("...)
|
||||||
hl := ifrm.HeaderLength()
|
b = append(b, proto...)
|
||||||
tl := int(ifrm.TotalLength())
|
b = append(b, ") src="...)
|
||||||
ttl := ifrm.TTL()
|
b = AppendFormatAddr(b, *ifrm.SourceAddr())
|
||||||
id := ifrm.ID()
|
b = append(b, " dst="...)
|
||||||
proto := ifrm.Protocol()
|
b = AppendFormatAddr(b, *ifrm.DestinationAddr())
|
||||||
tos := ifrm.ToS()
|
b = internal.AppendStrDecimal(b, " len=", int64(ifrm.TotalLength()))
|
||||||
return fmt.Sprintf("IP %s SRC=%s DST=%s LEN=%d OPT=%d TTL=%d ID=%d ToS=0x%x", proto.String(), src.String(), dst.String(), tl, tl-hl, ttl, id, tos)
|
b = internal.AppendStrDecimal(b, " opt=", int64(ifrm.HeaderLength()-20))
|
||||||
|
b = internal.AppendStrDecimal(b, " ttl=", int64(ifrm.TTL()))
|
||||||
|
b = internal.AppendStrDecimal(b, " id=", int64(ifrm.ID()))
|
||||||
|
b = internal.AppendStrHexData(b, " tos=0x", byte(ifrm.ToS()))
|
||||||
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-15
@@ -76,16 +76,10 @@ type ConnConfig struct {
|
|||||||
// Logger sets the [Conn] logger.
|
// Logger sets the [Conn] logger.
|
||||||
// Lower level logging available at [Handler.SetLoggers] via [Conn.InternalHandler].
|
// Lower level logging available at [Handler.SetLoggers] via [Conn.InternalHandler].
|
||||||
Logger *slog.Logger
|
Logger *slog.Logger
|
||||||
// LossRecovery is the optional packet-loss recovery algorithm (RTO,
|
// Policy is the optional transmit-steering algorithm (RTO, congestion
|
||||||
// congestion control, ...) for the connection. If set, Nanotime must also be
|
// control, ...) for the connection. nil disables it. A Policy needing time
|
||||||
// set (else Configure returns an error). Leaving it nil disables loss
|
// carries its own clock. See [Policy].
|
||||||
// recovery. See [LossRecovery].
|
Policy Policy
|
||||||
LossRecovery LossRecovery
|
|
||||||
// Nanotime is the monotonic time source in nanoseconds (the func() int64
|
|
||||||
// convention used across lneto) that drives LossRecovery. It is required when
|
|
||||||
// LossRecovery is set and unused otherwise. The tcp package reads it only to
|
|
||||||
// stamp the loss-recovery hooks; it holds no clock itself.
|
|
||||||
Nanotime func() int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Configure should be called on any newly created connection before usage. See [ConnConfig].
|
// Configure should be called on any newly created connection before usage. See [ConnConfig].
|
||||||
@@ -93,10 +87,6 @@ func (conn *Conn) Configure(config ConnConfig) (err error) {
|
|||||||
if config.RWBackoff == nil {
|
if config.RWBackoff == nil {
|
||||||
return lneto.ErrMissingHALConfig
|
return lneto.ErrMissingHALConfig
|
||||||
}
|
}
|
||||||
if config.LossRecovery != nil && config.Nanotime == nil {
|
|
||||||
// The tcp package holds no clock: a loss-recovery algorithm cannot run without it.
|
|
||||||
return lneto.ErrInvalidConfig
|
|
||||||
}
|
|
||||||
conn.mu.Lock()
|
conn.mu.Lock()
|
||||||
defer conn.mu.Unlock()
|
defer conn.mu.Unlock()
|
||||||
err = conn.h.SetBuffers(config.TxBuf, config.RxBuf, config.TxPacketQueueSize)
|
err = conn.h.SetBuffers(config.TxBuf, config.RxBuf, config.TxPacketQueueSize)
|
||||||
@@ -105,7 +95,7 @@ func (conn *Conn) Configure(config ConnConfig) (err error) {
|
|||||||
}
|
}
|
||||||
conn._backoff = config.RWBackoff
|
conn._backoff = config.RWBackoff
|
||||||
conn.logger.log = config.Logger
|
conn.logger.log = config.Logger
|
||||||
conn.h.SetLossRecovery(config.LossRecovery, config.Nanotime)
|
conn.h.SetPolicy(config.Policy)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+40
-12
@@ -3,7 +3,6 @@ package tcp
|
|||||||
import (
|
import (
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/soypat/lneto/internal"
|
"github.com/soypat/lneto/internal"
|
||||||
@@ -95,6 +94,12 @@ func (tcb *ControlBlock) RecvWindow() Size { return tcb.rcv.WND }
|
|||||||
// ISS returns the initial sequence number of the connection that was defined on a call to Open by user.
|
// ISS returns the initial sequence number of the connection that was defined on a call to Open by user.
|
||||||
func (tcb *ControlBlock) ISS() Value { return tcb.snd.ISS }
|
func (tcb *ControlBlock) ISS() Value { return tcb.snd.ISS }
|
||||||
|
|
||||||
|
// SendUNA returns snd.UNA, the oldest sequence number not yet acked by the remote.
|
||||||
|
func (tcb *ControlBlock) SendUNA() Value { return tcb.snd.UNA }
|
||||||
|
|
||||||
|
// SendNext returns snd.NXT, one past the highest sequence number sent.
|
||||||
|
func (tcb *ControlBlock) SendNext() Value { return tcb.snd.NXT }
|
||||||
|
|
||||||
// MaxInFlightData returns the maximum size of a segment that can be sent by taking into account
|
// MaxInFlightData returns the maximum size of a segment that can be sent by taking into account
|
||||||
// the send window size and the unacked data. Returns 0 before StateSynRcvd.
|
// the send window size and the unacked data. Returns 0 before StateSynRcvd.
|
||||||
func (tcb *ControlBlock) MaxInFlightData() Size {
|
func (tcb *ControlBlock) MaxInFlightData() Size {
|
||||||
@@ -224,7 +229,7 @@ func (tcb *ControlBlock) Open(iss Value, wnd Size) (err error) {
|
|||||||
switch {
|
switch {
|
||||||
case tcb._state != StateClosed && tcb._state != StateTimeWait:
|
case tcb._state != StateClosed && tcb._state != StateTimeWait:
|
||||||
err = errNeedClosedTCBToOpen
|
err = errNeedClosedTCBToOpen
|
||||||
case wnd > math.MaxUint16:
|
case wnd > maxWindow:
|
||||||
err = errWindowTooLarge
|
err = errWindowTooLarge
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -257,14 +262,34 @@ func (tcb *ControlBlock) HasPendingRetransmit() bool {
|
|||||||
return tcb._state.TxDataOpen() && tcb.dupack >= retransmitAfterDupacks && tcb.nRetransmit <= tcb.dupack-retransmitAfterDupacks
|
return tcb._state.TxDataOpen() && tcb.dupack >= retransmitAfterDupacks && tcb.nRetransmit <= tcb.dupack-retransmitAfterDupacks
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RetransmitFrom rewinds snd.NXT back to newNxt so the next PendingSegment and
|
||||||
|
// Send calls retransmit unacknowledged data from that sequence number onwards.
|
||||||
|
// It must be paired with ringTx.RetransmitFrom to rewind the transmit buffer to
|
||||||
|
// the same point. Implements RFC 9293 §3.10.8 (RETRANSMISSION TIMEOUT).
|
||||||
|
//
|
||||||
|
// It reports false and changes nothing when newNxt falls outside the
|
||||||
|
// unacknowledged range [snd.UNA, snd.NXT] or the connection cannot send data, so
|
||||||
|
// a misbehaving [Policy] cannot corrupt the send sequence space.
|
||||||
|
func (tcb *ControlBlock) RetransmitFrom(newNxt Value) bool {
|
||||||
|
if !tcb._state.txQueuedDataOpen() {
|
||||||
|
// Matches [State.TxDataOpen] and other states that may have data queued to make progress.
|
||||||
|
// Matches [ControlBlock.PendingSegment] gate (RFC 9293 §3.10.8).
|
||||||
|
return false
|
||||||
|
} else if newNxt.LessThan(tcb.snd.UNA) || tcb.snd.NXT.LessThan(newNxt) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
tcb.snd.NXT = newNxt
|
||||||
|
tcb.dupack = 0
|
||||||
|
tcb.nRetransmit = 0
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// RetransmitAll rewinds snd.NXT back to snd.UNA so the next PendingSegment and
|
// RetransmitAll rewinds snd.NXT back to snd.UNA so the next PendingSegment and
|
||||||
// Send calls retransmit all unacknowledged data from the oldest sequence number
|
// Send calls retransmit all unacknowledged data from the oldest sequence number
|
||||||
// (go-back-N). It must be paired with ringTx.RetransmitFromUNA to rewind the
|
// (go-back-N). It must be paired with ringTx.RetransmitFromUNA to rewind the
|
||||||
// transmit buffer. Implements RFC 9293 §3.10.8 (RETRANSMISSION TIMEOUT).
|
// transmit buffer. Implements RFC 9293 §3.10.8 (RETRANSMISSION TIMEOUT).
|
||||||
func (tcb *ControlBlock) RetransmitAll() {
|
func (tcb *ControlBlock) RetransmitAll() {
|
||||||
tcb.snd.NXT = tcb.snd.UNA
|
tcb.RetransmitFrom(tcb.snd.UNA)
|
||||||
tcb.dupack = 0
|
|
||||||
tcb.nRetransmit = 0
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PendingSegment calculates a suitable next segment to send from a payload length.
|
// PendingSegment calculates a suitable next segment to send from a payload length.
|
||||||
@@ -279,10 +304,9 @@ func (tcb *ControlBlock) PendingSegment(payloadLen int) (_ Segment, ok bool) {
|
|||||||
// Optimist Strategy: retransmit oldest data once.
|
// Optimist Strategy: retransmit oldest data once.
|
||||||
return Segment{SEQ: tcb.snd.UNA, DATALEN: Size(payloadLen), ACK: tcb.rcv.NXT, WND: tcb.rcv.WND, Flags: FlagACK}, true
|
return Segment{SEQ: tcb.snd.UNA, DATALEN: Size(payloadLen), ACK: tcb.rcv.NXT, WND: tcb.rcv.WND, Flags: FlagACK}, true
|
||||||
}
|
}
|
||||||
established := tcb._state == StateEstablished
|
canSendData := tcb._state.txQueuedDataOpen()
|
||||||
canSendData := established || tcb._state == StateCloseWait
|
|
||||||
if !canSendData {
|
if !canSendData {
|
||||||
payloadLen = 0 // Can't send data if not established or close-wait.
|
payloadLen = 0 // No send-buffer data may go out in this state.
|
||||||
}
|
}
|
||||||
if pending == 0 && payloadLen == 0 {
|
if pending == 0 && payloadLen == 0 {
|
||||||
return Segment{}, false // No pending segment.
|
return Segment{}, false // No pending segment.
|
||||||
@@ -510,7 +534,7 @@ func (tcb *ControlBlock) validateOutgoingSegment(seg Segment) (err error) {
|
|||||||
switch {
|
switch {
|
||||||
case tcb._state == StateClosed && !isFirst:
|
case tcb._state == StateClosed && !isFirst:
|
||||||
err = io.ErrClosedPipe
|
err = io.ErrClosedPipe
|
||||||
case seg.WND > math.MaxUint16:
|
case seg.WND > maxWindow:
|
||||||
err = errWindowTooLarge
|
err = errWindowTooLarge
|
||||||
case hasAck && seg.ACK != tcb.rcv.NXT:
|
case hasAck && seg.ACK != tcb.rcv.NXT:
|
||||||
err = errAckNotNext
|
err = errAckNotNext
|
||||||
@@ -522,8 +546,12 @@ func (tcb *ControlBlock) validateOutgoingSegment(seg Segment) (err error) {
|
|||||||
err = errSeqNotInWindow
|
err = errSeqNotInWindow
|
||||||
}
|
}
|
||||||
|
|
||||||
case seg.DATALEN > 0 && (tcb._state == StateFinWait1 || tcb._state == StateFinWait2):
|
case seg.DATALEN > 0 && tcb._state == StateFinWait2:
|
||||||
err = errConnectionClosing // Case 1: No further SENDs from the user will be accepted by the TCP implementation.
|
// FIN-WAIT-2 means our FIN was acknowledged, so no data below it can be
|
||||||
|
// unacknowledged and data here is a caller error. FIN-WAIT-1 is excluded:
|
||||||
|
// its FIN sits above data the peer may still be missing, which must go out
|
||||||
|
// for either side to make progress (RFC 9293 §3.10.8).
|
||||||
|
err = errConnectionClosing
|
||||||
|
|
||||||
case checkSeq && tcb.snd.WND == 0 && seg.DATALEN > 0 && seg.SEQ == tcb.snd.NXT:
|
case checkSeq && tcb.snd.WND == 0 && seg.DATALEN > 0 && seg.SEQ == tcb.snd.NXT:
|
||||||
err = errZeroWindow
|
err = errZeroWindow
|
||||||
@@ -549,7 +577,7 @@ func (tcb *ControlBlock) validateIncomingSegment(seg Segment) (err error) {
|
|||||||
zeroWindowOK := tcb.rcv.WND == 0 && seg.DATALEN == 0 && seg.SEQ == tcb.rcv.NXT
|
zeroWindowOK := tcb.rcv.WND == 0 && seg.DATALEN == 0 && seg.SEQ == tcb.rcv.NXT
|
||||||
// See section 3.4 of RFC 9293 for more on these checks.
|
// See section 3.4 of RFC 9293 for more on these checks.
|
||||||
switch {
|
switch {
|
||||||
case seg.WND > math.MaxUint16:
|
case seg.WND > maxWindow:
|
||||||
err = errWindowOverflow
|
err = errWindowOverflow
|
||||||
case tcb._state == StateClosed:
|
case tcb._state == StateClosed:
|
||||||
err = io.ErrClosedPipe
|
err = io.ErrClosedPipe
|
||||||
|
|||||||
+23
-6
@@ -2,19 +2,19 @@ package tcp
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"math/bits"
|
"math/bits"
|
||||||
"strconv"
|
"strconv"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
|
"github.com/soypat/lneto/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:generate stringer -type=State,OptionKind -linecomment -output stringers.go .
|
//go:generate stringer -type=State,OptionKind -linecomment -output stringers.go .
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errDropSegment error = lneto.ErrPacketDrop
|
errDropSegment error = lneto.ErrPacketDrop
|
||||||
errWindowTooLarge = errors.New("invalid window size > 2**16")
|
errWindowTooLarge = errors.New("invalid window size > max scaled window")
|
||||||
|
|
||||||
errBufferTooSmall error = lneto.ErrShortBuffer
|
errBufferTooSmall error = lneto.ErrShortBuffer
|
||||||
errNeedClosedTCBToOpen = errors.New("need closed TCB to call open")
|
errNeedClosedTCBToOpen = errors.New("need closed TCB to call open")
|
||||||
@@ -25,7 +25,7 @@ var (
|
|||||||
errBadSegack = errors.New("seqs:bad segack")
|
errBadSegack = errors.New("seqs:bad segack")
|
||||||
errFinwaitExpectedACK = errors.New("seqs:finwait1 expected ACK")
|
errFinwaitExpectedACK = errors.New("seqs:finwait1 expected ACK")
|
||||||
|
|
||||||
errWindowOverflow = newRejectErr("wnd > 2**16")
|
errWindowOverflow = newRejectErr("wnd > max scaled window")
|
||||||
errSeqNotInWindow = newRejectErr("seq not in snd/rcv.wnd")
|
errSeqNotInWindow = newRejectErr("seq not in snd/rcv.wnd")
|
||||||
errZeroWindow = newRejectErr("zero window")
|
errZeroWindow = newRejectErr("zero window")
|
||||||
errLastNotInWindow = newRejectErr("last not in snd/rcv.wnd")
|
errLastNotInWindow = newRejectErr("last not in snd/rcv.wnd")
|
||||||
@@ -73,10 +73,19 @@ func (seg Segment) isFirstSYN() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (seg Segment) String() string {
|
func (seg Segment) String() string {
|
||||||
if seg.DATALEN == 0 {
|
return string(seg.AppendString(nil))
|
||||||
return fmt.Sprintf("SEG %s ACK=%d SEQ=%d WND=%d", seg.Flags, seg.ACK, seg.SEQ, seg.WND)
|
}
|
||||||
|
|
||||||
|
func (seg Segment) AppendString(b []byte) []byte {
|
||||||
|
b = append(b, "SEG "...)
|
||||||
|
b = append(b, seg.Flags.String()...)
|
||||||
|
b = internal.AppendStrDecimal(b, " ACK=", int64(seg.ACK))
|
||||||
|
b = internal.AppendStrDecimal(b, " SEQ=", int64(seg.SEQ))
|
||||||
|
b = internal.AppendStrDecimal(b, " WND=", int64(seg.WND))
|
||||||
|
if seg.DATALEN > 0 {
|
||||||
|
b = internal.AppendStrDecimal(b, " DATALEN=", int64(seg.DATALEN))
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("SEG %s ACK=%d SEQ=%d WND=%d DATALEN=%d", seg.Flags, seg.ACK, seg.SEQ, seg.WND, seg.DATALEN)
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClientSynSegment is a the first packet sent over a TCP connection to a server. Typically the client
|
// ClientSynSegment is a the first packet sent over a TCP connection to a server. Typically the client
|
||||||
@@ -329,6 +338,14 @@ func (s State) TxDataOpen() bool {
|
|||||||
return s == StateEstablished || s == StateCloseWait
|
return s == StateEstablished || s == StateCloseWait
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// txQueuedDataOpen returns true if already-queued send-buffer data may still be
|
||||||
|
// put on the wire. It stays true after a local close, where the FIN occupies a
|
||||||
|
// sequence above data the peer has not acknowledged: until that data is
|
||||||
|
// (re)transmitted the peer cannot reach the FIN. RFC 9293 §3.10.8.
|
||||||
|
func (s State) txQueuedDataOpen() bool {
|
||||||
|
return s.TxDataOpen() || s == StateFinWait1 || s == StateClosing || s == StateLastAck
|
||||||
|
}
|
||||||
|
|
||||||
// RxDataOpen returns true if the state allows the receiving of incoming data segments.
|
// RxDataOpen returns true if the state allows the receiving of incoming data segments.
|
||||||
// Combine with [State.IsPreestablished] to know whether there is no more data to be received over the network.
|
// Combine with [State.IsPreestablished] to know whether there is no more data to be received over the network.
|
||||||
func (s State) RxDataOpen() bool {
|
func (s State) RxDataOpen() bool {
|
||||||
|
|||||||
+7
-2
@@ -2,10 +2,10 @@ package tcp
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
|
||||||
"math"
|
"math"
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
|
"github.com/soypat/lneto/internal"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -170,7 +170,12 @@ func (tfrm Frame) String() string {
|
|||||||
src := tfrm.SourcePort()
|
src := tfrm.SourcePort()
|
||||||
dst := tfrm.DestinationPort()
|
dst := tfrm.DestinationPort()
|
||||||
seg := tfrm.Segment(len(tfrm.Payload()))
|
seg := tfrm.Segment(len(tfrm.Payload()))
|
||||||
return fmt.Sprintf("TCP :%d -> :%d %s", src, dst, seg.String())
|
b := make([]byte, 0, 64)
|
||||||
|
b = append(b, "TCP "...)
|
||||||
|
b = internal.AppendStrDecimal(b, " src=", int64(src))
|
||||||
|
b = internal.AppendStrDecimal(b, " dst=", int64(dst))
|
||||||
|
b = append(b, ' ')
|
||||||
|
return string(seg.AppendString(b))
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|||||||
+153
-64
@@ -29,16 +29,18 @@ type Handler struct {
|
|||||||
// Read and Write calls belong to the current connection.
|
// Read and Write calls belong to the current connection.
|
||||||
|
|
||||||
optcodec OptionCodec
|
optcodec OptionCodec
|
||||||
|
// Window scaling (RFC 7323 §2). wndShiftLocal is derived from the receive
|
||||||
|
// buffer in [Handler.SetBuffers], wndShiftPeer learned from the peer's offer.
|
||||||
|
// Scaling lives at the wire seam only: the ControlBlock always holds real
|
||||||
|
// octet counts, converted on frame read ([Handler.Recv]) and write
|
||||||
|
// ([Handler.wireWnd]).
|
||||||
|
wndShiftLocal uint8
|
||||||
|
wndShiftPeer uint8
|
||||||
|
peerOfferedWS bool
|
||||||
// reasm tracks out-of-order segments staged in bufRx's free region. Always
|
// reasm tracks out-of-order segments staged in bufRx's free region. Always
|
||||||
// enabled once buffers are set (see [Handler.SetBuffers]).
|
// enabled once buffers are set (see [Handler.SetBuffers]).
|
||||||
reasm reassembly
|
reasm reassembly
|
||||||
// loss is the optional packet-loss recovery algorithm (RTO, congestion
|
policy Policy
|
||||||
// control, ...) driven from the rx/tx hooks. nil disables loss recovery, in
|
|
||||||
// which case the connection behaves as if no timing existed. nanotime is the
|
|
||||||
// monotonic time source (nanoseconds) passed to those hooks; it is non-nil
|
|
||||||
// whenever loss is non-nil (enforced by [Conn.Configure]). See [LossRecovery].
|
|
||||||
loss LossRecovery
|
|
||||||
nanotime func() int64
|
|
||||||
|
|
||||||
closing bool
|
closing bool
|
||||||
shutdownRx bool
|
shutdownRx bool
|
||||||
@@ -74,32 +76,22 @@ func (h *Handler) SetBuffers(txbuf, rxbuf []byte, packets int) error {
|
|||||||
h.bufRx.Buf = rxbuf
|
h.bufRx.Buf = rxbuf
|
||||||
}
|
}
|
||||||
h.scb.SetRecvWindow(Size(h.bufRx.Size()))
|
h.scb.SetRecvWindow(Size(h.bufRx.Size()))
|
||||||
|
h.wndShiftLocal = wndShiftFor(h.bufRx.Size())
|
||||||
h.bufRx.Reset()
|
h.bufRx.Reset()
|
||||||
h.reasm.reset(maxReasmSegments)
|
h.reasm.reset(maxReasmSegments)
|
||||||
return h.bufTx.ResetOrReuse(txbuf, packets, 0)
|
return h.bufTx.ResetOrReuse(txbuf, packets, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetLossRecovery installs the packet-loss recovery algorithm and the monotonic
|
// SetPolicy installs the transmit-steering algorithm. nil disables it.
|
||||||
// time source (nanoseconds, the func() int64 convention used across lneto) that
|
// It should be set before the connection is opened. See [Policy].
|
||||||
// drives it. The tcp package keeps no clock of its own; nanotime is read only to
|
func (h *Handler) SetPolicy(policy Policy) {
|
||||||
// stamp the rx/tx hooks (see [LossRecovery]). Passing loss == nil disables loss
|
h.policy = policy
|
||||||
// recovery. It should be set before the connection is opened.
|
|
||||||
func (h *Handler) SetLossRecovery(loss LossRecovery, nanotime func() int64) {
|
|
||||||
h.loss = loss
|
|
||||||
h.nanotime = nanotime
|
|
||||||
}
|
}
|
||||||
|
func (h *Handler) policyEnabled() bool { return h.policy != nil }
|
||||||
|
|
||||||
func (h *Handler) lossEnabled() bool { return h.loss != nil }
|
// ControlBlock returns the state machine underlying the Handler, mainly so a
|
||||||
|
// [Policy] can read the sequence spaces. Not for modification.
|
||||||
// NextDeadline returns the monotonic-nanosecond instant at which the connection
|
func (h *Handler) ControlBlock() *ControlBlock { return &h.scb }
|
||||||
// must next be serviced by a transmit attempt (e.g. an RTO expiry), or 0 when
|
|
||||||
// there is no deadline or no loss recovery is configured. See [LossRecovery].
|
|
||||||
func (h *Handler) NextDeadline() int64 {
|
|
||||||
if h.loss == nil {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
return h.loss.NextDeadline()
|
|
||||||
}
|
|
||||||
|
|
||||||
// LocalPort returns the local port of the connection. Returns 0 if the connection is closed and uninitialized.
|
// LocalPort returns the local port of the connection. Returns 0 if the connection is closed and uninitialized.
|
||||||
func (h *Handler) LocalPort() uint16 {
|
func (h *Handler) LocalPort() uint16 {
|
||||||
@@ -164,17 +156,17 @@ func (h *Handler) reset(localPort, remotePort uint16, iss Value) {
|
|||||||
closing: false,
|
closing: false,
|
||||||
shutdownRx: false,
|
shutdownRx: false,
|
||||||
// Persist configuration across reopen:
|
// Persist configuration across reopen:
|
||||||
validator: h.validator,
|
validator: h.validator,
|
||||||
loss: h.loss,
|
policy: h.policy,
|
||||||
nanotime: h.nanotime,
|
logger: h.logger,
|
||||||
logger: h.logger,
|
wndShiftLocal: h.wndShiftLocal, // derived from buffers, which persist too
|
||||||
// persist memory across repoen:
|
// persist memory across repoen:
|
||||||
bufTx: h.bufTx,
|
bufTx: h.bufTx,
|
||||||
bufRx: h.bufRx,
|
bufRx: h.bufRx,
|
||||||
reasm: h.reasm,
|
reasm: h.reasm,
|
||||||
}
|
}
|
||||||
if h.lossEnabled() {
|
if h.policyEnabled() {
|
||||||
h.loss.Reset()
|
h.policy.Reset()
|
||||||
}
|
}
|
||||||
h.reasm.clear() // preserve metadata capacity across reopen, drop held segments.
|
h.reasm.clear() // preserve metadata capacity across reopen, drop held segments.
|
||||||
h.bufTx.ResetOrReuse(nil, 0, iss)
|
h.bufTx.ResetOrReuse(nil, 0, iss)
|
||||||
@@ -207,14 +199,18 @@ func (h *Handler) Recv(incomingPacket []byte) error {
|
|||||||
}
|
}
|
||||||
payload := tfrm.Payload()
|
payload := tfrm.Payload()
|
||||||
segIncoming := tfrm.Segment(len(payload))
|
segIncoming := tfrm.Segment(len(payload))
|
||||||
|
if h.peerOfferedWS && !segIncoming.Flags.HasAny(FlagSYN) {
|
||||||
|
// Peer windows arrive scaled once both sides offered scaling, but never on
|
||||||
|
// SYN segments (RFC 7323 §2.2). Restore real octets before the
|
||||||
|
// ControlBlock sees them.
|
||||||
|
segIncoming.WND <<= h.wndShiftPeer
|
||||||
|
}
|
||||||
if h.scb.IncomingIsKeepalive(segIncoming) {
|
if h.scb.IncomingIsKeepalive(segIncoming) {
|
||||||
h.info("tcp.Handler:rx-keepalive", slog.Uint64("port", uint64(h.localPort)))
|
h.info("tcp.Handler:rx-keepalive", slog.Uint64("port", uint64(h.localPort)))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify loss recovery of the received segment (RTT sampling, timer
|
if h.policyEnabled() && !h.policy.PreRx(h, tfrm) {
|
||||||
// management) and let it drop the segment before processing if it asks to.
|
|
||||||
if h.lossEnabled() && !h.loss.PreRx(segIncoming, h.nanotime()).Keep {
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,6 +241,9 @@ func (h *Handler) Recv(incomingPacket []byte) error {
|
|||||||
if prevState != h.scb.State() {
|
if prevState != h.scb.State() {
|
||||||
h.info("tcp.Handler:rx-statechange", slog.Uint64("port", uint64(h.localPort)), slog.String("old", prevState.String()), slog.String("new", h.scb.State().String()), slog.String("rxflags", segIncoming.Flags.String()))
|
h.info("tcp.Handler:rx-statechange", slog.Uint64("port", uint64(h.localPort)), slog.String("old", prevState.String()), slog.String("new", h.scb.State().String()), slog.String("rxflags", segIncoming.Flags.String()))
|
||||||
}
|
}
|
||||||
|
if h.policyEnabled() {
|
||||||
|
h.policy.PostRx(h, prevState, tfrm)
|
||||||
|
}
|
||||||
if segIncoming.DATALEN != 0 && h.shutdownRx && (h.scb.State() == StateFinWait1 || h.scb.State() == StateFinWait2) {
|
if segIncoming.DATALEN != 0 && h.shutdownRx && (h.scb.State() == StateFinWait1 || h.scb.State() == StateFinWait2) {
|
||||||
// soypat/lneto#50: the application is done in both directions — read side
|
// soypat/lneto#50: the application is done in both directions — read side
|
||||||
// shut down (CloseRead) and our FIN sent (Close) — so inbound data has no
|
// shut down (CloseRead) and our FIN sent (Close) — so inbound data has no
|
||||||
@@ -283,6 +282,11 @@ func (h *Handler) Recv(incomingPacket []byte) error {
|
|||||||
h.scb.snd.MSS = Size(mss)
|
h.scb.snd.MSS = Size(mss)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if kind == OptWindowScale && len(data) == 1 {
|
||||||
|
// RFC 7323 §2.3: a shift above 14 is clamped, not rejected.
|
||||||
|
h.peerOfferedWS = true
|
||||||
|
h.wndShiftPeer = min(data[0], maxWndShift)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if h.remotePort == 0 {
|
if h.remotePort == 0 {
|
||||||
@@ -380,16 +384,31 @@ func (h *Handler) Send(b []byte) (int, error) {
|
|||||||
if h.IsTxOver() {
|
if h.IsTxOver() {
|
||||||
return 0, net.ErrClosed
|
return 0, net.ErrClosed
|
||||||
}
|
}
|
||||||
var now int64
|
tfrm, err := NewFrame(b)
|
||||||
if h.lossEnabled() {
|
if err != nil {
|
||||||
now = h.nanotime()
|
return 0, err
|
||||||
if h.loss.PreTx(now).RetransmitAll {
|
}
|
||||||
// Go-back-N retransmission directed by loss recovery: rewind the
|
offset := uint8(5)
|
||||||
// send sequence and transmit buffer so unacknowledged data is resent
|
txLimit := TransmitUnlimited
|
||||||
// from snd.UNA. Done before the early short-circuit below so an
|
if h.policyEnabled() {
|
||||||
// expired RTO retransmits even with no new data queued.
|
// Hand the Policy a defined frame: zeroed header at the minimum offset.
|
||||||
h.scb.RetransmitAll()
|
// It may append options and raise the offset, which is read back below.
|
||||||
h.bufTx.RetransmitFromUNA()
|
tfrm.ClearHeader()
|
||||||
|
tfrm.SetOffsetAndFlags(offset, 0)
|
||||||
|
limit, rtxFrom, doRtx := h.policy.PreTx(h, tfrm)
|
||||||
|
txLimit = limit
|
||||||
|
if limit == 0 {
|
||||||
|
h.info("tcp.Policy:newTxLimit=0") // Can cause headaches for users.
|
||||||
|
}
|
||||||
|
if doRtx && h.scb.RetransmitFrom(rtxFrom) {
|
||||||
|
// Retransmission directed by the Policy: rewind the transmit buffer
|
||||||
|
// to match the send sequence so unacknowledged data is resent. Done
|
||||||
|
// before the early short-circuit below so an expired RTO
|
||||||
|
// retransmits even with no new data queued.
|
||||||
|
h.bufTx.RetransmitFrom(rtxFrom)
|
||||||
|
}
|
||||||
|
if o, _ := tfrm.OffsetAndFlags(); o > offset && int(o)*4 < len(b) {
|
||||||
|
offset = o
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
awaitingSyn := h.AwaitingSynSend()
|
awaitingSyn := h.AwaitingSynSend()
|
||||||
@@ -405,30 +424,27 @@ func (h *Handler) Send(b []byte) (int, error) {
|
|||||||
// Early nop short circuit.
|
// Early nop short circuit.
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
tfrm, err := NewFrame(b)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
if buffered == 0 && h.closing && (h.scb.State() != StateCloseWait || !h.scb.HasPending()) {
|
if buffered == 0 && h.closing && (h.scb.State() != StateCloseWait || !h.scb.HasPending()) {
|
||||||
// If Close called and no more data to be sent, terminate connection.
|
// If Close called and no more data to be sent, terminate connection.
|
||||||
// In CLOSE-WAIT: wait until the pending ACK is sent first, since scb.Close()
|
// In CLOSE-WAIT: wait until the pending ACK is sent first, since scb.Close()
|
||||||
// overwrites pending with [FIN|ACK] (unlike ESTABLISHED which merges via bitmask).
|
// overwrites pending with [FIN|ACK] (unlike ESTABLISHED which merges via bitmask).
|
||||||
h.closing = false
|
h.closing = false
|
||||||
err = h.scb.Close()
|
err := h.scb.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.logerr("tcp.Handler.Close", slog.String("err", errstr(err)), slog.String("state", h.State().String()))
|
h.logerr("tcp.Handler.Close", slog.String("err", errstr(err)), slog.String("state", h.State().String()))
|
||||||
h.Abort()
|
h.Abort()
|
||||||
return 0, io.EOF
|
return 0, io.EOF
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
offset := uint8(5)
|
// optHead is where the Handler's own options begin: after the fixed header
|
||||||
mss := uint16(len(b) - sizeHeaderTCP)
|
// and after any options the Policy already wrote, so neither clobbers the other.
|
||||||
|
optHead := int(offset) * 4
|
||||||
|
mss := uint16(len(b) - optHead)
|
||||||
var segment Segment
|
var segment Segment
|
||||||
if awaitingSyn || requeueControl && h.scb.State() == StateSynSent {
|
if awaitingSyn || requeueControl && h.scb.State() == StateSynSent {
|
||||||
// Handling init syn segment.
|
// Handling init syn segment.
|
||||||
segment = ClientSynSegment(h.bufTx.iss, Size(h.bufRx.Size()))
|
segment = ClientSynSegment(h.bufTx.iss, Size(h.bufRx.Size()))
|
||||||
h.optcodec.PutOption16(b[sizeHeaderTCP:], OptMaxSegmentSize, mss)
|
offset += h.putSynOptions(b[optHead:], mss, false)
|
||||||
offset++
|
|
||||||
if requeueControl {
|
if requeueControl {
|
||||||
h.info("tcp.Handler:requeue-syn", slog.Uint64("port", uint64(h.localPort)), slog.Uint64("rport", uint64(h.remotePort)))
|
h.info("tcp.Handler:requeue-syn", slog.Uint64("port", uint64(h.localPort)), slog.Uint64("rport", uint64(h.remotePort)))
|
||||||
}
|
}
|
||||||
@@ -439,25 +455,27 @@ func (h *Handler) Send(b []byte) (int, error) {
|
|||||||
WND: Size(h.bufRx.Free()),
|
WND: Size(h.bufRx.Free()),
|
||||||
Flags: synack,
|
Flags: synack,
|
||||||
}
|
}
|
||||||
h.optcodec.PutOption16(b[sizeHeaderTCP:], OptMaxSegmentSize, mss)
|
offset += h.putSynOptions(b[optHead:], mss, true)
|
||||||
offset++
|
|
||||||
h.info("tcp.Handler:requeue-synack", slog.Uint64("port", uint64(h.localPort)), slog.Uint64("rport", uint64(h.remotePort)))
|
h.info("tcp.Handler:requeue-synack", slog.Uint64("port", uint64(h.localPort)), slog.Uint64("rport", uint64(h.remotePort)))
|
||||||
} else if requeueControl {
|
} else if requeueControl {
|
||||||
h.requeueControl = false
|
h.requeueControl = false
|
||||||
return 0, nil
|
return 0, nil
|
||||||
} else {
|
} else {
|
||||||
var ok bool
|
var ok bool
|
||||||
maxPayload := len(b) - sizeHeaderTCP
|
maxPayload := len(b) - optHead
|
||||||
|
if txLimit < Size(maxPayload) && !h.nextSegmentIsRetransmit() {
|
||||||
|
// Policy clamped new data.
|
||||||
|
maxPayload = int(txLimit)
|
||||||
|
}
|
||||||
segment, ok = h.scb.PendingSegment(maxPayload)
|
segment, ok = h.scb.PendingSegment(maxPayload)
|
||||||
segment.WND = h.recvWindow()
|
segment.WND = h.recvWindow()
|
||||||
if !ok {
|
if !ok {
|
||||||
// No pending control segment or data to send. Yield.
|
// No pending control segment or data to send. Yield.
|
||||||
return 0, nil
|
return 0, nil
|
||||||
} else if segment.Flags == synack {
|
} else if segment.Flags == synack {
|
||||||
h.optcodec.PutOption16(b[sizeHeaderTCP:], OptMaxSegmentSize, mss)
|
offset += h.putSynOptions(b[optHead:], mss, true)
|
||||||
offset++
|
|
||||||
} else if segment.DATALEN > 0 {
|
} else if segment.DATALEN > 0 {
|
||||||
n, err := h.bufTx.MakePacket(b[sizeHeaderTCP:sizeHeaderTCP+segment.DATALEN], segment.SEQ)
|
n, err := h.bufTx.MakePacket(b[optHead:optHead+int(segment.DATALEN)], segment.SEQ)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
@@ -474,15 +492,20 @@ func (h *Handler) Send(b []byte) (int, error) {
|
|||||||
} else if prevState != h.scb.State() && h.logenabled(slog.LevelInfo) {
|
} else if prevState != h.scb.State() && h.logenabled(slog.LevelInfo) {
|
||||||
h.info("tcp.Handler:tx-statechange", slog.Uint64("port", uint64(h.localPort)), slog.String("oldState", prevState.String()), slog.String("newState", h.scb.State().String()), slog.String("txflags", segment.Flags.String()))
|
h.info("tcp.Handler:tx-statechange", slog.Uint64("port", uint64(h.localPort)), slog.String("oldState", prevState.String()), slog.String("newState", h.scb.State().String()), slog.String("txflags", segment.Flags.String()))
|
||||||
}
|
}
|
||||||
if h.lossEnabled() {
|
|
||||||
h.loss.PostTx(segment, now)
|
|
||||||
}
|
|
||||||
h.requeueControl = false
|
h.requeueControl = false
|
||||||
tfrm.SetSourcePort(h.localPort)
|
tfrm.SetSourcePort(h.localPort)
|
||||||
tfrm.SetDestinationPort(h.remotePort)
|
tfrm.SetDestinationPort(h.remotePort)
|
||||||
|
segment.WND = h.wireWnd(segment) // wire representation only; scb keeps real octets
|
||||||
tfrm.SetSegment(segment, offset)
|
tfrm.SetSegment(segment, offset)
|
||||||
tfrm.SetUrgentPtr(0)
|
tfrm.SetUrgentPtr(0)
|
||||||
datalen := int(offset)*4 + int(segment.DATALEN)
|
datalen := int(offset)*4 + int(segment.DATALEN)
|
||||||
|
if h.policyEnabled() {
|
||||||
|
// Frame trimmed to what is actually emitted so the Policy's Payload()
|
||||||
|
// is the segment data and nothing more.
|
||||||
|
if sent, err := NewFrame(b[:datalen]); err == nil {
|
||||||
|
h.policy.PostTx(h, sent)
|
||||||
|
}
|
||||||
|
}
|
||||||
closedSuccess := prevState == StateTimeWait && segment.Flags.HasAny(FlagACK)
|
closedSuccess := prevState == StateTimeWait && segment.Flags.HasAny(FlagACK)
|
||||||
if closedSuccess {
|
if closedSuccess {
|
||||||
h.reset(0, 0, 0)
|
h.reset(0, 0, 0)
|
||||||
@@ -494,6 +517,27 @@ func (h *Handler) Send(b []byte) (int, error) {
|
|||||||
return datalen, nil
|
return datalen, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nextSegmentIsRetransmit reports whether the next data segment would resend
|
||||||
|
// already-transmitted bytes rather than open new sequence space. Used to let a
|
||||||
|
// retransmission through while a [Policy] holds new data back.
|
||||||
|
func (h *Handler) nextSegmentIsRetransmit() bool {
|
||||||
|
endSeq, hasSent := h.bufTx.sentEndSeq()
|
||||||
|
return hasSent && h.scb.snd.NXT.LessThan(endSeq)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextSegmentSYN returns syn=true if next outgoing segment is a handshake SYN.
|
||||||
|
// This method is exported for use by [Policy] implementations to decide handshake-only options (window scale, SACK-permitted, timestamps).
|
||||||
|
func (h *Handler) NextSegmentSYN() (syn, ack bool) {
|
||||||
|
state := h.scb.State()
|
||||||
|
if h.AwaitingSynSend() || h.requeueControl && state == StateSynSent {
|
||||||
|
return true, false // SYN initial/requeue.
|
||||||
|
} else if h.requeueControl && state == StateSynRcvd {
|
||||||
|
return true, true // SYNACK requeue.
|
||||||
|
}
|
||||||
|
pending := h.scb.pending[0]
|
||||||
|
return pending.HasAny(FlagSYN), pending.HasAny(FlagACK)
|
||||||
|
}
|
||||||
|
|
||||||
// Write implements [io.Writer] by copying b to a internal buffer to be sent over the network on the next
|
// Write implements [io.Writer] by copying b to a internal buffer to be sent over the network on the next
|
||||||
// [Handler.Send] call that can send data to remote peer. Use [Handler.Free] to know the maximum length the argument slice can be before erroring.
|
// [Handler.Send] call that can send data to remote peer. Use [Handler.Free] to know the maximum length the argument slice can be before erroring.
|
||||||
func (h *Handler) Write(b []byte) (int, error) {
|
func (h *Handler) Write(b []byte) (int, error) {
|
||||||
@@ -598,6 +642,51 @@ func (h *Handler) recvWindow() Size {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// maxWndShift is the RFC 7323 §2.2/§2.3 cap on the window-scale shift count and
|
||||||
|
// maxWindow the largest window it permits: the 16-bit wire field at that shift.
|
||||||
|
const (
|
||||||
|
maxWndShift = 14
|
||||||
|
maxWindow = 0xFFFF << maxWndShift
|
||||||
|
)
|
||||||
|
|
||||||
|
// wndShiftFor returns the smallest window-scale shift with which a receive
|
||||||
|
// buffer of bufSize octets can be advertised in the 16-bit window field.
|
||||||
|
func wndShiftFor(bufSize int) (shift uint8) {
|
||||||
|
for shift < maxWndShift && bufSize>>shift > 0xFFFF {
|
||||||
|
shift++
|
||||||
|
}
|
||||||
|
return shift
|
||||||
|
}
|
||||||
|
|
||||||
|
// putSynOptions writes the option block shared by SYN and SYN-ACK segments.
|
||||||
|
// MSS always, then the NOP-padded window-scale offer. An active SYN always
|
||||||
|
// offers scaling, since a zero shift still lets the peer scale its own window
|
||||||
|
// (RFC 7323 §2.5). A SYN-ACK echoes the offer only when the peer's SYN carried
|
||||||
|
// it (§2.2). Returns the number of 32-bit header words written.
|
||||||
|
func (h *Handler) putSynOptions(b []byte, mss uint16, isSynack bool) uint8 {
|
||||||
|
h.optcodec.PutOption16(b, OptMaxSegmentSize, mss)
|
||||||
|
words := uint8(1)
|
||||||
|
if (!isSynack || h.peerOfferedWS) && len(b) >= 8 {
|
||||||
|
b[4] = byte(OptNop)
|
||||||
|
h.optcodec.PutOption(b[5:], OptWindowScale, h.wndShiftLocal)
|
||||||
|
words++
|
||||||
|
}
|
||||||
|
return words
|
||||||
|
}
|
||||||
|
|
||||||
|
// wireWnd converts a segment's real window to its on-wire representation.
|
||||||
|
// SYN segments are never scaled (RFC7323 §2.2), we cap SYN windows at maxuint16.
|
||||||
|
func (h *Handler) wireWnd(seg Segment) Size {
|
||||||
|
wnd := seg.WND
|
||||||
|
if h.peerOfferedWS && !seg.Flags.HasAny(FlagSYN) {
|
||||||
|
wnd >>= h.wndShiftLocal
|
||||||
|
}
|
||||||
|
if wnd > 0xFFFF {
|
||||||
|
wnd = 0xFFFF
|
||||||
|
}
|
||||||
|
return wnd
|
||||||
|
}
|
||||||
|
|
||||||
// AwaitingSynResponse returns true if the Handler is an active client opened with [Handler.OpenActive] and has already sent out the first SYN packet to the remote client.
|
// AwaitingSynResponse returns true if the Handler is an active client opened with [Handler.OpenActive] and has already sent out the first SYN packet to the remote client.
|
||||||
func (h *Handler) AwaitingSynResponse() bool {
|
func (h *Handler) AwaitingSynResponse() bool {
|
||||||
return h.remotePort != 0 && h.scb.State() == StateSynSent
|
return h.remotePort != 0 && h.scb.State() == StateSynSent
|
||||||
|
|||||||
-83
@@ -1,83 +0,0 @@
|
|||||||
package tcp
|
|
||||||
|
|
||||||
// LossRecovery abstracts TCP packet-loss recovery: RTO, congestion control and
|
|
||||||
// any similar algorithm that observes segment traffic and steers the
|
|
||||||
// connection's transmit behaviour. As far as the tcp package is concerned these
|
|
||||||
// are all the same thing — packet-loss recovery algorithms — so they share one
|
|
||||||
// interface (see discussion #157).
|
|
||||||
//
|
|
||||||
// The tcp package stays free of any time source: the current monotonic time in
|
|
||||||
// nanoseconds (the func() int64 convention used across lneto) is passed in at
|
|
||||||
// each hook boundary. It originates from [ConnConfig.Nanotime] and satisfies the
|
|
||||||
// "WHEN was this segment rx/tx'd" requirement without a clock living inside the
|
|
||||||
// state machine, which also keeps implementations deterministic for testing
|
|
||||||
// (see issue #140).
|
|
||||||
//
|
|
||||||
// The interface is intentionally free of errors: an implementation handles or
|
|
||||||
// reports its own errors rather than propagating them into lneto internals.
|
|
||||||
//
|
|
||||||
// Introspection (smoothed RTT, current window, ...) is deliberately left off the
|
|
||||||
// interface; expose it on the concrete implementation the caller constructs and
|
|
||||||
// hands to [ConnConfig].
|
|
||||||
type LossRecovery interface {
|
|
||||||
// Reset returns the implementation to its initial, pre-connection state. It
|
|
||||||
// is invoked whenever the connection is (re)opened or aborted so a single
|
|
||||||
// LossRecovery value can be reused across the lifetime of connection reuse
|
|
||||||
// (see discussion #115).
|
|
||||||
Reset()
|
|
||||||
|
|
||||||
// NextDeadline returns the monotonic-nanosecond instant at which the
|
|
||||||
// connection must next be serviced by a transmit attempt — typically the RTO
|
|
||||||
// expiry. A return of 0 means there is no pending deadline. It replaces a
|
|
||||||
// poll/atomic-flag scheme with a deadline the caller's event loop can
|
|
||||||
// schedule against.
|
|
||||||
NextDeadline() int64
|
|
||||||
|
|
||||||
// PreRx is called for every segment received on the TCP port before the
|
|
||||||
// state machine processes it, with the monotonic time the segment arrived. It
|
|
||||||
// returns whether the segment should be kept (processed) or dropped.
|
|
||||||
PreRx(incoming Segment, now int64) RxDirective
|
|
||||||
|
|
||||||
// PreTx is called on entering the transmit path (Encapsulate), before a
|
|
||||||
// segment is built, with the current monotonic time. Its directive tells the
|
|
||||||
// connection whether to retransmit unacknowledged data, rewind the send
|
|
||||||
// pointer, or hold back new data.
|
|
||||||
PreTx(now int64) TxDirective
|
|
||||||
|
|
||||||
// PostTx is called on leaving the transmit path with the segment that was
|
|
||||||
// actually emitted and the monotonic time it was sent. This is where segment
|
|
||||||
// timing (for RTT sampling and the retransmission timer) is recorded.
|
|
||||||
PostTx(outgoing Segment, now int64)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TxDirective is returned by [LossRecovery.PreTx] to steer the transmit path.
|
|
||||||
// The zero value directs the connection to proceed normally (send new data if
|
|
||||||
// available, no retransmission).
|
|
||||||
type TxDirective struct {
|
|
||||||
// RewindNXT is the number of sequence-space octets to rewind snd.NXT by
|
|
||||||
// before transmitting, for partial (e.g. selective) retransmission. Zero
|
|
||||||
// means no rewind. It is independent of Retransmit, which rewinds fully to
|
|
||||||
// snd.UNA.
|
|
||||||
// RewindNXT uint32
|
|
||||||
|
|
||||||
// RetransmitAll requests go-back-N retransmission: the connection rewinds
|
|
||||||
// snd.NXT to snd.UNA and resends unacknowledged data from the oldest
|
|
||||||
// sequence number.
|
|
||||||
RetransmitAll bool
|
|
||||||
// HoldNew pauses transmission of new data (for example when the congestion
|
|
||||||
// window is exhausted). Retransmissions already directed by this same
|
|
||||||
// directive still proceed.
|
|
||||||
// HoldNew bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// RxDirective is returned by [LossRecovery.PreRx].
|
|
||||||
//
|
|
||||||
// NOTE: its shape is the minimum viable contract — it mirrors the original
|
|
||||||
// PreRx "keep" boolean from discussion #157 — and is the one element of the
|
|
||||||
// interface not yet fully settled there. It is a struct (rather than a bare
|
|
||||||
// bool) so fields can be added without breaking implementations.
|
|
||||||
type RxDirective struct {
|
|
||||||
// Keep reports whether the received segment should be handed to the state
|
|
||||||
// machine. A false value drops the segment before it is processed.
|
|
||||||
Keep bool
|
|
||||||
}
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
package tcp
|
|
||||||
|
|
||||||
import (
|
|
||||||
"math/rand"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/soypat/lneto/ethernet"
|
|
||||||
)
|
|
||||||
|
|
||||||
// recordingLoss is a test LossRecovery that records every hook invocation and
|
|
||||||
// lets the test steer the directives returned to the Handler. It is the
|
|
||||||
// interface counterpart driven by the Handler under test.
|
|
||||||
type recordingLoss struct {
|
|
||||||
resets int
|
|
||||||
preRx []hookCall
|
|
||||||
preTx []int64
|
|
||||||
postTx []hookCall
|
|
||||||
deadline int64 // value NextDeadline reports back.
|
|
||||||
|
|
||||||
// Directives handed back to the Handler.
|
|
||||||
keep bool // PreRx result. Default true (see newRecordingLoss).
|
|
||||||
tx TxDirective // PreTx result.
|
|
||||||
}
|
|
||||||
|
|
||||||
type hookCall struct {
|
|
||||||
seg Segment
|
|
||||||
now int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRecordingLoss() *recordingLoss { return &recordingLoss{keep: true} }
|
|
||||||
|
|
||||||
var _ LossRecovery = (*recordingLoss)(nil)
|
|
||||||
|
|
||||||
func (l *recordingLoss) Reset() { l.resets++ }
|
|
||||||
func (l *recordingLoss) NextDeadline() int64 { return l.deadline }
|
|
||||||
|
|
||||||
func (l *recordingLoss) PreRx(incoming Segment, now int64) RxDirective {
|
|
||||||
l.preRx = append(l.preRx, hookCall{seg: incoming, now: now})
|
|
||||||
return RxDirective{Keep: l.keep}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *recordingLoss) PreTx(now int64) TxDirective {
|
|
||||||
l.preTx = append(l.preTx, now)
|
|
||||||
return l.tx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *recordingLoss) PostTx(outgoing Segment, now int64) {
|
|
||||||
l.postTx = append(l.postTx, hookCall{seg: outgoing, now: now})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_DisabledByDefault verifies the Handler runs normally with no
|
|
||||||
// loss recovery installed: NextDeadline reports no deadline and the transmit/
|
|
||||||
// receive paths never touch a nil LossRecovery.
|
|
||||||
func TestLossRecovery_DisabledByDefault(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
rng := rand.New(rand.NewSource(1))
|
|
||||||
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
|
||||||
setupClientServer(t, rng, client, server)
|
|
||||||
|
|
||||||
if d := client.NextDeadline(); d != 0 {
|
|
||||||
t.Fatalf("NextDeadline with no loss recovery = %d, want 0", d)
|
|
||||||
}
|
|
||||||
var buf [mtu]byte
|
|
||||||
establish(t, client, server, buf[:]) // must not panic on nil loss recovery.
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_HooksInvoked verifies the Handler drives the full hook
|
|
||||||
// contract across a handshake: Reset on open, PreTx+PostTx on every transmit,
|
|
||||||
// PreRx on every receive, each stamped with the configured monotonic clock.
|
|
||||||
func TestLossRecovery_HooksInvoked(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
rng := rand.New(rand.NewSource(2))
|
|
||||||
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
|
||||||
|
|
||||||
loss := newRecordingLoss()
|
|
||||||
const clockNow = 1_000_000
|
|
||||||
client.SetLossRecovery(loss, func() int64 { return clockNow })
|
|
||||||
|
|
||||||
setupClientServer(t, rng, client, server) // OpenActive → reset → Reset().
|
|
||||||
if loss.resets == 0 {
|
|
||||||
t.Fatal("Reset not called on open")
|
|
||||||
}
|
|
||||||
|
|
||||||
var buf [mtu]byte
|
|
||||||
establish(t, client, server, buf[:])
|
|
||||||
|
|
||||||
// Client emitted SYN and the final ACK: both paths must have hit PreTx/PostTx.
|
|
||||||
if len(loss.preTx) == 0 {
|
|
||||||
t.Fatal("PreTx never called on transmit")
|
|
||||||
}
|
|
||||||
if len(loss.postTx) == 0 {
|
|
||||||
t.Fatal("PostTx never called on transmit")
|
|
||||||
}
|
|
||||||
if len(loss.preTx) != len(loss.postTx) {
|
|
||||||
t.Fatalf("PreTx calls=%d, PostTx calls=%d, want equal", len(loss.preTx), len(loss.postTx))
|
|
||||||
}
|
|
||||||
// Client received the SYN-ACK: PreRx must have seen it.
|
|
||||||
if len(loss.preRx) == 0 {
|
|
||||||
t.Fatal("PreRx never called on receive")
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Handler holds no clock: every hook must be stamped from the supplied
|
|
||||||
// nanotime source.
|
|
||||||
for i, c := range loss.postTx {
|
|
||||||
if c.now != clockNow {
|
|
||||||
t.Fatalf("PostTx[%d].now = %d, want clock %d", i, c.now, clockNow)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for i, now := range loss.preTx {
|
|
||||||
if now != clockNow {
|
|
||||||
t.Fatalf("PreTx[%d].now = %d, want clock %d", i, now, clockNow)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for i, c := range loss.preRx {
|
|
||||||
if c.now != clockNow {
|
|
||||||
t.Fatalf("PreRx[%d].now = %d, want clock %d", i, c.now, clockNow)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// PostTx receives the segment actually emitted: the first is the SYN.
|
|
||||||
if !loss.postTx[0].seg.Flags.HasAny(FlagSYN) {
|
|
||||||
t.Fatalf("first PostTx segment flags=%s, want SYN", loss.postTx[0].seg.Flags)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_NextDeadlineDelegates verifies NextDeadline is forwarded to
|
|
||||||
// the installed LossRecovery unchanged.
|
|
||||||
func TestLossRecovery_NextDeadlineDelegates(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
rng := rand.New(rand.NewSource(3))
|
|
||||||
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
|
||||||
|
|
||||||
loss := newRecordingLoss()
|
|
||||||
loss.deadline = 4242
|
|
||||||
client.SetLossRecovery(loss, func() int64 { return 1 })
|
|
||||||
setupClientServer(t, rng, client, server)
|
|
||||||
|
|
||||||
if d := client.NextDeadline(); d != 4242 {
|
|
||||||
t.Fatalf("NextDeadline = %d, want delegated 4242", d)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_PreRxDropsSegment verifies a PreRx directive of Keep=false
|
|
||||||
// drops the segment before the state machine sees it: the payload is not
|
|
||||||
// buffered and connection state is untouched.
|
|
||||||
func TestLossRecovery_PreRxDropsSegment(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
rng := rand.New(rand.NewSource(4))
|
|
||||||
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
|
||||||
|
|
||||||
loss := newRecordingLoss()
|
|
||||||
server.SetLossRecovery(loss, func() int64 { return 1 })
|
|
||||||
setupClientServer(t, rng, client, server)
|
|
||||||
var buf [mtu]byte
|
|
||||||
establish(t, client, server, buf[:]) // keep=true so handshake completes.
|
|
||||||
|
|
||||||
// Now start dropping everything the server receives.
|
|
||||||
loss.keep = false
|
|
||||||
preRxBefore := len(loss.preRx)
|
|
||||||
|
|
||||||
data := []byte("dropme")
|
|
||||||
if _, err := client.Write(data); err != nil {
|
|
||||||
t.Fatal("client write:", err)
|
|
||||||
}
|
|
||||||
clear(buf[:])
|
|
||||||
n, err := client.Send(buf[:])
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("client send:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := server.Recv(buf[:n]); err != nil {
|
|
||||||
t.Fatalf("dropped segment must return nil, got %v", err)
|
|
||||||
}
|
|
||||||
if len(loss.preRx) != preRxBefore+1 {
|
|
||||||
t.Fatalf("PreRx calls=%d, want %d (segment must reach PreRx)", len(loss.preRx), preRxBefore+1)
|
|
||||||
}
|
|
||||||
if server.BufferedInput() != 0 {
|
|
||||||
t.Fatalf("dropped segment must not be buffered, got %d bytes", server.BufferedInput())
|
|
||||||
}
|
|
||||||
if server.State() != StateEstablished {
|
|
||||||
t.Fatalf("dropped segment must not change state, got %s", server.State())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_PreTxRetransmitAll verifies a PreTx directive of
|
|
||||||
// RetransmitAll drives go-back-N: the Handler rewinds and re-emits already-sent,
|
|
||||||
// unacknowledged data from snd.UNA on the next transmit.
|
|
||||||
func TestLossRecovery_PreTxRetransmitAll(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
rng := rand.New(rand.NewSource(5))
|
|
||||||
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
|
||||||
|
|
||||||
loss := newRecordingLoss()
|
|
||||||
client.SetLossRecovery(loss, func() int64 { return 1 })
|
|
||||||
setupClientServer(t, rng, client, server)
|
|
||||||
var buf [mtu]byte
|
|
||||||
establish(t, client, server, buf[:])
|
|
||||||
|
|
||||||
// Emit one data segment; server never ACKs, so it stays unacknowledged.
|
|
||||||
data := []byte("payload")
|
|
||||||
if _, err := client.Write(data); err != nil {
|
|
||||||
t.Fatal("client write:", err)
|
|
||||||
}
|
|
||||||
clear(buf[:])
|
|
||||||
n, err := client.Send(buf[:])
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("client send data:", err)
|
|
||||||
}
|
|
||||||
if n <= sizeHeaderTCP {
|
|
||||||
t.Fatal("expected data segment")
|
|
||||||
}
|
|
||||||
firstSeg := mustSegment(t, buf[:n], n-sizeHeaderTCP)
|
|
||||||
|
|
||||||
// Direct go-back-N on the next transmit.
|
|
||||||
loss.tx = TxDirective{RetransmitAll: true}
|
|
||||||
clear(buf[:])
|
|
||||||
n, err = client.Send(buf[:])
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal("client send retransmit:", err)
|
|
||||||
}
|
|
||||||
if n <= sizeHeaderTCP {
|
|
||||||
t.Fatal("expected retransmitted data segment")
|
|
||||||
}
|
|
||||||
rtSeg := mustSegment(t, buf[:n], n-sizeHeaderTCP)
|
|
||||||
|
|
||||||
if rtSeg.SEQ != firstSeg.SEQ {
|
|
||||||
t.Fatalf("retransmit SEQ=%d, want original UNA SEQ=%d (go-back-N)", rtSeg.SEQ, firstSeg.SEQ)
|
|
||||||
}
|
|
||||||
if rtSeg.DATALEN != firstSeg.DATALEN {
|
|
||||||
t.Fatalf("retransmit DATALEN=%d, want %d", rtSeg.DATALEN, firstSeg.DATALEN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestLossRecovery_ResetOnReopen verifies Reset fires on every (re)open and on
|
|
||||||
// Abort, so a single LossRecovery value can be reused across connection reuse.
|
|
||||||
func TestLossRecovery_ResetOnReopen(t *testing.T) {
|
|
||||||
const mtu = ethernet.MaxMTU
|
|
||||||
client := newHandler(t, mtu, 3)
|
|
||||||
loss := newRecordingLoss()
|
|
||||||
client.SetLossRecovery(loss, func() int64 { return 1 })
|
|
||||||
|
|
||||||
if err := client.OpenActive(1234, 5678, 0); err != nil {
|
|
||||||
t.Fatal("open 1:", err)
|
|
||||||
}
|
|
||||||
afterOpen := loss.resets
|
|
||||||
if afterOpen == 0 {
|
|
||||||
t.Fatal("Reset not called on first open")
|
|
||||||
}
|
|
||||||
|
|
||||||
client.Abort()
|
|
||||||
if loss.resets <= afterOpen {
|
|
||||||
t.Fatalf("Reset not called on Abort: resets=%d, want >%d", loss.resets, afterOpen)
|
|
||||||
}
|
|
||||||
afterAbort := loss.resets
|
|
||||||
|
|
||||||
if err := client.OpenActive(1234, 5678, 0); err != nil {
|
|
||||||
t.Fatal("open 2:", err)
|
|
||||||
}
|
|
||||||
if loss.resets <= afterAbort {
|
|
||||||
t.Fatalf("Reset not called on reopen: resets=%d, want >%d", loss.resets, afterAbort)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+61
-45
@@ -82,7 +82,7 @@ func (op OptionCodec) PutOption16(dst []byte, kind OptionKind, v uint16) (int, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (op OptionCodec) PutOption32(dst []byte, kind OptionKind, v uint32) (int, error) {
|
func (op OptionCodec) PutOption32(dst []byte, kind OptionKind, v uint32) (int, error) {
|
||||||
return op.PutOption(dst, kind, byte(v>>24), byte(v>>16), byte(v>>7), byte(v))
|
return op.PutOption(dst, kind, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (op OptionCodec) PutOption(dst []byte, kind OptionKind, data ...byte) (int, error) {
|
func (op OptionCodec) PutOption(dst []byte, kind OptionKind, data ...byte) (int, error) {
|
||||||
@@ -100,49 +100,65 @@ func (op OptionCodec) PutOption(dst []byte, kind OptionKind, data ...byte) (int,
|
|||||||
return putSize, nil
|
return putSize, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (op OptionCodec) ForEachOption(opts []byte, fn func(OptionKind, []byte) error) error {
|
// Next parses the next option in opts and returns it along with the remaining buffer.
|
||||||
off := 0
|
// Will skip obsolete options and can validate given flags are set.
|
||||||
skipSizeValidation := op.Flags.HasAny(OptFlagSkipSizeValidation)
|
// Parser must stop calling Next after [OptEnd] returned.
|
||||||
skipObsolete := op.Flags.HasAny(OptFlagSkipObsolete)
|
func (op OptionCodec) Next(opts []byte) (kind OptionKind, optData, remainingOpts []byte, err error) {
|
||||||
for off < len(opts) && opts[off] != 0 {
|
REDO:
|
||||||
kind := OptionKind(opts[off])
|
if len(opts) == 0 || opts[0] == 0 {
|
||||||
off++
|
return OptEnd, nil, nil, nil
|
||||||
if kind == OptNop {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if len(opts[off:]) < 1 {
|
|
||||||
return lneto.ErrTruncatedFrame
|
|
||||||
}
|
|
||||||
size := int(opts[off]) // Total option length including kind and length bytes.
|
|
||||||
off++
|
|
||||||
dataLen := size - 2 // Data bytes after kind and length.
|
|
||||||
if dataLen < 0 || len(opts[off:]) < dataLen {
|
|
||||||
return lneto.ErrTruncatedFrame
|
|
||||||
}
|
|
||||||
|
|
||||||
if !skipSizeValidation {
|
|
||||||
expectSize := -1
|
|
||||||
switch kind {
|
|
||||||
case OptTimestamps:
|
|
||||||
expectSize = 10
|
|
||||||
case OptMaxSegmentSize, OptUserTimeout:
|
|
||||||
expectSize = 4
|
|
||||||
case OptWindowScale:
|
|
||||||
expectSize = 3
|
|
||||||
case OptSACKPermitted:
|
|
||||||
expectSize = 2
|
|
||||||
}
|
|
||||||
if expectSize != -1 && size != expectSize {
|
|
||||||
return lneto.ErrInvalidLengthField
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !(skipObsolete && kind.IsObsolete()) {
|
|
||||||
err := fn(kind, opts[off:off+dataLen])
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
off += dataLen
|
|
||||||
}
|
}
|
||||||
return nil
|
var size int
|
||||||
|
kind = OptionKind(opts[0])
|
||||||
|
if kind == OptNop {
|
||||||
|
return kind, nil, opts[1:], nil
|
||||||
|
} else if len(opts) == 1 {
|
||||||
|
return kind, nil, nil, lneto.ErrTruncatedFrame
|
||||||
|
}
|
||||||
|
size = int(opts[1])
|
||||||
|
if size > len(opts) {
|
||||||
|
return kind, nil, nil, lneto.ErrTruncatedFrame
|
||||||
|
} else if size < 2 {
|
||||||
|
return kind, nil, nil, lneto.ErrInvalidLengthField
|
||||||
|
}
|
||||||
|
optData = opts[2:size]
|
||||||
|
remainingOpts = opts[size:]
|
||||||
|
if op.Flags.HasAny(OptFlagSkipObsolete) && kind.IsObsolete() {
|
||||||
|
opts = remainingOpts
|
||||||
|
goto REDO
|
||||||
|
}
|
||||||
|
if !op.Flags.HasAny(OptFlagSkipSizeValidation) {
|
||||||
|
var expectSize int
|
||||||
|
switch kind {
|
||||||
|
case OptTimestamps:
|
||||||
|
expectSize = 10
|
||||||
|
case OptMaxSegmentSize, OptUserTimeout:
|
||||||
|
expectSize = 4
|
||||||
|
case OptWindowScale:
|
||||||
|
expectSize = 3
|
||||||
|
case OptSACKPermitted:
|
||||||
|
expectSize = 2
|
||||||
|
}
|
||||||
|
if expectSize != 0 && size != expectSize {
|
||||||
|
err = lneto.ErrInvalidLengthField
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return kind, optData, remainingOpts, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForEachOption calls fn on all non-End/Nop options in opts. Will skip obsolete options if flag set.
|
||||||
|
func (op OptionCodec) ForEachOption(opts []byte, fn func(OptionKind, []byte) error) (err error) {
|
||||||
|
var kind OptionKind = 1
|
||||||
|
var data []byte
|
||||||
|
for kind != 0 {
|
||||||
|
kind, data, opts, err = op.Next(opts)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
} else if kind <= OptNop {
|
||||||
|
continue
|
||||||
|
} else if err = fn(kind, data); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
// TransmitUnlimited size returned by [Policy.PreTx] to signal no new data transmit limit (no congestion control).
|
||||||
|
const TransmitUnlimited = ^Size(0)
|
||||||
|
|
||||||
|
// Policy observes segment traffic and steers transmit behaviour: RTO,
|
||||||
|
// congestion control and the like (discussion #157). The tcp package holds no
|
||||||
|
// clock, so a Policy needing time carries its own (issue #140).
|
||||||
|
type Policy interface {
|
||||||
|
// Reset returns the Policy to its pre-connection state. Should be called on every
|
||||||
|
// Open/Listen on connection creation. Configuration like clock setting and fine tuning
|
||||||
|
// should persist throughout the Policy lifetime after Reset calls.
|
||||||
|
Reset()
|
||||||
|
|
||||||
|
// PreTx is called before writing to a frame.
|
||||||
|
// The outgoing frame options can be set by the Policy and will be respected if Frame offset >5.
|
||||||
|
// Keep in mind Handler will add options PreTx already added, these options are best overwritten in PostTx.
|
||||||
|
// retransmitFrom is ignored unless within [snd.UNA, snd.NXT] and returned retransmit==true.
|
||||||
|
// newTransmitLimit sets the maximum number of new bytes to send over the wire (congestion control).
|
||||||
|
// If not implementing congestion control then newTransmitLimit=[TransmitUnlimited].
|
||||||
|
PreTx(h *Handler, outgoingOpts Frame) (newTransmitLimit Size, retransmitFrom Value, retransmit bool)
|
||||||
|
// PostTx called on leaving the transmit path with the fully written frame.
|
||||||
|
// PostTx can strategically overwrite options normally set by Handler like MSS, Window scaling which
|
||||||
|
// ends up being more ergonomic than adding them in PreTx and then de-duplicating them in PostTx.
|
||||||
|
PostTx(h *Handler, outgoing Frame)
|
||||||
|
|
||||||
|
// PreRx is called by [Handler] on every incoming segment.
|
||||||
|
// PreRx can choose to drop segment if it returns keep=false.
|
||||||
|
PreRx(h *Handler, incoming Frame) (keep bool)
|
||||||
|
// PostRx is called by [Handler] after accepting an incoming segment.
|
||||||
|
// To access [ControlBlock.SendUNA] before incoming frame was processed save UNA in PreRx.
|
||||||
|
PostRx(h *Handler, prevState State, accepted Frame)
|
||||||
|
}
|
||||||
@@ -0,0 +1,449 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
)
|
||||||
|
|
||||||
|
// recordingPolicy records every hook invocation and lets the test steer what is
|
||||||
|
// returned to the Handler. It is the [Policy] counterpart driven by the Handler
|
||||||
|
// under test.
|
||||||
|
type recordingPolicy struct {
|
||||||
|
resets int
|
||||||
|
preRx []Segment
|
||||||
|
preTx int
|
||||||
|
postRx []Segment
|
||||||
|
postTx []txRecord
|
||||||
|
|
||||||
|
// Values handed back to the Handler.
|
||||||
|
keep bool // PreRx result. Default true (see newRecordingPolicy).
|
||||||
|
rtxFrom Value
|
||||||
|
retransmit bool
|
||||||
|
txLimit Size // PreTx new-data limit. Default TransmitUnlimited (see newRecordingPolicy).
|
||||||
|
// writeOpts, when non-empty, is appended as TCP options by PreTx.
|
||||||
|
writeOpts []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// txRecord is what PostTx observed on the emitted frame.
|
||||||
|
type txRecord struct {
|
||||||
|
seg Segment
|
||||||
|
offset uint8
|
||||||
|
sport uint16
|
||||||
|
dport uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRecordingPolicy() *recordingPolicy {
|
||||||
|
return &recordingPolicy{keep: true, txLimit: TransmitUnlimited}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Policy = (*recordingPolicy)(nil)
|
||||||
|
|
||||||
|
func (p *recordingPolicy) Reset() { p.resets++ }
|
||||||
|
|
||||||
|
func (p *recordingPolicy) PreRx(h *Handler, incoming Frame) bool {
|
||||||
|
p.preRx = append(p.preRx, incoming.Segment(len(incoming.Payload())))
|
||||||
|
return p.keep
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *recordingPolicy) PostRx(h *Handler, prevState State, accepted Frame) {
|
||||||
|
p.postRx = append(p.postRx, accepted.Segment(len(accepted.Payload())))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *recordingPolicy) PreTx(h *Handler, outgoingOpts Frame) (Size, Value, bool) {
|
||||||
|
p.preTx++
|
||||||
|
if len(p.writeOpts) > 0 {
|
||||||
|
// Raise the offset first: Options() is sized from it.
|
||||||
|
words := uint8(5 + (len(p.writeOpts)+3)/4)
|
||||||
|
outgoingOpts.SetOffsetAndFlags(words, 0)
|
||||||
|
copy(outgoingOpts.Options(), p.writeOpts)
|
||||||
|
}
|
||||||
|
return p.txLimit, p.rtxFrom, p.retransmit
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *recordingPolicy) PostTx(h *Handler, outgoing Frame) {
|
||||||
|
offset, _ := outgoing.OffsetAndFlags()
|
||||||
|
p.postTx = append(p.postTx, txRecord{
|
||||||
|
seg: outgoing.Segment(len(outgoing.Payload())),
|
||||||
|
offset: offset,
|
||||||
|
sport: outgoing.SourcePort(),
|
||||||
|
dport: outgoing.DestinationPort(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_DisabledByDefault verifies the Handler runs normally with no Policy
|
||||||
|
// installed: the transmit and receive paths never touch a nil Policy.
|
||||||
|
func TestPolicy_DisabledByDefault(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(1))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:]) // must not panic on nil Policy.
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_HooksInvoked verifies the Handler drives the full hook contract
|
||||||
|
// across a handshake: Reset on open, PreTx+PostTx on transmit, PreRx+PostRx on
|
||||||
|
// receive.
|
||||||
|
func TestPolicy_HooksInvoked(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(2))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
|
||||||
|
setupClientServer(t, rng, client, server) // OpenActive → reset → Reset().
|
||||||
|
if pol.resets == 0 {
|
||||||
|
t.Fatal("Reset not called on open")
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
if pol.preTx == 0 {
|
||||||
|
t.Fatal("PreTx never called on transmit")
|
||||||
|
}
|
||||||
|
if len(pol.postTx) == 0 {
|
||||||
|
t.Fatal("PostTx never called on transmit")
|
||||||
|
}
|
||||||
|
if pol.preTx < len(pol.postTx) {
|
||||||
|
t.Fatalf("PreTx calls=%d < PostTx calls=%d: PostTx must never fire without PreTx", pol.preTx, len(pol.postTx))
|
||||||
|
}
|
||||||
|
// Client received the SYN-ACK and accepted it.
|
||||||
|
if len(pol.preRx) == 0 {
|
||||||
|
t.Fatal("PreRx never called on receive")
|
||||||
|
}
|
||||||
|
if len(pol.postRx) == 0 {
|
||||||
|
t.Fatal("PostRx never called on accepted receive")
|
||||||
|
}
|
||||||
|
// PostTx receives the segment actually emitted: the first is the SYN.
|
||||||
|
if !pol.postTx[0].seg.Flags.HasAny(FlagSYN) {
|
||||||
|
t.Fatalf("first PostTx segment flags=%s, want SYN", pol.postTx[0].seg.Flags)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_PostTxSeesWrittenFrame verifies PostTx observes the fully populated
|
||||||
|
// frame — ports, sequence numbers and payload length as emitted — and not the
|
||||||
|
// frame as it stood before the segment was written into it.
|
||||||
|
func TestPolicy_PostTxSeesWrittenFrame(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(6))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
data := []byte("payload")
|
||||||
|
if _, err := client.Write(data); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
n, err := client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
last := pol.postTx[len(pol.postTx)-1]
|
||||||
|
wantSeg := mustSegment(t, buf[:n], n-int(last.offset)*4)
|
||||||
|
if last.seg != wantSeg {
|
||||||
|
t.Fatalf("PostTx segment=%+v, want emitted %+v", last.seg, wantSeg)
|
||||||
|
}
|
||||||
|
if int(last.seg.DATALEN) != len(data) {
|
||||||
|
t.Fatalf("PostTx DATALEN=%d, want %d", last.seg.DATALEN, len(data))
|
||||||
|
}
|
||||||
|
if last.sport != client.LocalPort() || last.dport != client.RemotePort() {
|
||||||
|
t.Fatalf("PostTx ports=%d→%d, want %d→%d", last.sport, last.dport, client.LocalPort(), client.RemotePort())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_NoPostTxWithoutSegment verifies a transmit attempt that emits
|
||||||
|
// nothing still runs PreTx but never PostTx, so a Policy cannot mistake a
|
||||||
|
// no-op Send for a segment on the wire.
|
||||||
|
func TestPolicy_NoPostTxWithoutSegment(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(7))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
preTxBefore, postTxBefore := pol.preTx, len(pol.postTx)
|
||||||
|
n, err := client.Send(buf[:]) // Nothing queued: no segment.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
if n != 0 {
|
||||||
|
t.Fatalf("expected no segment, got %d bytes", n)
|
||||||
|
}
|
||||||
|
if pol.preTx != preTxBefore+1 {
|
||||||
|
t.Fatalf("PreTx calls=%d, want %d: PreTx must run on every attempt", pol.preTx, preTxBefore+1)
|
||||||
|
}
|
||||||
|
if len(pol.postTx) != postTxBefore {
|
||||||
|
t.Fatalf("PostTx calls=%d, want %d: no segment was emitted", len(pol.postTx), postTxBefore)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_PreTxOptions verifies options written by PreTx survive to the wire:
|
||||||
|
// the data offset accounts for them and the payload starts after them.
|
||||||
|
func TestPolicy_PreTxOptions(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(8))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
// One 4-byte option word: NOP,NOP,NOP,EOL.
|
||||||
|
opts := []byte{1, 1, 1, 0}
|
||||||
|
pol.writeOpts = opts
|
||||||
|
|
||||||
|
data := []byte("payload")
|
||||||
|
if _, err := client.Write(data); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
n, err := client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
frm, err := NewFrame(buf[:n])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("frame:", err)
|
||||||
|
}
|
||||||
|
offset, _ := frm.OffsetAndFlags()
|
||||||
|
if offset != 6 {
|
||||||
|
t.Fatalf("data offset=%d, want 6 (header + one option word)", offset)
|
||||||
|
}
|
||||||
|
if got := frm.Options(); string(got) != string(opts) {
|
||||||
|
t.Fatalf("options=%v, want %v", got, opts)
|
||||||
|
}
|
||||||
|
if got := frm.Payload(); string(got) != string(data) {
|
||||||
|
t.Fatalf("payload=%q, want %q: options must not overlap data", got, data)
|
||||||
|
}
|
||||||
|
if n != int(offset)*4+len(data) {
|
||||||
|
t.Fatalf("frame length=%d, want %d", n, int(offset)*4+len(data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_PreRxDropsSegment verifies keep=false drops the segment before the
|
||||||
|
// state machine sees it: the payload is not buffered, connection state is
|
||||||
|
// untouched and PostRx never fires.
|
||||||
|
func TestPolicy_PreRxDropsSegment(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(4))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
server.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:]) // keep=true so handshake completes.
|
||||||
|
|
||||||
|
// Now start dropping everything the server receives.
|
||||||
|
pol.keep = false
|
||||||
|
preRxBefore, postRxBefore := len(pol.preRx), len(pol.postRx)
|
||||||
|
|
||||||
|
data := []byte("dropme")
|
||||||
|
if _, err := client.Write(data); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
n, err := client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := server.Recv(buf[:n]); err != nil {
|
||||||
|
t.Fatalf("dropped segment must return nil, got %v", err)
|
||||||
|
}
|
||||||
|
if len(pol.preRx) != preRxBefore+1 {
|
||||||
|
t.Fatalf("PreRx calls=%d, want %d (segment must reach PreRx)", len(pol.preRx), preRxBefore+1)
|
||||||
|
}
|
||||||
|
if len(pol.postRx) != postRxBefore {
|
||||||
|
t.Fatalf("PostRx calls=%d, want %d: a dropped segment was never accepted", len(pol.postRx), postRxBefore)
|
||||||
|
}
|
||||||
|
if server.BufferedInput() != 0 {
|
||||||
|
t.Fatalf("dropped segment must not be buffered, got %d bytes", server.BufferedInput())
|
||||||
|
}
|
||||||
|
if server.State() != StateEstablished {
|
||||||
|
t.Fatalf("dropped segment must not change state, got %s", server.State())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_PreTxRetransmit verifies a PreTx retransmit directive drives
|
||||||
|
// go-back-N: the Handler rewinds the send sequence and the transmit buffer
|
||||||
|
// together and re-emits already-sent, unacknowledged data from snd.UNA.
|
||||||
|
func TestPolicy_PreTxRetransmit(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(5))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
// Emit one data segment; server never ACKs, so it stays unacknowledged.
|
||||||
|
data := []byte("payload")
|
||||||
|
if _, err := client.Write(data); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
n, err := client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send data:", err)
|
||||||
|
}
|
||||||
|
if n <= sizeHeaderTCP {
|
||||||
|
t.Fatal("expected data segment")
|
||||||
|
}
|
||||||
|
firstSeg := mustSegment(t, buf[:n], n-sizeHeaderTCP)
|
||||||
|
firstData := append([]byte(nil), buf[sizeHeaderTCP:n]...)
|
||||||
|
|
||||||
|
// Direct go-back-N on the next transmit.
|
||||||
|
pol.rtxFrom, pol.retransmit = client.ControlBlock().SendUNA(), true
|
||||||
|
clear(buf[:])
|
||||||
|
n, err = client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send retransmit:", err)
|
||||||
|
}
|
||||||
|
if n <= sizeHeaderTCP {
|
||||||
|
t.Fatal("expected retransmitted data segment")
|
||||||
|
}
|
||||||
|
rtSeg := mustSegment(t, buf[:n], n-sizeHeaderTCP)
|
||||||
|
|
||||||
|
if rtSeg.SEQ != firstSeg.SEQ {
|
||||||
|
t.Fatalf("retransmit SEQ=%d, want original UNA SEQ=%d (go-back-N)", rtSeg.SEQ, firstSeg.SEQ)
|
||||||
|
}
|
||||||
|
if rtSeg.DATALEN != firstSeg.DATALEN {
|
||||||
|
t.Fatalf("retransmit DATALEN=%d, want %d", rtSeg.DATALEN, firstSeg.DATALEN)
|
||||||
|
}
|
||||||
|
if got := buf[sizeHeaderTCP:n]; string(got) != string(firstData) {
|
||||||
|
t.Fatalf("retransmit payload=%q, want %q", got, firstData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_PreTxRetransmitOutOfRange verifies an out-of-range rtxFrom is
|
||||||
|
// refused, leaving the send sequence and transmit buffer untouched.
|
||||||
|
func TestPolicy_PreTxRetransmitOutOfRange(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(9))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
if _, err := client.Write([]byte("payload")); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
if _, err := client.Send(buf[:]); err != nil {
|
||||||
|
t.Fatal("client send data:", err)
|
||||||
|
}
|
||||||
|
nxtBefore := client.ControlBlock().SendNext()
|
||||||
|
|
||||||
|
// Well beyond snd.NXT: must be refused.
|
||||||
|
pol.rtxFrom, pol.retransmit = nxtBefore+1000, true
|
||||||
|
clear(buf[:])
|
||||||
|
if _, err := client.Send(buf[:]); err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
if got := client.ControlBlock().SendNext(); got != nxtBefore {
|
||||||
|
t.Fatalf("snd.NXT=%d, want unchanged %d: out-of-range rtxFrom must be refused", got, nxtBefore)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_TransmitLimit verifies the PreTx new-data limit caps the payload
|
||||||
|
// sent while leaving control segments free to go out: a zero limit suppresses
|
||||||
|
// data entirely, a partial limit truncates the segment.
|
||||||
|
func TestPolicy_TransmitLimit(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
rng := rand.New(rand.NewSource(10))
|
||||||
|
client, server := newHandler(t, mtu, 3), newHandler(t, mtu, 3)
|
||||||
|
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var buf [mtu]byte
|
||||||
|
establish(t, client, server, buf[:])
|
||||||
|
|
||||||
|
const payload = "payload"
|
||||||
|
pol.txLimit = 0
|
||||||
|
if _, err := client.Write([]byte(payload)); err != nil {
|
||||||
|
t.Fatal("client write:", err)
|
||||||
|
}
|
||||||
|
clear(buf[:])
|
||||||
|
n, err := client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send:", err)
|
||||||
|
}
|
||||||
|
if n > sizeHeaderTCP {
|
||||||
|
t.Fatalf("a zero limit must suppress new data, got %d payload bytes", n-sizeHeaderTCP)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A partial limit lets only that many bytes out.
|
||||||
|
pol.txLimit = 3
|
||||||
|
clear(buf[:])
|
||||||
|
n, err = client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send under partial limit:", err)
|
||||||
|
}
|
||||||
|
if got := n - sizeHeaderTCP; got != int(pol.txLimit) {
|
||||||
|
t.Fatalf("got %d payload bytes, want the limit of %d", got, pol.txLimit)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Releasing the limit lets the rest of the data out.
|
||||||
|
pol.txLimit = TransmitUnlimited
|
||||||
|
clear(buf[:])
|
||||||
|
n, err = client.Send(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send after limit lifted:", err)
|
||||||
|
}
|
||||||
|
if got := n - sizeHeaderTCP; got != len(payload)-3 {
|
||||||
|
t.Fatalf("got %d payload bytes, want the remaining %d once unlimited", got, len(payload)-3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPolicy_ResetOnReopen verifies Reset fires on every (re)open and on Abort,
|
||||||
|
// so a single Policy value can be reused across connection reuse.
|
||||||
|
func TestPolicy_ResetOnReopen(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
client := newHandler(t, mtu, 3)
|
||||||
|
pol := newRecordingPolicy()
|
||||||
|
client.SetPolicy(pol)
|
||||||
|
|
||||||
|
if err := client.OpenActive(1234, 5678, 0); err != nil {
|
||||||
|
t.Fatal("open 1:", err)
|
||||||
|
}
|
||||||
|
afterOpen := pol.resets
|
||||||
|
if afterOpen == 0 {
|
||||||
|
t.Fatal("Reset not called on first open")
|
||||||
|
}
|
||||||
|
|
||||||
|
client.Abort()
|
||||||
|
if pol.resets <= afterOpen {
|
||||||
|
t.Fatalf("Reset not called on Abort: resets=%d, want >%d", pol.resets, afterOpen)
|
||||||
|
}
|
||||||
|
afterAbort := pol.resets
|
||||||
|
|
||||||
|
if err := client.OpenActive(1234, 5678, 0); err != nil {
|
||||||
|
t.Fatal("open 2:", err)
|
||||||
|
}
|
||||||
|
if pol.resets <= afterAbort {
|
||||||
|
t.Fatalf("Reset not called on reopen: resets=%d, want >%d", pol.resets, afterAbort)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestHandlerStreamIntegrityUnderReorder asserts byte identity of a reassembled
|
||||||
|
// stream whose segments arrive out of order: arrival order is randomised within
|
||||||
|
// each block of shuffleWindow segments, and nothing is lost or retransmitted, so
|
||||||
|
// several segments sit staged in the receive ring at once. Reordering may cost
|
||||||
|
// throughput; it may not change the bytes.
|
||||||
|
func TestHandlerStreamIntegrityUnderReorder(t *testing.T) {
|
||||||
|
const (
|
||||||
|
mtu = ethernet.MaxMTU
|
||||||
|
maxpackets = 8
|
||||||
|
segSize = 100
|
||||||
|
nsegs = 8 // per round; 800 bytes through a 1500-byte ring
|
||||||
|
rounds = 40 // enough for the ring to wrap many times
|
||||||
|
shuffleWindow = 4 // segments that may arrive in any order among themselves
|
||||||
|
)
|
||||||
|
rng := rand.New(rand.NewSource(3))
|
||||||
|
client, server := newHandler(t, mtu, maxpackets), newHandler(t, mtu, maxpackets)
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var rawbuf [mtu]byte
|
||||||
|
establish(t, client, server, rawbuf[:])
|
||||||
|
|
||||||
|
var want, got []byte
|
||||||
|
rb := make([]byte, mtu)
|
||||||
|
letter := byte('A')
|
||||||
|
for round := range rounds {
|
||||||
|
// Capture this round's segments on the wire, one segment per write.
|
||||||
|
segs := make([][]byte, 0, nsegs)
|
||||||
|
for range nsegs {
|
||||||
|
payload := make([]byte, segSize)
|
||||||
|
for j := range payload {
|
||||||
|
payload[j] = letter
|
||||||
|
}
|
||||||
|
letter++
|
||||||
|
if letter > 'Z' {
|
||||||
|
letter = 'A'
|
||||||
|
}
|
||||||
|
if n, err := client.Write(payload); err != nil || n != segSize {
|
||||||
|
t.Fatalf("round %d: client write: %d %v", round, n, err)
|
||||||
|
}
|
||||||
|
clear(rawbuf[:])
|
||||||
|
n, err := client.Send(rawbuf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("round %d: client send: %v", round, err)
|
||||||
|
}
|
||||||
|
segs = append(segs, append([]byte(nil), rawbuf[:n]...))
|
||||||
|
want = append(want, payload...)
|
||||||
|
}
|
||||||
|
|
||||||
|
order := make([]int, 0, nsegs)
|
||||||
|
for i := 0; i < nsegs; i += shuffleWindow {
|
||||||
|
block := make([]int, 0, shuffleWindow)
|
||||||
|
for j := i; j < min(i+shuffleWindow, nsegs); j++ {
|
||||||
|
block = append(block, j)
|
||||||
|
}
|
||||||
|
rng.Shuffle(len(block), func(a, b int) { block[a], block[b] = block[b], block[a] })
|
||||||
|
order = append(order, block...)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, idx := range order {
|
||||||
|
if err := server.Recv(append([]byte(nil), segs[idx]...)); err != nil {
|
||||||
|
t.Logf("round %d segment %d refused: %v", round, idx, err)
|
||||||
|
}
|
||||||
|
// Drain as an application would, keeping the ring from filling.
|
||||||
|
for {
|
||||||
|
n, err := server.Read(rb)
|
||||||
|
if n > 0 {
|
||||||
|
got = append(got, rb[:n]...)
|
||||||
|
}
|
||||||
|
if n == 0 || err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Feed ACKs back so the sender's window keeps opening; without this
|
||||||
|
// the test stalls on flow control instead of exercising reassembly.
|
||||||
|
clear(rawbuf[:])
|
||||||
|
if n, err := server.Send(rawbuf[:]); err == nil && n > 0 {
|
||||||
|
client.Recv(rawbuf[:n])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if string(got) != string(want) {
|
||||||
|
// Report the first divergence; later rounds only add noise.
|
||||||
|
i := 0
|
||||||
|
for i < len(got) && i < len(want) && got[i] == want[i] {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
t.Errorf("stream diverges in round %d at byte %d of %d; arrival order %v",
|
||||||
|
round, i, len(want), order)
|
||||||
|
lo := max(0, i-200)
|
||||||
|
t.Errorf("got %s", summarizeRuns(got[lo:min(len(got), i+200)]))
|
||||||
|
t.Errorf("want %s", summarizeRuns(want[lo:min(len(want), i+200)]))
|
||||||
|
t.FailNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("%d bytes intact across %d rounds of reordering (window %d)", len(got), rounds, shuffleWindow)
|
||||||
|
}
|
||||||
|
|
||||||
|
// summarizeRuns renders a byte stream as run-length pairs ("A*100 B*100") so a
|
||||||
|
// duplicated or missing segment is visible at a glance.
|
||||||
|
func summarizeRuns(b []byte) string {
|
||||||
|
out := make([]byte, 0, 64)
|
||||||
|
for i := 0; i < len(b); {
|
||||||
|
j := i
|
||||||
|
for j < len(b) && b[j] == b[i] {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
out = append(out, b[i], '*')
|
||||||
|
out = append(out, strconv.Itoa(j-i)...)
|
||||||
|
out = append(out, ' ')
|
||||||
|
i = j
|
||||||
|
}
|
||||||
|
return string(out)
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package rto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
"github.com/soypat/lneto/tcp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sizeHeaderTCP is the fixed TCP header length. The tcp package's own constant
|
||||||
|
// is unexported and these tests live outside it.
|
||||||
|
const sizeHeaderTCP = 20
|
||||||
|
|
||||||
|
// TestRTO_HandlerRetransmitsAfterTimeout covers the seam between a Handler and
|
||||||
|
// its Policy, which the Timer unit tests do not: a lost data segment must be
|
||||||
|
// resent once the timer expires, with nothing arriving to prompt it.
|
||||||
|
func TestRTO_HandlerRetransmitsAfterTimeout(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
const maxpackets = 4
|
||||||
|
rng := rand.New(rand.NewSource(5))
|
||||||
|
client, server := newHandler(t, mtu, maxpackets), newHandler(t, mtu, maxpackets)
|
||||||
|
|
||||||
|
var now int64 // injected monotonic clock, in nanoseconds
|
||||||
|
client.SetPolicy(newTimer(t, func() int64 { return now }))
|
||||||
|
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var rawbuf [mtu]byte
|
||||||
|
establish(t, client, server, rawbuf[:])
|
||||||
|
|
||||||
|
data := []byte("hello")
|
||||||
|
if n, err := client.Write(data); err != nil || n != len(data) {
|
||||||
|
t.Fatal("client write:", n, err)
|
||||||
|
}
|
||||||
|
clear(rawbuf[:])
|
||||||
|
n, err := client.Send(rawbuf[:])
|
||||||
|
if err != nil || n == 0 {
|
||||||
|
t.Fatal("client send:", n, err)
|
||||||
|
}
|
||||||
|
// That frame is lost: it is never handed to the server.
|
||||||
|
|
||||||
|
// Nothing may come back before the timer expires.
|
||||||
|
var probe [mtu]byte
|
||||||
|
if n, err := client.Send(probe[:]); err != nil || n != 0 {
|
||||||
|
t.Fatalf("client sent %d bytes before the RTO expired (err %v)", n, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
now += int64(3 * time.Second) // past the initial RTO and one backoff
|
||||||
|
|
||||||
|
clear(probe[:])
|
||||||
|
n, err = client.Send(probe[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send after RTO:", err)
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
t.Fatal("no retransmission after the RTO expired: the Policy directive is never applied")
|
||||||
|
}
|
||||||
|
if err := server.Recv(probe[:n]); err != nil {
|
||||||
|
t.Fatal("server refused the retransmission:", err)
|
||||||
|
}
|
||||||
|
got := make([]byte, 16)
|
||||||
|
nr, err := server.Read(got)
|
||||||
|
if err != nil || string(got[:nr]) != string(data) {
|
||||||
|
t.Fatalf("server read %q (%v), want %q", got[:nr], err, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_HandlerRetransmitsAfterCloseWithUnackedData is the write-then-close
|
||||||
|
// case every server performs. With the last data segment lost, the FIN behind it
|
||||||
|
// sits above a gap the peer cannot cross, so FIN-WAIT-1 must still retransmit
|
||||||
|
// that data or both sides wait forever.
|
||||||
|
func TestRTO_HandlerRetransmitsAfterCloseWithUnackedData(t *testing.T) {
|
||||||
|
const mtu = ethernet.MaxMTU
|
||||||
|
const maxpackets = 4
|
||||||
|
rng := rand.New(rand.NewSource(9))
|
||||||
|
client, server := newHandler(t, mtu, maxpackets), newHandler(t, mtu, maxpackets)
|
||||||
|
|
||||||
|
var now int64
|
||||||
|
client.SetPolicy(newTimer(t, func() int64 { return now }))
|
||||||
|
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
var rawbuf [mtu]byte
|
||||||
|
establish(t, client, server, rawbuf[:])
|
||||||
|
|
||||||
|
data := []byte("last response bytes")
|
||||||
|
if n, err := client.Write(data); err != nil || n != len(data) {
|
||||||
|
t.Fatal("client write:", n, err)
|
||||||
|
}
|
||||||
|
clear(rawbuf[:])
|
||||||
|
n, err := client.Send(rawbuf[:]) // this frame is lost in transit
|
||||||
|
if err != nil || n == 0 {
|
||||||
|
t.Fatal("client send:", n, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The application closes right after writing.
|
||||||
|
if err := client.Close(); err != nil {
|
||||||
|
t.Fatal("client close:", err)
|
||||||
|
}
|
||||||
|
var finbuf [mtu]byte
|
||||||
|
nfin, err := client.Send(finbuf[:]) // FIN (also lost, or simply unacked)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send FIN:", err)
|
||||||
|
}
|
||||||
|
t.Logf("state after close: %s (FIN frame %d bytes)", client.State(), nfin)
|
||||||
|
|
||||||
|
now += int64(3 * time.Second) // past the RTO
|
||||||
|
|
||||||
|
var probe [mtu]byte
|
||||||
|
n, err = client.Send(probe[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client send after RTO:", err)
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
t.Fatalf("no retransmission in %s: unacknowledged data is stranded by the close", client.State())
|
||||||
|
}
|
||||||
|
if err := server.Recv(probe[:n]); err != nil {
|
||||||
|
t.Fatal("server refused the retransmission:", err)
|
||||||
|
}
|
||||||
|
got := make([]byte, 32)
|
||||||
|
nr, err := server.Read(got)
|
||||||
|
if err != nil || string(got[:nr]) != string(data) {
|
||||||
|
t.Fatalf("server read %q (%v), want %q", got[:nr], err, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newTimer returns a Timer driven by nanotime, ready to install as a [tcp.Policy].
|
||||||
|
func newTimer(t *testing.T, nanotime func() int64) *Timer {
|
||||||
|
t.Helper()
|
||||||
|
r := new(Timer)
|
||||||
|
err := r.Configure(nanotime)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// The handshake helpers below mirror those in the tcp package's own tests, which
|
||||||
|
// are unexported and so unavailable here. They drive two Handlers against each
|
||||||
|
// other over a single packet buffer, with no network in between.
|
||||||
|
|
||||||
|
func newHandler(t *testing.T, mtu, minpackets int) *tcp.Handler {
|
||||||
|
t.Helper()
|
||||||
|
h := new(tcp.Handler)
|
||||||
|
err := h.SetBuffers(make([]byte, mtu), make([]byte, mtu), minpackets)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
func setupClientServer(t *testing.T, rng *rand.Rand, client, server *tcp.Handler) {
|
||||||
|
t.Helper()
|
||||||
|
err := server.OpenListen(uint16(rng.Uint32()), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = client.OpenActive(uint16(rng.Uint32()), server.LocalPort(), 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !client.AwaitingSynSend() {
|
||||||
|
t.Fatal("client in wrong state")
|
||||||
|
}
|
||||||
|
if !server.AwaitingSynAck() {
|
||||||
|
t.Fatal("server in wrong state")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func establish(t *testing.T, client, server *tcp.Handler, packetBuf []byte) {
|
||||||
|
t.Helper()
|
||||||
|
if client.State() != tcp.StateClosed {
|
||||||
|
t.Fatal("client in wrong state")
|
||||||
|
} else if server.State() != tcp.StateListen {
|
||||||
|
t.Fatal("server in wrong state")
|
||||||
|
}
|
||||||
|
clear(packetBuf)
|
||||||
|
|
||||||
|
// Commence 3-way handshake: client sends SYN, server sends SYN-ACK, client sends ACK.
|
||||||
|
n, err := client.Send(packetBuf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client sending:", err)
|
||||||
|
} else if n < sizeHeaderTCP {
|
||||||
|
t.Fatal("expected client to send SYN packet")
|
||||||
|
} else if client.State() != tcp.StateSynSent {
|
||||||
|
t.Fatal("client did not transition to SynSent state:", client.State().String())
|
||||||
|
}
|
||||||
|
err = server.Recv(packetBuf[:n]) // Server receives SYN.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if server.State() != tcp.StateSynRcvd {
|
||||||
|
t.Fatal("server did not transition to SynReceived state:", server.State().String())
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(packetBuf)
|
||||||
|
n, err = server.Send(packetBuf) // Server sends SYNACK.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("server sending:", err)
|
||||||
|
} else if n < sizeHeaderTCP {
|
||||||
|
t.Fatal("expected server to send SYNACK packet")
|
||||||
|
}
|
||||||
|
err = client.Recv(packetBuf[:n]) // Client receives SYNACK, is established but must send ACK.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if client.State() != tcp.StateEstablished {
|
||||||
|
t.Fatal("client did not transition to Established state:", client.State().String())
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(packetBuf)
|
||||||
|
n, err = client.Send(packetBuf) // Client sends ACK.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client sending ACK:", err)
|
||||||
|
} else if n < sizeHeaderTCP {
|
||||||
|
t.Fatal("expected client to send ACK packet")
|
||||||
|
}
|
||||||
|
err = server.Recv(packetBuf[:n]) // Server receives ACK.
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if server.State() != tcp.StateEstablished {
|
||||||
|
t.Fatal("server did not transition to Established state on ACK receive:", server.State().String())
|
||||||
|
}
|
||||||
|
}
|
||||||
+115
-47
@@ -1,6 +1,11 @@
|
|||||||
package tcp
|
package rto
|
||||||
|
|
||||||
import "time"
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto"
|
||||||
|
"github.com/soypat/lneto/tcp"
|
||||||
|
)
|
||||||
|
|
||||||
// RFC 6298 retransmission-timeout (RTO) parameters. The algorithm keeps a
|
// RFC 6298 retransmission-timeout (RTO) parameters. The algorithm keeps a
|
||||||
// single retransmission timer per connection (RFC 6298 §5): the timer is
|
// single retransmission timer per connection (RFC 6298 §5): the timer is
|
||||||
@@ -30,61 +35,80 @@ const (
|
|||||||
backoffMax = 12
|
backoffMax = 12
|
||||||
)
|
)
|
||||||
|
|
||||||
// RTO implements the RFC 6298 round-trip-time estimator and the single
|
// Timer implements the RFC 6298 round-trip-time estimator and the single
|
||||||
// retransmission timer as a [LossRecovery]. Construct it with new(RTO) and hand
|
// retransmission timer as a [tcp.Policy]. Construct it with [NewTimer] and hand
|
||||||
// it to [ConnConfig.LossRecovery]; the connection calls [RTO.Reset] on open, so
|
// it to [tcp.ConnConfig.Policy].
|
||||||
// the zero value is ready to use.
|
|
||||||
//
|
//
|
||||||
// RTO is a pure, reactive state machine: it observes the segments a connection
|
// Timer is a pure, reactive state machine: it observes the segments a connection
|
||||||
// sends and receives (via the LossRecovery hooks) and the monotonic time handed
|
// sends and receives (via the tcp.Policy hooks) and from those alone derives RTT
|
||||||
// in at each hook, and from those alone derives RTT estimates and retransmission
|
// estimates and retransmission decisions. The tcp package holds no clock, so the
|
||||||
// decisions. It holds no clock and allocates nothing, which keeps it
|
// Timer carries its own; injecting it keeps the estimator deterministic for unit
|
||||||
// deterministic for unit testing (see issue #140).
|
// testing (see issue #140).
|
||||||
//
|
//
|
||||||
// RTO tracks its own shadow of the send sequence space purely from the segments
|
// Timer tracks its own shadow of the send sequence space purely from the segments
|
||||||
// it observes: [RTO.PostTx] advances the highest sequence sent and [RTO.PreRx]
|
// it observes: [Timer.PostTx] advances the highest sequence sent and [Timer.PreRx]
|
||||||
// advances the highest sequence acknowledged. This is what lets it manage the
|
// advances the highest sequence acknowledged. This is what lets it manage the
|
||||||
// timer (RFC 6298 §5.2/§5.3) without reaching into the tcp state machine, and it
|
// timer (RFC 6298 §5.2/§5.3) without reaching into the tcp state machine, and it
|
||||||
// is also how retransmissions are distinguished for Karn's algorithm — a segment
|
// is also how retransmissions are distinguished for Karn's algorithm — a segment
|
||||||
// whose sequence space is not beyond the shadow snd.NXT is a retransmission and
|
// whose sequence space is not beyond the shadow snd.NXT is a retransmission and
|
||||||
// is never RTT-sampled.
|
// is never RTT-sampled.
|
||||||
type RTO struct {
|
type Timer struct {
|
||||||
|
// nanotime is the monotonic time source in nanoseconds. Preserved by Reset.
|
||||||
|
nanotime func() int64
|
||||||
|
|
||||||
srtt time.Duration // smoothed round-trip time (SRTT).
|
srtt time.Duration // smoothed round-trip time (SRTT).
|
||||||
rttvar time.Duration // round-trip-time variation (RTTVAR).
|
rttvar time.Duration // round-trip-time variation (RTTVAR).
|
||||||
rto time.Duration // current retransmission timeout.
|
rto time.Duration // current retransmission timeout.
|
||||||
haveRTT bool // false until the first RTT sample is taken.
|
haveRTT bool // false until the first RTT sample is taken.
|
||||||
|
|
||||||
// Shadow of the send sequence space, derived from observed segments.
|
// Shadow of the send sequence space, derived from observed segments.
|
||||||
haveSeq bool // false until the first data segment is observed.
|
haveSeq bool // false until the first data segment is observed.
|
||||||
sndUNA Value // highest acknowledged sequence number seen on the wire.
|
sndUNA tcp.Value // highest acknowledged sequence number seen on the wire.
|
||||||
sndNXT Value // one past the highest sequence number sent.
|
sndNXT tcp.Value // one past the highest sequence number sent.
|
||||||
|
|
||||||
// RTT sampling state (Karn's algorithm, RFC 6298 §3): at most one segment is
|
// RTT sampling state (Karn's algorithm, RFC 6298 §3): at most one segment is
|
||||||
// timed at a time and retransmitted segments are never sampled.
|
// timed at a time and retransmitted segments are never sampled.
|
||||||
timing bool
|
timing bool
|
||||||
timedSeq Value // ACK at or beyond this value completes the sample.
|
timedSeq tcp.Value // ACK at or beyond this value completes the sample.
|
||||||
timedAt int64 // send time (monotonic ns) of the timed segment.
|
timedAt int64 // send time (monotonic ns) of the timed segment.
|
||||||
|
|
||||||
// Retransmission timer state.
|
// Retransmission timer state.
|
||||||
running bool
|
running bool
|
||||||
deadline int64 // time (monotonic ns) at which the timer expires.
|
deadline int64 // time (monotonic ns) at which the timer expires.
|
||||||
backoff uint8 // consecutive timeouts, for exponential backoff.
|
backoff uint8 // consecutive timeouts, for exponential backoff.
|
||||||
|
|
||||||
|
// expirations counts timeouts since Reset. It exists so a policy sharing this
|
||||||
|
// timer can notice a timeout it did not itself drive: a congestion controller
|
||||||
|
// must collapse its window on one, and a policy that composes the timer as a
|
||||||
|
// peer never sees the timer's own directive.
|
||||||
|
expirations uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ LossRecovery = (*RTO)(nil)
|
var _ tcp.Policy = (*Timer)(nil)
|
||||||
|
|
||||||
// Reset returns the estimator to its pre-connection state with the initial RTO.
|
// Configure prepares the Timer for use with nanotime, the monotonic time source
|
||||||
// It implements [LossRecovery] and is called when the connection opens or aborts
|
// in nanoseconds (the func() int64 convention used across lneto). It must be
|
||||||
// so the estimator can be reused across connection reuse.
|
// called before the connection is opened.
|
||||||
func (r *RTO) Reset() { *r = RTO{rto: rtoInitial} }
|
func (r *Timer) Configure(nanotime func() int64) error {
|
||||||
|
if nanotime == nil {
|
||||||
|
return lneto.ErrMissingHALConfig // The estimator cannot run without a clock.
|
||||||
|
}
|
||||||
|
*r = Timer{rto: rtoInitial, nanotime: nanotime}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset returns the estimator to its pre-connection state with the initial RTO,
|
||||||
|
// preserving the configured clock. It implements [tcp.Policy] and is called when
|
||||||
|
// the connection opens or aborts so the estimator survives connection reuse.
|
||||||
|
func (r *Timer) Reset() { *r = Timer{rto: rtoInitial, nanotime: r.nanotime} }
|
||||||
|
|
||||||
// SmoothedRTT returns the current smoothed round-trip time (SRTT), or zero
|
// SmoothedRTT returns the current smoothed round-trip time (SRTT), or zero
|
||||||
// before the first RTT measurement. It is concrete-type introspection and is
|
// before the first RTT measurement. It is concrete-type introspection and is
|
||||||
// intentionally not part of [LossRecovery].
|
// intentionally not part of [tcp.Policy].
|
||||||
func (r *RTO) SmoothedRTT() time.Duration { return r.srtt }
|
func (r *Timer) SmoothedRTT() time.Duration { return r.srtt }
|
||||||
|
|
||||||
// CurrentRTO returns the timeout currently in effect, clamped to [rtoMin, rtoMax].
|
// CurrentRTO returns the timeout currently in effect, clamped to [rtoMin, rtoMax].
|
||||||
func (r *RTO) CurrentRTO() time.Duration {
|
func (r *Timer) CurrentRTO() time.Duration {
|
||||||
rto := r.rto
|
rto := r.rto
|
||||||
if rto < rtoMin {
|
if rto < rtoMin {
|
||||||
rto = rtoMin
|
rto = rtoMin
|
||||||
@@ -95,23 +119,46 @@ func (r *RTO) CurrentRTO() time.Duration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Running reports whether the retransmission timer is currently armed.
|
// Running reports whether the retransmission timer is currently armed.
|
||||||
func (r *RTO) Running() bool { return r.running }
|
func (r *Timer) Running() bool { return r.running }
|
||||||
|
|
||||||
|
// Expirations returns how many times the retransmission timer has expired since
|
||||||
|
// [Timer.Reset]. A policy that shares this timer rather than driving it watches
|
||||||
|
// this for a change to learn that a timeout happened, since it never sees the
|
||||||
|
// timer's own directive. It is concrete-type introspection and is intentionally
|
||||||
|
// not part of [tcp.Policy].
|
||||||
|
func (r *Timer) Expirations() uint32 { return r.expirations }
|
||||||
|
|
||||||
// NextDeadline returns the monotonic-nanosecond instant at which the timer
|
// NextDeadline returns the monotonic-nanosecond instant at which the timer
|
||||||
// expires, or 0 when it is not armed. It implements [LossRecovery].
|
// expires, or 0 when it is not armed. It is concrete-type introspection, not
|
||||||
func (r *RTO) NextDeadline() int64 {
|
// part of [tcp.Policy]: an event loop that wants to schedule against the RTO
|
||||||
|
// holds the Timer it configured and reads this.
|
||||||
|
func (r *Timer) NextDeadline() int64 {
|
||||||
if !r.running {
|
if !r.running {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
return r.deadline
|
return r.deadline
|
||||||
}
|
}
|
||||||
|
|
||||||
// PreRx samples the RTT and manages the retransmission timer from a received
|
// PreRx keeps every segment: the estimator never drops traffic and records
|
||||||
// segment (RFC 6298 §5.2/§5.3). It implements [LossRecovery] and always keeps
|
// nothing before the connection has decided whether the segment counts. It
|
||||||
// the segment (the estimator never drops traffic).
|
// implements [tcp.Policy].
|
||||||
func (r *RTO) PreRx(incoming Segment, now int64) RxDirective {
|
func (r *Timer) PreRx(h *tcp.Handler, incoming tcp.Frame) bool {
|
||||||
if !r.haveSeq || !incoming.Flags.HasAny(FlagACK) {
|
return true
|
||||||
return RxDirective{Keep: true}
|
}
|
||||||
|
|
||||||
|
// PostRx samples the RTT and manages the retransmission timer from a segment the
|
||||||
|
// connection accepted (RFC 6298 §5.2/§5.3). It implements [tcp.Policy].
|
||||||
|
//
|
||||||
|
// Only accepted segments reach here. Acting on a refused one would let an
|
||||||
|
// acknowledgement the state machine rejected, for data never sent, collapse the
|
||||||
|
// backoff and take a bogus RTT sample.
|
||||||
|
func (r *Timer) PostRx(h *tcp.Handler, prevState tcp.State, accepted tcp.Frame) {
|
||||||
|
r.postRx(accepted.Segment(len(accepted.Payload())), r.nanotime())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Timer) postRx(incoming tcp.Segment, now int64) {
|
||||||
|
if !r.haveSeq || !incoming.Flags.HasAny(tcp.FlagACK) {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
ack := incoming.ACK
|
ack := incoming.ACK
|
||||||
if r.timing && !ack.LessThan(r.timedSeq) {
|
if r.timing && !ack.LessThan(r.timedSeq) {
|
||||||
@@ -132,18 +179,24 @@ func (r *RTO) PreRx(incoming Segment, now int64) RxDirective {
|
|||||||
r.running = true
|
r.running = true
|
||||||
r.deadline = now + int64(r.CurrentRTO())
|
r.deadline = now + int64(r.CurrentRTO())
|
||||||
}
|
}
|
||||||
return RxDirective{Keep: true}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PreTx reports whether the retransmission timer has expired and, if so, applies
|
// PreTx reports whether the retransmission timer has expired and, if so, applies
|
||||||
// the RFC 6298 §5.4–§5.6 timeout response — discard the outstanding RTT sample
|
// the RFC 6298 §5.4–§5.6 timeout response — discard the outstanding RTT sample
|
||||||
// (Karn), back the RTO off exponentially and restart the timer — returning a
|
// (Karn), back the RTO off exponentially and restart the timer — and asks the
|
||||||
// directive that asks the connection to retransmit from snd.UNA (go-back-N). It
|
// connection to retransmit from snd.UNA (go-back-N). It writes no TCP options
|
||||||
// implements [LossRecovery].
|
// and imposes no transmit limit: retransmission timing needs neither, and
|
||||||
func (r *RTO) PreTx(now int64) TxDirective {
|
// congestion control belongs to a Policy composing this timer. It implements
|
||||||
|
// [tcp.Policy].
|
||||||
|
func (r *Timer) PreTx(h *tcp.Handler, outgoingOpts tcp.Frame) (newTransmitLimit tcp.Size, rtxFrom tcp.Value, retransmit bool) {
|
||||||
|
return r.preTx(r.nanotime(), h.ControlBlock().SendUNA())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Timer) preTx(now int64, una tcp.Value) (newTransmitLimit tcp.Size, rtxFrom tcp.Value, retransmit bool) {
|
||||||
if !r.running || now < r.deadline || r.sndUNA == r.sndNXT {
|
if !r.running || now < r.deadline || r.sndUNA == r.sndNXT {
|
||||||
return TxDirective{}
|
return tcp.TransmitUnlimited, 0, false
|
||||||
}
|
}
|
||||||
|
r.expirations++
|
||||||
r.timing = false // §5.4: do not sample a retransmitted segment.
|
r.timing = false // §5.4: do not sample a retransmitted segment.
|
||||||
if r.backoff < backoffMax {
|
if r.backoff < backoffMax {
|
||||||
r.backoff++
|
r.backoff++
|
||||||
@@ -151,20 +204,24 @@ func (r *RTO) PreTx(now int64) TxDirective {
|
|||||||
}
|
}
|
||||||
r.running = true
|
r.running = true
|
||||||
r.deadline = now + int64(r.CurrentRTO())
|
r.deadline = now + int64(r.CurrentRTO())
|
||||||
return TxDirective{RetransmitAll: true}
|
return tcp.TransmitUnlimited, una, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// PostTx records an emitted segment: it advances the shadow send sequence,
|
// PostTx records an emitted segment: it advances the shadow send sequence,
|
||||||
// begins timing newly transmitted data (RFC 6298 §3) and arms the timer (§5.1).
|
// begins timing newly transmitted data (RFC 6298 §3) and arms the timer (§5.1).
|
||||||
// Segments that do not extend the send sequence are retransmissions and are
|
// Segments that do not extend the send sequence are retransmissions and are
|
||||||
// never RTT-sampled (Karn's algorithm). Control-only segments (no data) are
|
// never RTT-sampled (Karn's algorithm). Control-only segments (no data) are
|
||||||
// ignored. It implements [LossRecovery].
|
// ignored. It implements [tcp.Policy].
|
||||||
func (r *RTO) PostTx(outgoing Segment, now int64) {
|
func (r *Timer) PostTx(h *tcp.Handler, outgoing tcp.Frame) {
|
||||||
|
r.postTx(outgoing.Segment(len(outgoing.Payload())), r.nanotime())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Timer) postTx(outgoing tcp.Segment, now int64) {
|
||||||
if outgoing.DATALEN == 0 {
|
if outgoing.DATALEN == 0 {
|
||||||
return // only data segments are timed / arm the RTO.
|
return // only data segments are timed / arm the RTO.
|
||||||
}
|
}
|
||||||
segStart := outgoing.SEQ
|
segStart := outgoing.SEQ
|
||||||
segEnd := segStart + Value(outgoing.LEN())
|
segEnd := segStart + tcp.Value(outgoing.LEN())
|
||||||
if !r.haveSeq {
|
if !r.haveSeq {
|
||||||
r.haveSeq = true
|
r.haveSeq = true
|
||||||
r.sndUNA = segStart
|
r.sndUNA = segStart
|
||||||
@@ -189,9 +246,20 @@ func (r *RTO) PostTx(outgoing Segment, now int64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ObserveRTT folds a round-trip measurement taken by other means into the
|
||||||
|
// estimator, for a policy that composes this timer and can measure the round trip
|
||||||
|
// more accurately than acknowledgement timing allows. The RFC 7323 timestamp echo
|
||||||
|
// is the case this exists for.
|
||||||
|
//
|
||||||
|
// Unlike the timer's own sampling this does not apply Karn's algorithm, because a
|
||||||
|
// sample derived from an echoed timestamp is unambiguous even when the segment
|
||||||
|
// carrying it was a retransmission (RFC 7323 §4.1). Non-positive samples are
|
||||||
|
// ignored.
|
||||||
|
func (r *Timer) ObserveRTT(rtt time.Duration) { r.updateRTT(rtt) }
|
||||||
|
|
||||||
// updateRTT folds a round-trip measurement into SRTT/RTTVAR/RTO using the
|
// updateRTT folds a round-trip measurement into SRTT/RTTVAR/RTO using the
|
||||||
// integer-shift form of RFC 6298 §2.2/§2.3.
|
// integer-shift form of RFC 6298 §2.2/§2.3.
|
||||||
func (r *RTO) updateRTT(sample time.Duration) {
|
func (r *Timer) updateRTT(sample time.Duration) {
|
||||||
if sample <= 0 {
|
if sample <= 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
package rto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/tcp"
|
||||||
|
)
|
||||||
|
|
||||||
|
const rtoMs = int64(time.Millisecond)
|
||||||
|
|
||||||
|
// dataSeg builds a data segment of datalen octets starting at seq.
|
||||||
|
func dataSeg(seq uint32, datalen int) tcp.Segment {
|
||||||
|
return tcp.Segment{SEQ: tcp.Value(seq), DATALEN: tcp.Size(datalen), Flags: tcp.FlagPSH | tcp.FlagACK}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ackSeg builds a bare ACK acknowledging up to ack.
|
||||||
|
func ackSeg(ack uint32) tcp.Segment {
|
||||||
|
return tcp.Segment{ACK: tcp.Value(ack), Flags: tcp.FlagACK}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newRTO() *Timer {
|
||||||
|
var r Timer
|
||||||
|
if err := r.Configure(func() int64 { return 0 }); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return &r
|
||||||
|
}
|
||||||
|
|
||||||
|
// frameOf renders a segment as the wire frame the [tcp.Policy] hooks receive.
|
||||||
|
func frameOf(t *testing.T, s tcp.Segment) tcp.Frame {
|
||||||
|
t.Helper()
|
||||||
|
frm, err := tcp.NewFrame(make([]byte, 20+int(s.DATALEN)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
frm.SetSegment(s, 5)
|
||||||
|
return frm
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRTO_Configure(t *testing.T) {
|
||||||
|
var r Timer
|
||||||
|
if err := r.Configure(nil); err == nil {
|
||||||
|
t.Error("Configure must reject a nil clock")
|
||||||
|
}
|
||||||
|
if err := r.Configure(func() int64 { return 0 }); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if r.nanotime == nil {
|
||||||
|
t.Fatal("clock not stored")
|
||||||
|
}
|
||||||
|
r.Reset()
|
||||||
|
if r.nanotime == nil {
|
||||||
|
t.Error("Reset must preserve the configured clock")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRTO_Reset(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
r.Reset()
|
||||||
|
if r.rto != rtoInitial {
|
||||||
|
t.Errorf("initial rto=%v, want %v", r.rto, rtoInitial)
|
||||||
|
}
|
||||||
|
if r.CurrentRTO() != rtoInitial {
|
||||||
|
t.Errorf("CurrentRTO=%v, want %v", r.CurrentRTO(), rtoInitial)
|
||||||
|
}
|
||||||
|
if r.haveRTT {
|
||||||
|
t.Error("haveRTT should be false before first sample")
|
||||||
|
}
|
||||||
|
if r.Running() || r.NextDeadline() != 0 {
|
||||||
|
t.Error("timer must be disarmed after Reset")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_ArmOnSendSampleOnAck sends data, verifies the timer arms, then acks it
|
||||||
|
// and verifies an RTT sample is taken and the timer stops once all data is acked.
|
||||||
|
func TestRTO_ArmOnSendSampleOnAck(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
if !r.Running() {
|
||||||
|
t.Fatal("timer must arm after sending data")
|
||||||
|
}
|
||||||
|
if r.NextDeadline() != int64(rtoInitial) {
|
||||||
|
t.Errorf("deadline=%d, want %d", r.NextDeadline(), int64(rtoInitial))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ACK arrives one RTT (40ms) later covering all sent data.
|
||||||
|
if !r.PreRx(nil, frameOf(t, ackSeg(iss+100))) {
|
||||||
|
t.Error("PreRx must keep the segment")
|
||||||
|
}
|
||||||
|
r.postRx(ackSeg(iss+100), 40*rtoMs)
|
||||||
|
if r.Running() {
|
||||||
|
t.Error("timer must stop once all data is acknowledged")
|
||||||
|
}
|
||||||
|
if r.SmoothedRTT() != 40*time.Millisecond {
|
||||||
|
t.Errorf("srtt=%v, want 40ms", r.SmoothedRTT())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_RetransmitOnTimeout verifies PreTx directs a go-back-N retransmit once
|
||||||
|
// the deadline passes with data outstanding, and backs the RTO off.
|
||||||
|
func TestRTO_RetransmitOnTimeout(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
|
||||||
|
if _, _, rtx := r.preTx(int64(rtoInitial)-1, tcp.Value(iss)); rtx {
|
||||||
|
t.Fatal("must not retransmit before the deadline")
|
||||||
|
}
|
||||||
|
limit, from, rtx := r.preTx(int64(rtoInitial), tcp.Value(iss))
|
||||||
|
if !rtx {
|
||||||
|
t.Fatal("RTO must fire at the deadline with data outstanding")
|
||||||
|
}
|
||||||
|
if limit != tcp.TransmitUnlimited {
|
||||||
|
t.Error("the estimator never limits new data")
|
||||||
|
}
|
||||||
|
if from != tcp.Value(iss) {
|
||||||
|
t.Errorf("retransmit from %d, want snd.UNA=%d", from, iss)
|
||||||
|
}
|
||||||
|
if r.CurrentRTO() != 2*rtoInitial {
|
||||||
|
t.Errorf("rto=%v after one backoff, want %v", r.CurrentRTO(), 2*rtoInitial)
|
||||||
|
}
|
||||||
|
// The connection resends from snd.UNA; postTx sees a retransmission.
|
||||||
|
r.postTx(dataSeg(iss, 100), int64(rtoInitial))
|
||||||
|
if r.timing {
|
||||||
|
t.Error("retransmitted segment must not be RTT-sampled (Karn)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_KarnNoSampleOnRetransmittedAck verifies that after a retransmission the
|
||||||
|
// ACK does not produce an RTT sample (Karn's algorithm).
|
||||||
|
func TestRTO_KarnNoSampleOnRetransmittedAck(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
// Timeout and retransmit.
|
||||||
|
r.preTx(int64(rtoInitial), tcp.Value(iss))
|
||||||
|
r.postTx(dataSeg(iss, 100), int64(rtoInitial))
|
||||||
|
// ACK now arrives; no sample should be taken since timing was discarded.
|
||||||
|
r.postRx(ackSeg(iss+100), int64(rtoInitial)+10*rtoMs)
|
||||||
|
if r.haveRTT {
|
||||||
|
t.Error("no RTT sample should exist after a retransmission (Karn)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_TimerRestartsWhilePartiallyAcked verifies the timer restarts (not
|
||||||
|
// stops) when an ACK advances UNA but data remains in flight (RFC 6298 §5.3).
|
||||||
|
func TestRTO_TimerRestartsWhilePartiallyAcked(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
r.postTx(dataSeg(iss+100, 100), 0) // 200 octets outstanding, iss..iss+200.
|
||||||
|
|
||||||
|
r.postRx(ackSeg(iss+100), 40*rtoMs) // acks first 100 only.
|
||||||
|
if !r.Running() {
|
||||||
|
t.Fatal("timer must remain armed while data is still in flight")
|
||||||
|
}
|
||||||
|
if r.NextDeadline() != 40*rtoMs+int64(r.CurrentRTO()) {
|
||||||
|
t.Errorf("deadline=%d, want %d", r.NextDeadline(), 40*rtoMs+int64(r.CurrentRTO()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_NoArmWithoutData verifies control-only segments neither arm the timer
|
||||||
|
// nor start an RTT sample.
|
||||||
|
func TestRTO_NoArmWithoutData(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
r.postTx(tcp.Segment{SEQ: 1000, Flags: tcp.FlagACK}, 0) // pure ACK, DATALEN==0.
|
||||||
|
if r.Running() || r.timing {
|
||||||
|
t.Error("pure control segment must not arm the timer or start a sample")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_BackoffCollapsesOnValidSample verifies a valid RTT measurement
|
||||||
|
// collapses the exponential backoff counter (RFC 6298 §5.7).
|
||||||
|
func TestRTO_BackoffCollapsesOnValidSample(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
r.preTx(int64(rtoInitial), tcp.Value(iss)) // one timeout: backoff=1.
|
||||||
|
r.postTx(dataSeg(iss, 100), int64(rtoInitial)) // retransmit (no sample).
|
||||||
|
if r.backoff != 1 {
|
||||||
|
t.Fatalf("backoff=%d, want 1 after a timeout", r.backoff)
|
||||||
|
}
|
||||||
|
// New data sent and freshly sampled, then acked.
|
||||||
|
r.postTx(dataSeg(iss+100, 100), int64(rtoInitial)+rtoMs)
|
||||||
|
r.postRx(ackSeg(iss+200), int64(rtoInitial)+30*rtoMs)
|
||||||
|
if r.backoff != 0 {
|
||||||
|
t.Errorf("backoff=%d, want 0 after a valid RTT sample", r.backoff)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_Clamped verifies CurrentRTO is clamped to [rtoMin, rtoMax].
|
||||||
|
func TestRTO_Clamped(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
r.rto = time.Nanosecond
|
||||||
|
if got := r.CurrentRTO(); got != rtoMin {
|
||||||
|
t.Errorf("CurrentRTO=%v, want floor %v", got, rtoMin)
|
||||||
|
}
|
||||||
|
r.rto = time.Hour
|
||||||
|
if got := r.CurrentRTO(); got != rtoMax {
|
||||||
|
t.Errorf("CurrentRTO=%v, want ceiling %v", got, rtoMax)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_UpdateRTTFirstSample verifies the first-measurement initialization of
|
||||||
|
// SRTT/RTTVAR (RFC 6298 §2.2).
|
||||||
|
func TestRTO_UpdateRTTFirstSample(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
r.updateRTT(100 * time.Millisecond)
|
||||||
|
if r.srtt != 100*time.Millisecond {
|
||||||
|
t.Errorf("srtt=%v, want 100ms", r.srtt)
|
||||||
|
}
|
||||||
|
if r.rttvar != 50*time.Millisecond {
|
||||||
|
t.Errorf("rttvar=%v, want 50ms", r.rttvar)
|
||||||
|
}
|
||||||
|
// RTO = SRTT + K*RTTVAR = 100 + 4*50 = 300ms.
|
||||||
|
if r.rto != 300*time.Millisecond {
|
||||||
|
t.Errorf("rto=%v, want 300ms", r.rto)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_PolicyHooksDeriveFromFrame exercises Timer through the [tcp.Policy]
|
||||||
|
// hooks, verifying it reads the segment out of the frame it is handed: sending
|
||||||
|
// data arms a deadline and a full ACK disarms it and yields the RTT sample.
|
||||||
|
func TestRTO_PolicyHooksDeriveFromFrame(t *testing.T) {
|
||||||
|
var clock int64
|
||||||
|
var r Timer
|
||||||
|
if err := r.Configure(func() int64 { return clock }); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var pol tcp.Policy = &r
|
||||||
|
pol.Reset()
|
||||||
|
|
||||||
|
pol.PostTx(nil, frameOf(t, dataSeg(1000, 100)))
|
||||||
|
if r.NextDeadline() == 0 {
|
||||||
|
t.Fatal("expected an armed deadline after sending data")
|
||||||
|
}
|
||||||
|
clock = 10 * rtoMs
|
||||||
|
if !pol.PreRx(nil, frameOf(t, ackSeg(1100))) {
|
||||||
|
t.Error("PreRx must keep")
|
||||||
|
}
|
||||||
|
pol.PostRx(nil, tcp.StateEstablished, frameOf(t, ackSeg(1100)))
|
||||||
|
if r.NextDeadline() != 0 {
|
||||||
|
t.Error("expected disarmed timer after full ack")
|
||||||
|
}
|
||||||
|
if r.SmoothedRTT() != 10*time.Millisecond {
|
||||||
|
t.Errorf("srtt=%v, want 10ms sampled through the hooks", r.SmoothedRTT())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_PreRxNeverDrops verifies the estimator keeps every segment and records
|
||||||
|
// nothing at PreRx time. Dropping is not its business, and the connection has not
|
||||||
|
// yet judged the segment: an acknowledgement for data never sent would otherwise
|
||||||
|
// collapse the backoff and take a bogus round-trip sample. Only accepted segments
|
||||||
|
// reach PostRx, which the Handler guarantees.
|
||||||
|
func TestRTO_PreRxNeverDrops(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(1000)
|
||||||
|
r.postTx(dataSeg(iss, 100), 0)
|
||||||
|
armed := r.NextDeadline()
|
||||||
|
if armed == 0 {
|
||||||
|
t.Fatal("timer must be armed after sending data")
|
||||||
|
}
|
||||||
|
|
||||||
|
// An acknowledgement far beyond anything sent, which the connection refuses.
|
||||||
|
if !r.PreRx(nil, frameOf(t, ackSeg(iss+100000))) {
|
||||||
|
t.Error("PreRx must keep: dropping is not the estimator's business")
|
||||||
|
}
|
||||||
|
if r.NextDeadline() != armed {
|
||||||
|
t.Errorf("deadline moved to %d at PreRx, want it left at %d", r.NextDeadline(), armed)
|
||||||
|
}
|
||||||
|
if r.SmoothedRTT() != 0 {
|
||||||
|
t.Errorf("took an RTT sample of %v at PreRx", r.SmoothedRTT())
|
||||||
|
}
|
||||||
|
if !r.Running() {
|
||||||
|
t.Error("timer disarmed at PreRx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRTO_RetransmitsZeroWindowProbe verifies the timer takes over the periodic
|
||||||
|
// probing of a closed send window. A zero-window probe is a single octet the peer
|
||||||
|
// cannot accept, so it goes unacknowledged; the timer must keep resending it, with
|
||||||
|
// exponential backoff, which is the persist-timer behaviour of RFC 9293 §3.8.6.1.
|
||||||
|
// The tcp package relies on this and refuses to probe without a policy installed.
|
||||||
|
func TestRTO_RetransmitsZeroWindowProbe(t *testing.T) {
|
||||||
|
r := newRTO()
|
||||||
|
const iss = uint32(5000)
|
||||||
|
probe := dataSeg(iss, 1) // The one-octet probe.
|
||||||
|
r.postTx(probe, 0)
|
||||||
|
|
||||||
|
now := int64(rtoInitial)
|
||||||
|
prevRTO := r.CurrentRTO()
|
||||||
|
for attempt := 1; attempt <= 4; attempt++ {
|
||||||
|
_, from, rtx := r.preTx(now, tcp.Value(iss))
|
||||||
|
if !rtx {
|
||||||
|
t.Fatalf("attempt %d: timer did not fire; the probe would never be resent", attempt)
|
||||||
|
}
|
||||||
|
if from != tcp.Value(iss) {
|
||||||
|
t.Errorf("attempt %d: retransmit from %d, want the probe octet at %d", attempt, from, iss)
|
||||||
|
}
|
||||||
|
if got := r.CurrentRTO(); got <= prevRTO {
|
||||||
|
t.Errorf("attempt %d: rto %v did not back off past %v", attempt, got, prevRTO)
|
||||||
|
}
|
||||||
|
prevRTO = r.CurrentRTO()
|
||||||
|
// The peer still cannot accept the octet, so it stays unacknowledged.
|
||||||
|
r.postTx(probe, now)
|
||||||
|
now += int64(prevRTO)
|
||||||
|
}
|
||||||
|
}
|
||||||
-206
@@ -1,206 +0,0 @@
|
|||||||
package tcp
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
const rtoMs = int64(time.Millisecond)
|
|
||||||
|
|
||||||
// rtoDataSeg builds a data segment of datalen octets starting at seq.
|
|
||||||
func rtoDataSeg(seq uint32, datalen int) Segment {
|
|
||||||
return Segment{SEQ: Value(seq), DATALEN: Size(datalen), Flags: FlagPSH | FlagACK}
|
|
||||||
}
|
|
||||||
|
|
||||||
// rtoAckSeg builds a bare ACK acknowledging up to ack.
|
|
||||||
func rtoAckSeg(ack uint32) Segment {
|
|
||||||
return Segment{ACK: Value(ack), Flags: FlagACK}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRTO() *RTO {
|
|
||||||
var r RTO
|
|
||||||
r.Reset()
|
|
||||||
return &r
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRTO_Reset(t *testing.T) {
|
|
||||||
var r RTO
|
|
||||||
r.Reset()
|
|
||||||
if r.rto != rtoInitial {
|
|
||||||
t.Errorf("initial rto=%v, want %v", r.rto, rtoInitial)
|
|
||||||
}
|
|
||||||
if r.CurrentRTO() != rtoInitial {
|
|
||||||
t.Errorf("CurrentRTO=%v, want %v", r.CurrentRTO(), rtoInitial)
|
|
||||||
}
|
|
||||||
if r.haveRTT {
|
|
||||||
t.Error("haveRTT should be false before first sample")
|
|
||||||
}
|
|
||||||
if r.Running() || r.NextDeadline() != 0 {
|
|
||||||
t.Error("timer must be disarmed after Reset")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_ArmOnSendSampleOnAck sends data, verifies the timer arms, then acks it
|
|
||||||
// and verifies an RTT sample is taken and the timer stops once all data is acked.
|
|
||||||
func TestRTO_ArmOnSendSampleOnAck(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
const iss = uint32(1000)
|
|
||||||
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), 0)
|
|
||||||
if !r.Running() {
|
|
||||||
t.Fatal("timer must arm after sending data")
|
|
||||||
}
|
|
||||||
if r.NextDeadline() != int64(rtoInitial) {
|
|
||||||
t.Errorf("deadline=%d, want %d", r.NextDeadline(), int64(rtoInitial))
|
|
||||||
}
|
|
||||||
|
|
||||||
// ACK arrives one RTT (40ms) later covering all sent data.
|
|
||||||
dir := r.PreRx(rtoAckSeg(iss+100), 40*rtoMs)
|
|
||||||
if !dir.Keep {
|
|
||||||
t.Error("PreRx must keep the segment")
|
|
||||||
}
|
|
||||||
if r.Running() {
|
|
||||||
t.Error("timer must stop once all data is acknowledged")
|
|
||||||
}
|
|
||||||
if r.SmoothedRTT() != 40*time.Millisecond {
|
|
||||||
t.Errorf("srtt=%v, want 40ms", r.SmoothedRTT())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_RetransmitOnTimeout verifies PreTx directs a go-back-N retransmit once
|
|
||||||
// the deadline passes with data outstanding, and backs the RTO off.
|
|
||||||
func TestRTO_RetransmitOnTimeout(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
const iss = uint32(1000)
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), 0)
|
|
||||||
|
|
||||||
if r.PreTx(int64(rtoInitial) - 1).RetransmitAll {
|
|
||||||
t.Fatal("must not retransmit before the deadline")
|
|
||||||
}
|
|
||||||
dir := r.PreTx(int64(rtoInitial))
|
|
||||||
if !dir.RetransmitAll {
|
|
||||||
t.Fatal("RTO must fire at the deadline with data outstanding")
|
|
||||||
}
|
|
||||||
if r.CurrentRTO() != 2*rtoInitial {
|
|
||||||
t.Errorf("rto=%v after one backoff, want %v", r.CurrentRTO(), 2*rtoInitial)
|
|
||||||
}
|
|
||||||
// The connection resends from snd.UNA; PostTx sees a retransmission.
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), int64(rtoInitial))
|
|
||||||
if r.timing {
|
|
||||||
t.Error("retransmitted segment must not be RTT-sampled (Karn)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_KarnNoSampleOnRetransmittedAck verifies that after a retransmission the
|
|
||||||
// ACK does not produce an RTT sample (Karn's algorithm).
|
|
||||||
func TestRTO_KarnNoSampleOnRetransmittedAck(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
const iss = uint32(1000)
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), 0)
|
|
||||||
// Timeout and retransmit.
|
|
||||||
r.PreTx(int64(rtoInitial))
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), int64(rtoInitial))
|
|
||||||
// ACK now arrives; no sample should be taken since timing was discarded.
|
|
||||||
r.PreRx(rtoAckSeg(iss+100), int64(rtoInitial)+10*rtoMs)
|
|
||||||
if r.haveRTT {
|
|
||||||
t.Error("no RTT sample should exist after a retransmission (Karn)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_TimerRestartsWhilePartiallyAcked verifies the timer restarts (not
|
|
||||||
// stops) when an ACK advances UNA but data remains in flight (RFC 6298 §5.3).
|
|
||||||
func TestRTO_TimerRestartsWhilePartiallyAcked(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
const iss = uint32(1000)
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), 0)
|
|
||||||
r.PostTx(rtoDataSeg(iss+100, 100), 0) // 200 octets outstanding, iss..iss+200.
|
|
||||||
|
|
||||||
dir := r.PreRx(rtoAckSeg(iss+100), 40*rtoMs) // acks first 100 only.
|
|
||||||
if !r.Running() {
|
|
||||||
t.Fatal("timer must remain armed while data is still in flight")
|
|
||||||
}
|
|
||||||
if r.NextDeadline() != 40*rtoMs+int64(r.CurrentRTO()) {
|
|
||||||
t.Errorf("deadline=%d, want %d", r.NextDeadline(), 40*rtoMs+int64(r.CurrentRTO()))
|
|
||||||
}
|
|
||||||
if !dir.Keep {
|
|
||||||
t.Error("PreRx must keep the segment")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_NoArmWithoutData verifies control-only segments neither arm the timer
|
|
||||||
// nor start an RTT sample.
|
|
||||||
func TestRTO_NoArmWithoutData(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
r.PostTx(Segment{SEQ: 1000, Flags: FlagACK}, 0) // pure ACK, DATALEN==0.
|
|
||||||
if r.Running() || r.timing {
|
|
||||||
t.Error("pure control segment must not arm the timer or start a sample")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_BackoffCollapsesOnValidSample verifies a valid RTT measurement
|
|
||||||
// collapses the exponential backoff counter (RFC 6298 §5.7).
|
|
||||||
func TestRTO_BackoffCollapsesOnValidSample(t *testing.T) {
|
|
||||||
r := newRTO()
|
|
||||||
const iss = uint32(1000)
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), 0)
|
|
||||||
r.PreTx(int64(rtoInitial)) // one timeout: backoff=1.
|
|
||||||
r.PostTx(rtoDataSeg(iss, 100), int64(rtoInitial)) // retransmit (no sample).
|
|
||||||
if r.backoff != 1 {
|
|
||||||
t.Fatalf("backoff=%d, want 1 after a timeout", r.backoff)
|
|
||||||
}
|
|
||||||
// New data sent and freshly sampled, then acked.
|
|
||||||
r.PostTx(rtoDataSeg(iss+100, 100), int64(rtoInitial)+rtoMs)
|
|
||||||
r.PreRx(rtoAckSeg(iss+200), int64(rtoInitial)+30*rtoMs)
|
|
||||||
if r.backoff != 0 {
|
|
||||||
t.Errorf("backoff=%d, want 0 after a valid RTT sample", r.backoff)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_Clamped verifies CurrentRTO is clamped to [rtoMin, rtoMax].
|
|
||||||
func TestRTO_Clamped(t *testing.T) {
|
|
||||||
var r RTO
|
|
||||||
r.Reset()
|
|
||||||
r.rto = time.Nanosecond
|
|
||||||
if got := r.CurrentRTO(); got != rtoMin {
|
|
||||||
t.Errorf("CurrentRTO=%v, want floor %v", got, rtoMin)
|
|
||||||
}
|
|
||||||
r.rto = time.Hour
|
|
||||||
if got := r.CurrentRTO(); got != rtoMax {
|
|
||||||
t.Errorf("CurrentRTO=%v, want ceiling %v", got, rtoMax)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_UpdateRTTFirstSample verifies the first-measurement initialization of
|
|
||||||
// SRTT/RTTVAR (RFC 6298 §2.2).
|
|
||||||
func TestRTO_UpdateRTTFirstSample(t *testing.T) {
|
|
||||||
var r RTO
|
|
||||||
r.Reset()
|
|
||||||
r.updateRTT(100 * time.Millisecond)
|
|
||||||
if r.srtt != 100*time.Millisecond {
|
|
||||||
t.Errorf("srtt=%v, want 100ms", r.srtt)
|
|
||||||
}
|
|
||||||
if r.rttvar != 50*time.Millisecond {
|
|
||||||
t.Errorf("rttvar=%v, want 50ms", r.rttvar)
|
|
||||||
}
|
|
||||||
// RTO = SRTT + K*RTTVAR = 100 + 4*50 = 300ms.
|
|
||||||
if r.rto != 300*time.Millisecond {
|
|
||||||
t.Errorf("rto=%v, want 300ms", r.rto)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRTO_ImplementsLossRecovery exercises RTO through the [LossRecovery]
|
|
||||||
// interface: sending data arms a deadline and a full ACK disarms it.
|
|
||||||
func TestRTO_ImplementsLossRecovery(t *testing.T) {
|
|
||||||
var lr LossRecovery = newRTO()
|
|
||||||
lr.Reset()
|
|
||||||
lr.PostTx(rtoDataSeg(1000, 100), 0)
|
|
||||||
if lr.NextDeadline() == 0 {
|
|
||||||
t.Error("expected an armed deadline after sending data")
|
|
||||||
}
|
|
||||||
if !lr.PreRx(rtoAckSeg(1100), 10*rtoMs).Keep {
|
|
||||||
t.Error("PreRx must keep")
|
|
||||||
}
|
|
||||||
if lr.NextDeadline() != 0 {
|
|
||||||
t.Error("expected disarmed timer after full ack")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-1
@@ -329,7 +329,7 @@ func TestWindowReject_ChallengeACK(t *testing.T) {
|
|||||||
SEQ: issB + 512,
|
SEQ: issB + 512,
|
||||||
ACK: issA,
|
ACK: issA,
|
||||||
Flags: FlagACK,
|
Flags: FlagACK,
|
||||||
WND: Size(1 << 17), // > MaxUint16.
|
WND: Size(maxWindow + 1), // beyond even the largest scaled window (RFC 7323).
|
||||||
}
|
}
|
||||||
err := tcb.Recv(seg)
|
err := tcb.Recv(seg)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
+58
-11
@@ -227,18 +227,36 @@ func (rtx *ringTx) RetransmitFromUNA() {
|
|||||||
if oldest == nil {
|
if oldest == nil {
|
||||||
return // Nothing in the retransmission queue.
|
return // Nothing in the retransmission queue.
|
||||||
}
|
}
|
||||||
unaSeq := oldest.seq
|
rtx.RetransmitFrom(oldest.seq)
|
||||||
if rtx.sentend != 0 {
|
}
|
||||||
// Merge sent region [sentoff, sentend) back into unsent.
|
|
||||||
rtx.unsentoff = rtx.sentoff
|
// RetransmitFrom rewinds the transmit queue so sent-but-unacked data from seq onward
|
||||||
if rtx.unsentend == 0 {
|
// becomes unsent again causing next [ringTx.MakePacket] to resend them.
|
||||||
rtx.unsentend = rtx.sentend
|
//
|
||||||
}
|
// Must be called when [ControlBlock.RetransmitFrom] returns true so the
|
||||||
rtx.sentoff = 0
|
// ring and control block state are coherent.
|
||||||
rtx.sentend = 0
|
func (rtx *ringTx) RetransmitFrom(seq Value) {
|
||||||
|
pkt := rtx.slist.packetContaining(seq)
|
||||||
|
if pkt == nil {
|
||||||
|
return // seq not in the retransmission queue.
|
||||||
}
|
}
|
||||||
// Clear packet metadata; sequence tracking restarts from UNA.
|
rewindOff, rewindSeq := pkt.off, pkt.seq
|
||||||
rtx.slist.Reset(cap(rtx.slist.pkts), unaSeq)
|
// The write position is unsentend, except when the unsent region is empty
|
||||||
|
// (unsentend==0) in which case data ends where the sent region ends. Capture
|
||||||
|
// it before reopening the unsent region over the rewound packets.
|
||||||
|
writeEnd := rtx.unsentend
|
||||||
|
if writeEnd == 0 {
|
||||||
|
writeEnd = rtx.sentend
|
||||||
|
}
|
||||||
|
if rewindOff == rtx.sentoff {
|
||||||
|
rtx.sentoff = 0 // Whole queue rewound: sent region becomes empty.
|
||||||
|
rtx.sentend = 0
|
||||||
|
} else {
|
||||||
|
rtx.sentend = rewindOff
|
||||||
|
}
|
||||||
|
rtx.unsentoff = rewindOff
|
||||||
|
rtx.unsentend = writeEnd
|
||||||
|
rtx.slist.truncateFrom(rewindSeq)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rtx *ringTx) consolidateBufs() {
|
func (rtx *ringTx) consolidateBufs() {
|
||||||
@@ -331,6 +349,35 @@ func (sl *sentlist) Free() int {
|
|||||||
return cap(sl.pkts) - len(sl.pkts)
|
return cap(sl.pkts) - len(sl.pkts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// packetContaining returns the queued packet whose sequence range covers seq, or
|
||||||
|
// nil when no packet does.
|
||||||
|
func (sl *sentlist) packetContaining(seq Value) *ringidx {
|
||||||
|
for i := range sl.pkts {
|
||||||
|
pkt := &sl.pkts[i]
|
||||||
|
if pkt.seq.LessThanEq(seq) && seq.LessThan(pkt.endSeq()) {
|
||||||
|
return pkt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncateFrom drops the packet starting at seq and every packet sent after it,
|
||||||
|
// so their data can be re-queued as unsent. seq must be a packet start sequence
|
||||||
|
// (see [sentlist.packetContaining]). When no packet survives, the auxiliary
|
||||||
|
// sequence counter is rewound to seq so [sentlist.EndSeq] keeps reporting where
|
||||||
|
// the next packet begins.
|
||||||
|
func (sl *sentlist) truncateFrom(seq Value) {
|
||||||
|
for i := range sl.pkts {
|
||||||
|
if sl.pkts[i].seq == seq {
|
||||||
|
sl.pkts = sl.pkts[:i]
|
||||||
|
if i == 0 {
|
||||||
|
sl.ssn = seq
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (sl *sentlist) AddPacket(datalen, off, bufsize int, seq Value) *ringidx {
|
func (sl *sentlist) AddPacket(datalen, off, bufsize int, seq Value) *ringidx {
|
||||||
free := sl.Free()
|
free := sl.Free()
|
||||||
if free == 0 {
|
if free == 0 {
|
||||||
|
|||||||
@@ -0,0 +1,215 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newRetransmitQueue builds a queue holding npkt sent packets of pktlen octets
|
||||||
|
// each, starting at iss, plus any leftover unsent data. It returns the queue and
|
||||||
|
// the full byte stream that was written.
|
||||||
|
func newRetransmitQueue(t *testing.T, bufsize, maxPkts, npkt, pktlen, unsent int, iss Value) (*ringTx, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
var rtx ringTx
|
||||||
|
if err := rtx.Reset(make([]byte, bufsize), maxPkts, iss); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
stream := make([]byte, npkt*pktlen+unsent)
|
||||||
|
for i := range stream {
|
||||||
|
stream[i] = byte(i + 1) // Non-zero so a stale ring shows up as a mismatch.
|
||||||
|
}
|
||||||
|
if n, err := rtx.Write(stream); err != nil || n != len(stream) {
|
||||||
|
t.Fatalf("write n=%d err=%v", n, err)
|
||||||
|
}
|
||||||
|
seq := iss
|
||||||
|
scratch := make([]byte, pktlen)
|
||||||
|
for i := range npkt {
|
||||||
|
n, err := rtx.MakePacket(scratch, seq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("packet %d: %v", i, err)
|
||||||
|
}
|
||||||
|
if n != pktlen {
|
||||||
|
t.Fatalf("packet %d: n=%d, want %d", i, n, pktlen)
|
||||||
|
}
|
||||||
|
seq += Value(n)
|
||||||
|
}
|
||||||
|
testQueueSanity(t, &rtx)
|
||||||
|
return &rtx, stream
|
||||||
|
}
|
||||||
|
|
||||||
|
// mustRemake asserts the queue re-emits datalen octets at seq matching want.
|
||||||
|
func mustRemake(t *testing.T, rtx *ringTx, seq Value, want []byte) {
|
||||||
|
t.Helper()
|
||||||
|
got := make([]byte, len(want))
|
||||||
|
n, err := rtx.MakePacket(got, seq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("MakePacket at seq %d: %v", seq, err)
|
||||||
|
}
|
||||||
|
if n != len(want) {
|
||||||
|
t.Fatalf("MakePacket at seq %d: n=%d, want %d", seq, n, len(want))
|
||||||
|
}
|
||||||
|
if !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("MakePacket at seq %d: got %v, want %v", seq, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitFromBoundary rewinds to the start of the second of three
|
||||||
|
// sent packets: the first stays sent, the rest become unsent and re-emit their
|
||||||
|
// original bytes.
|
||||||
|
func TestRingTx_RetransmitFromBoundary(t *testing.T) {
|
||||||
|
const iss, pktlen = Value(100), 4
|
||||||
|
rtx, stream := newRetransmitQueue(t, 64, 4, 3, pktlen, 0, iss)
|
||||||
|
|
||||||
|
sentBefore := rtx.BufferedSent()
|
||||||
|
rtx.RetransmitFrom(iss + pktlen) // Start of packet 2.
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
if got := rtx.BufferedSent(); got != pktlen {
|
||||||
|
t.Fatalf("sent=%d, want %d (only packet 1 remains sent)", got, pktlen)
|
||||||
|
}
|
||||||
|
if got := rtx.BufferedUnsent(); got != sentBefore-pktlen {
|
||||||
|
t.Fatalf("unsent=%d, want %d", got, sentBefore-pktlen)
|
||||||
|
}
|
||||||
|
mustRemake(t, rtx, iss+pktlen, stream[pktlen:2*pktlen])
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
mustRemake(t, rtx, iss+2*pktlen, stream[2*pktlen:3*pktlen])
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitFromMidPacket verifies a sequence inside a packet is
|
||||||
|
// snapped down to that packet's start: the queue tracks whole packets.
|
||||||
|
func TestRingTx_RetransmitFromMidPacket(t *testing.T) {
|
||||||
|
const iss, pktlen = Value(100), 4
|
||||||
|
rtx, stream := newRetransmitQueue(t, 64, 4, 3, pktlen, 0, iss)
|
||||||
|
|
||||||
|
rtx.RetransmitFrom(iss + pktlen + 2) // Two octets into packet 2.
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
if got := rtx.BufferedSent(); got != pktlen {
|
||||||
|
t.Fatalf("sent=%d, want %d: rewind must floor to the packet start", got, pktlen)
|
||||||
|
}
|
||||||
|
mustRemake(t, rtx, iss+pktlen, stream[pktlen:2*pktlen])
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitFromOldest rewinds the whole queue, which must match
|
||||||
|
// RetransmitFromUNA.
|
||||||
|
func TestRingTx_RetransmitFromOldest(t *testing.T) {
|
||||||
|
const iss, pktlen, npkt = Value(100), 4, 3
|
||||||
|
rtx, stream := newRetransmitQueue(t, 64, 4, npkt, pktlen, 0, iss)
|
||||||
|
rtx.RetransmitFrom(iss)
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
viaUNA, _ := newRetransmitQueue(t, 64, 4, npkt, pktlen, 0, iss)
|
||||||
|
viaUNA.RetransmitFromUNA()
|
||||||
|
testQueueSanity(t, viaUNA)
|
||||||
|
|
||||||
|
if rtx.BufferedSent() != 0 {
|
||||||
|
t.Fatalf("sent=%d, want 0 after a full rewind", rtx.BufferedSent())
|
||||||
|
}
|
||||||
|
if rtx.BufferedUnsent() != npkt*pktlen {
|
||||||
|
t.Fatalf("unsent=%d, want %d", rtx.BufferedUnsent(), npkt*pktlen)
|
||||||
|
}
|
||||||
|
if rtx.BufferedSent() != viaUNA.BufferedSent() || rtx.BufferedUnsent() != viaUNA.BufferedUnsent() {
|
||||||
|
t.Fatal("RetransmitFrom(oldest) must match RetransmitFromUNA")
|
||||||
|
}
|
||||||
|
mustRemake(t, rtx, iss, stream[:pktlen])
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitFromUnknownSeq verifies a sequence covered by no queued
|
||||||
|
// packet leaves the queue untouched.
|
||||||
|
func TestRingTx_RetransmitFromUnknownSeq(t *testing.T) {
|
||||||
|
const iss, pktlen, npkt = Value(100), 4, 3
|
||||||
|
rtx, _ := newRetransmitQueue(t, 64, 4, npkt, pktlen, 0, iss)
|
||||||
|
sent, unsent := rtx.BufferedSent(), rtx.BufferedUnsent()
|
||||||
|
|
||||||
|
rtx.RetransmitFrom(iss - 1) // Before the queue.
|
||||||
|
rtx.RetransmitFrom(iss + npkt*pktlen) // One past the last octet sent.
|
||||||
|
rtx.RetransmitFrom(iss + 1000) // Far beyond.
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
if rtx.BufferedSent() != sent || rtx.BufferedUnsent() != unsent {
|
||||||
|
t.Fatalf("queue moved: sent %d→%d, unsent %d→%d", sent, rtx.BufferedSent(), unsent, rtx.BufferedUnsent())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitWithUnsentTail verifies a rewind reopens the unsent region
|
||||||
|
// over the rewound packets without losing the unsent tail behind them.
|
||||||
|
func TestRingTx_RetransmitWithUnsentTail(t *testing.T) {
|
||||||
|
const iss, pktlen, npkt, tail = Value(100), 4, 2, 5
|
||||||
|
rtx, stream := newRetransmitQueue(t, 64, 4, npkt, pktlen, tail, iss)
|
||||||
|
if got := rtx.BufferedUnsent(); got != tail {
|
||||||
|
t.Fatalf("unsent tail=%d, want %d", got, tail)
|
||||||
|
}
|
||||||
|
|
||||||
|
rtx.RetransmitFrom(iss + pktlen) // Rewind the second packet only.
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
if got := rtx.BufferedUnsent(); got != pktlen+tail {
|
||||||
|
t.Fatalf("unsent=%d, want %d (rewound packet plus the tail)", got, pktlen+tail)
|
||||||
|
}
|
||||||
|
// The rewound packet re-emits first, then the tail follows in order.
|
||||||
|
mustRemake(t, rtx, iss+pktlen, stream[pktlen:2*pktlen])
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
mustRemake(t, rtx, iss+2*pktlen, stream[2*pktlen:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitAfterDrainedUnsent pins the write-position recovery: when
|
||||||
|
// every octet written has been packetized the unsent region is empty, so the
|
||||||
|
// rewind must reconstruct where data ends from the sent region.
|
||||||
|
func TestRingTx_RetransmitAfterDrainedUnsent(t *testing.T) {
|
||||||
|
const iss, pktlen, npkt = Value(100), 4, 3
|
||||||
|
rtx, stream := newRetransmitQueue(t, 64, 4, npkt, pktlen, 0, iss)
|
||||||
|
if got := rtx.BufferedUnsent(); got != 0 {
|
||||||
|
t.Fatalf("unsent=%d, want 0: all written data was packetized", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
rtx.RetransmitFrom(iss + pktlen)
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
|
||||||
|
if got := rtx.BufferedUnsent(); got != 2*pktlen {
|
||||||
|
t.Fatalf("unsent=%d, want %d: rewind lost the end of the data", got, 2*pktlen)
|
||||||
|
}
|
||||||
|
mustRemake(t, rtx, iss+pktlen, stream[pktlen:2*pktlen])
|
||||||
|
testQueueSanity(t, rtx)
|
||||||
|
mustRemake(t, rtx, iss+2*pktlen, stream[2*pktlen:3*pktlen])
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRingTx_RetransmitWrapped exercises a rewind on a queue whose regions wrap
|
||||||
|
// the end of the ring buffer.
|
||||||
|
func TestRingTx_RetransmitWrapped(t *testing.T) {
|
||||||
|
const bufsize, pktlen = 16, 4
|
||||||
|
const iss = Value(100)
|
||||||
|
var rtx ringTx
|
||||||
|
if err := rtx.Reset(make([]byte, bufsize), 4, iss); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Push the queue most of the way around the ring, acking as we go.
|
||||||
|
seq := iss
|
||||||
|
scratch := make([]byte, pktlen)
|
||||||
|
for round := range 3 {
|
||||||
|
chunk := make([]byte, pktlen)
|
||||||
|
for i := range chunk {
|
||||||
|
chunk[i] = byte(round*pktlen + i + 1)
|
||||||
|
}
|
||||||
|
if _, err := rtx.Write(chunk); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := rtx.MakePacket(scratch, seq); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
seq += Value(pktlen)
|
||||||
|
if round < 2 {
|
||||||
|
if err := rtx.RecvACK(seq); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
testQueueSanity(t, &rtx)
|
||||||
|
}
|
||||||
|
// Two packets outstanding, straddling the wrap. Rewind the newest.
|
||||||
|
rewindSeq := seq - Value(pktlen)
|
||||||
|
want := append([]byte(nil), scratch...)
|
||||||
|
rtx.RetransmitFrom(rewindSeq)
|
||||||
|
testQueueSanity(t, &rtx)
|
||||||
|
mustRemake(t, &rtx, rewindSeq, want)
|
||||||
|
testQueueSanity(t, &rtx)
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// synOptions parses the option block of a raw TCP frame and returns the MSS
|
||||||
|
// and window-scale values found, with ok flags for presence.
|
||||||
|
func synOptions(t *testing.T, frame []byte) (mss uint16, mssOK bool, shift uint8, shiftOK bool) {
|
||||||
|
t.Helper()
|
||||||
|
tfrm, err := NewFrame(frame)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var oc OptionCodec
|
||||||
|
err = oc.ForEachOption(tfrm.Options(), func(kind OptionKind, data []byte) error {
|
||||||
|
switch {
|
||||||
|
case kind == OptMaxSegmentSize && len(data) == 2:
|
||||||
|
mss = uint16(data[0])<<8 | uint16(data[1])
|
||||||
|
mssOK = true
|
||||||
|
case kind == OptWindowScale && len(data) == 1:
|
||||||
|
shift = data[0]
|
||||||
|
shiftOK = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return mss, mssOK, shift, shiftOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWindowScaleNegotiation walks the three-way handshake with asymmetric
|
||||||
|
// buffer sizes and verifies RFC 7323 §2 end to end on the wire: the SYN and
|
||||||
|
// SYN-ACK carry the shift derived from each side's receive buffer, SYN
|
||||||
|
// windows are never scaled (and saturate rather than wrap the 16-bit field),
|
||||||
|
// and the first post-handshake segment advertises the scaled window.
|
||||||
|
func TestWindowScaleNegotiation(t *testing.T) {
|
||||||
|
const clientBuf = 256 << 10 // shift 3: 256KiB>>3 = 32Ki fits, >>2 does not.
|
||||||
|
const serverBuf = 1 << 20 // shift 5: 1MiB>>5 = 32Ki fits, >>4 does not.
|
||||||
|
rng := rand.New(rand.NewSource(1))
|
||||||
|
client, server := new(Handler), new(Handler)
|
||||||
|
err := client.SetBuffers(make([]byte, 2048), make([]byte, clientBuf), 32)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = server.SetBuffers(make([]byte, 2048), make([]byte, serverBuf), 32)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
|
||||||
|
packetBuf := make([]byte, 2048)
|
||||||
|
|
||||||
|
// Client SYN: window-scale offer present, window field unscaled+saturated.
|
||||||
|
n, err := client.Send(packetBuf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, mssOK, shift, shiftOK := synOptions(t, packetBuf[:n])
|
||||||
|
if !mssOK {
|
||||||
|
t.Fatal("client SYN lacks MSS option")
|
||||||
|
}
|
||||||
|
if !shiftOK {
|
||||||
|
t.Fatal("client SYN lacks window-scale option")
|
||||||
|
}
|
||||||
|
if shift != 3 {
|
||||||
|
t.Errorf("client SYN shift = %d, want 3 (buffer %d)", shift, clientBuf)
|
||||||
|
}
|
||||||
|
tfrm, _ := NewFrame(packetBuf[:n])
|
||||||
|
if got := tfrm.WindowSize(); got != 0xFFFF {
|
||||||
|
t.Errorf("client SYN wire window = %d, want 65535 (saturated, never scaled)", got)
|
||||||
|
}
|
||||||
|
if err = server.Recv(packetBuf[:n]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server SYN-ACK: echoes its own shift because the SYN offered scaling.
|
||||||
|
clear(packetBuf)
|
||||||
|
n, err = server.Send(packetBuf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _, shift, shiftOK = synOptions(t, packetBuf[:n])
|
||||||
|
if !shiftOK {
|
||||||
|
t.Fatal("server SYN-ACK lacks window-scale option")
|
||||||
|
}
|
||||||
|
if shift != 5 {
|
||||||
|
t.Errorf("server SYN-ACK shift = %d, want 5 (buffer %d)", shift, serverBuf)
|
||||||
|
}
|
||||||
|
tfrm, _ = NewFrame(packetBuf[:n])
|
||||||
|
if got := tfrm.WindowSize(); got != 0xFFFF {
|
||||||
|
t.Errorf("server SYN-ACK wire window = %d, want 65535 (saturated, never scaled)", got)
|
||||||
|
}
|
||||||
|
if err = client.Recv(packetBuf[:n]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client handshake ACK: the first scaled window on the wire. The client
|
||||||
|
// advertises its whole free buffer, which only fits the field when
|
||||||
|
// right-shifted by its offered shift.
|
||||||
|
clear(packetBuf)
|
||||||
|
n, err = client.Send(packetBuf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tfrm, _ = NewFrame(packetBuf[:n])
|
||||||
|
wantWire := uint16(clientBuf >> 3)
|
||||||
|
if got := tfrm.WindowSize(); got != wantWire {
|
||||||
|
t.Errorf("client ACK wire window = %d, want %d (%d >> 3)", got, wantWire, clientBuf)
|
||||||
|
}
|
||||||
|
if err = server.Recv(packetBuf[:n]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// The server must have scaled the advertisement back up to real octets.
|
||||||
|
if got := server.scb.snd.WND; got != Size(clientBuf) {
|
||||||
|
t.Errorf("server snd.WND = %d, want %d (scaled back up)", got, clientBuf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWindowScaleBigTransfer proves the negotiated scale carries real data
|
||||||
|
// past the unscaled 64KiB ceiling: with 256KiB buffers on both sides the
|
||||||
|
// server streams segments without receiving a single ACK, and must be able
|
||||||
|
// to put more than 64KiB in flight before stalling on the send window. The
|
||||||
|
// client then receives everything intact.
|
||||||
|
func TestWindowScaleBigTransfer(t *testing.T) {
|
||||||
|
const bufSize = 256 << 10
|
||||||
|
const payload = 200 << 10
|
||||||
|
const mtu = 2048
|
||||||
|
rng := rand.New(rand.NewSource(2))
|
||||||
|
client, server := new(Handler), new(Handler)
|
||||||
|
err := client.SetBuffers(make([]byte, mtu), make([]byte, bufSize), 32)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = server.SetBuffers(make([]byte, bufSize), make([]byte, bufSize), 256)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
setupClientServer(t, rng, client, server)
|
||||||
|
packetBuf := make([]byte, mtu)
|
||||||
|
establish(t, client, server, packetBuf)
|
||||||
|
|
||||||
|
data := make([]byte, payload)
|
||||||
|
rng.Read(data)
|
||||||
|
nw, err := server.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if nw != payload {
|
||||||
|
t.Fatalf("server buffered %d of %d", nw, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream server→client WITHOUT delivering anything back: no ACKs, so
|
||||||
|
// everything sent stays in flight. Past 64KiB in flight is the proof
|
||||||
|
// that the scaled window governs the sender.
|
||||||
|
inFlight := 0
|
||||||
|
frames := make([][]byte, 0, payload/1024)
|
||||||
|
for {
|
||||||
|
clear(packetBuf)
|
||||||
|
n, err := server.Send(packetBuf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n <= sizeHeaderTCP {
|
||||||
|
break // window exhausted (or nothing left to send).
|
||||||
|
}
|
||||||
|
tfrm, _ := NewFrame(packetBuf[:n])
|
||||||
|
inFlight += len(tfrm.Payload())
|
||||||
|
frames = append(frames, append([]byte(nil), packetBuf[:n]...))
|
||||||
|
if inFlight >= payload {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if inFlight <= 0xFFFF {
|
||||||
|
t.Fatalf("server stalled at %d bytes in flight; scaled window should allow more than 65535", inFlight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliver the flight; the client must reassemble the stream intact.
|
||||||
|
for _, frm := range frames {
|
||||||
|
if err := client.Recv(frm); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
got := make([]byte, inFlight)
|
||||||
|
nr, err := client.Read(got)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if nr != inFlight {
|
||||||
|
t.Fatalf("client read %d of %d in-flight bytes", nr, inFlight)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(got[:nr], data[:nr]) {
|
||||||
|
t.Fatal("received data differs from sent data")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWindowScaleWireSafety covers the wire-conversion corners without a
|
||||||
|
// peer: no echo of the offer when the peer never gave one, and saturation
|
||||||
|
// (not wrap-around) of oversized windows for both SYN and non-SYN segments
|
||||||
|
// when scaling is off. Before window scaling existed a 128KiB receive buffer
|
||||||
|
// wrapped to a near-zero wire window on the SYN; that regression stays pinned
|
||||||
|
// here.
|
||||||
|
func TestWindowScaleWireSafety(t *testing.T) {
|
||||||
|
h := new(Handler)
|
||||||
|
err := h.SetBuffers(make([]byte, 2048), make([]byte, 128<<10), 32)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if h.wndShiftLocal != 2 {
|
||||||
|
// 128KiB>>1 = 65536 still overflows the field; >>2 = 32768 fits.
|
||||||
|
t.Errorf("wndShiftLocal = %d, want 2 for 128KiB buffer", h.wndShiftLocal)
|
||||||
|
}
|
||||||
|
|
||||||
|
var b [16]byte
|
||||||
|
if words := h.putSynOptions(b[:], 1460, true); words != 1 {
|
||||||
|
t.Errorf("SYN-ACK echoed window scale without a peer offer (words=%d)", words)
|
||||||
|
}
|
||||||
|
if words := h.putSynOptions(b[:], 1460, false); words != 2 {
|
||||||
|
t.Errorf("active SYN did not offer window scale (words=%d)", words)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scaling off: oversized windows saturate the 16-bit field.
|
||||||
|
if got := h.wireWnd(Segment{WND: 128 << 10, Flags: FlagACK}); got != 0xFFFF {
|
||||||
|
t.Errorf("unscaled oversized window = %d, want 65535", got)
|
||||||
|
}
|
||||||
|
// SYN never scales, even with a negotiated peer shift.
|
||||||
|
h.peerOfferedWS = true
|
||||||
|
if got := h.wireWnd(Segment{WND: 128 << 10, Flags: FlagSYN}); got != 0xFFFF {
|
||||||
|
t.Errorf("SYN window = %d, want 65535 (saturated, unscaled)", got)
|
||||||
|
}
|
||||||
|
// Established segment with negotiated scaling: shifted representation.
|
||||||
|
if got := h.wireWnd(Segment{WND: 128 << 10, Flags: FlagACK}); got != (128<<10)>>2 {
|
||||||
|
t.Errorf("scaled window = %d, want %d", got, (128<<10)>>2)
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-4
@@ -1,7 +1,6 @@
|
|||||||
package udp
|
package udp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/soypat/lneto"
|
"github.com/soypat/lneto"
|
||||||
@@ -117,7 +116,7 @@ func (h *Handler) Send(buf []byte) (int, error) {
|
|||||||
dgram := internal.SliceDequeueFront(&h.txDgrams)
|
dgram := internal.SliceDequeueFront(&h.txDgrams)
|
||||||
n, err := h.txRing.Read(buf[8 : 8+dgram.length])
|
n, err := h.txRing.Read(buf[8 : 8+dgram.length])
|
||||||
if err != nil || n != int(dgram.length) {
|
if err != nil || n != int(dgram.length) {
|
||||||
panic(fmt.Sprintf("udp send handler failure %d %s", n, err))
|
panic("udp send handler failure")
|
||||||
}
|
}
|
||||||
ufrm.SetSourcePort(h.lport)
|
ufrm.SetSourcePort(h.lport)
|
||||||
ufrm.SetDestinationPort(h.rport)
|
ufrm.SetDestinationPort(h.rport)
|
||||||
@@ -152,13 +151,13 @@ func (h *Handler) ReadNext(b []byte) (int, error) {
|
|||||||
dgram := internal.SliceDequeueFront(&h.rxDgrams)
|
dgram := internal.SliceDequeueFront(&h.rxDgrams)
|
||||||
n, err := h.rxRing.Read(b[:min(len(b), int(dgram.length))])
|
n, err := h.rxRing.Read(b[:min(len(b), int(dgram.length))])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Sprintf("udp read handler failure %d %s", n, err))
|
panic("udp readnext rx ring failure")
|
||||||
}
|
}
|
||||||
discard := int(dgram.length) - len(b)
|
discard := int(dgram.length) - len(b)
|
||||||
if discard > 0 {
|
if discard > 0 {
|
||||||
err = h.rxRing.ReadDiscard(discard)
|
err = h.rxRing.ReadDiscard(discard)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(fmt.Sprintf("udp readdiscard handler failure %d %s", n, err))
|
panic("udp readnext discard failure")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
|
|||||||
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
package udp
|
package udp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"math"
|
"math"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -226,7 +225,7 @@ func (mh *muxHandler) Encapsulate(carrierData []byte, ipOffset, frameOffset int)
|
|||||||
|
|
||||||
n, err := mh.txRing.Read(buf[8 : 8+dgram.length])
|
n, err := mh.txRing.Read(buf[8 : 8+dgram.length])
|
||||||
if err != nil || n != int(dgram.length) {
|
if err != nil || n != int(dgram.length) {
|
||||||
panic(fmt.Sprintf("udp send handler failure %d %s", n, err))
|
panic("udp muxh encaps fail txring read")
|
||||||
}
|
}
|
||||||
ufrm.SetSourcePort(dgram.lport)
|
ufrm.SetSourcePort(dgram.lport)
|
||||||
ufrm.SetDestinationPort(dgram.rport)
|
ufrm.SetDestinationPort(dgram.rport)
|
||||||
|
|||||||
+1
-2
@@ -2,7 +2,6 @@ package lneto
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -82,7 +81,7 @@ type BitPosErr struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (bpe *BitPosErr) Error() string {
|
func (bpe *BitPosErr) Error() string {
|
||||||
return fmt.Sprintf("%s at bits %d..%d", bpe.Err.Error(), bpe.BitStart, bpe.BitStart+bpe.BitLen)
|
return bpe.Err.Error()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bpe *BitPosErr) AppendError(dst []byte) []byte {
|
func (bpe *BitPosErr) AppendError(dst []byte) []byte {
|
||||||
|
|||||||
+35
-5
@@ -107,9 +107,30 @@ func (bs *bufferSelect) numFree() (numFree int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// getRx returns the oldest published Rx frame, or nil if none is pending.
|
// getRx returns the oldest published Rx frame, or nil if none is pending.
|
||||||
|
//
|
||||||
|
// The slot scan is not a consistent snapshot: goroPutRx may publish a frame
|
||||||
|
// into an already-scanned slot while this scan is in progress. Because the
|
||||||
|
// producer publishes frames in seq (arrival) order, any such straggler carries
|
||||||
|
// a lower seq than the candidate and must be delivered first to preserve
|
||||||
|
// arrival order. A confirming re-scan detects it; the loop retries until no
|
||||||
|
// older frame is observed, which terminates because the candidate seq strictly
|
||||||
|
// decreases and is bounded below by the true oldest pending frame.
|
||||||
func (bs *bufferSelect) getRx() []byte {
|
func (bs *bufferSelect) getRx() []byte {
|
||||||
oldest := -1
|
for {
|
||||||
var oldestSeq uint32
|
oldest, oldestSeq := bs.scanOldest()
|
||||||
|
if oldest < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !bs.hasPendingOlderThan(oldestSeq) {
|
||||||
|
return bs.bufs[oldest].buf[:bs.bufs[oldest].lenAcquire.Load()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// scanOldest returns the index and seq of the pending Rx frame with the lowest
|
||||||
|
// arrival seq, or -1 if none is pending.
|
||||||
|
func (bs *bufferSelect) scanOldest() (oldest int, oldestSeq uint32) {
|
||||||
|
oldest = -1
|
||||||
for i := range bs.bufs {
|
for i := range bs.bufs {
|
||||||
n := bs.bufs[i].lenAcquire.Load()
|
n := bs.bufs[i].lenAcquire.Load()
|
||||||
if n > 0 && bs.bufs[i].isRx.Load() &&
|
if n > 0 && bs.bufs[i].isRx.Load() &&
|
||||||
@@ -118,10 +139,19 @@ func (bs *bufferSelect) getRx() []byte {
|
|||||||
oldestSeq = bs.bufs[i].seq
|
oldestSeq = bs.bufs[i].seq
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if oldest < 0 {
|
return oldest, oldestSeq
|
||||||
return nil
|
}
|
||||||
|
|
||||||
|
// hasPendingOlderThan reports whether any pending Rx frame has a seq strictly
|
||||||
|
// less than seq, i.e. a frame that should be delivered before it.
|
||||||
|
func (bs *bufferSelect) hasPendingOlderThan(seq uint32) bool {
|
||||||
|
for i := range bs.bufs {
|
||||||
|
n := bs.bufs[i].lenAcquire.Load()
|
||||||
|
if n > 0 && bs.bufs[i].isRx.Load() && lessThan(bs.bufs[i].seq, seq) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return bs.bufs[oldest].buf[:bs.bufs[oldest].lenAcquire.Load()]
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (bs *bufferSelect) release(buf []byte) {
|
func (bs *bufferSelect) release(buf []byte) {
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package xnet
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto"
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
"github.com/soypat/lneto/internal/ltesto"
|
||||||
|
"github.com/soypat/lneto/tcp"
|
||||||
|
"github.com/soypat/lneto/tcp/rto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestTCPRetransmitsLostSegment drops exactly one data segment and requires the
|
||||||
|
// bytes to arrive anyway. It covers [TCPPoolConfig.NewPolicy] reaching the pooled
|
||||||
|
// and dialed connections alike: with no [tcp.Policy] installed nothing notices the
|
||||||
|
// loss, no retransmission is ever sent and the read below never completes.
|
||||||
|
//
|
||||||
|
// The server and the client each get an [ltesto.Sched] goroutine and the test
|
||||||
|
// thread drives them as a barrier: it only moves frames or advances the clock
|
||||||
|
// once both are parked, so the stacks are never touched concurrently. Time is
|
||||||
|
// simulated, so waiting out the one-second initial RTO (RFC 6298 §2.1) costs
|
||||||
|
// nothing and the outcome does not depend on how fast the machine is.
|
||||||
|
func TestTCPRetransmitsLostSegment(t *testing.T) {
|
||||||
|
const (
|
||||||
|
MTU = ethernet.MaxMTU
|
||||||
|
svPort = 80
|
||||||
|
bufSize = 2 << 10
|
||||||
|
want = "this segment is lost in transit"
|
||||||
|
// A quiet round means both sides are waiting on the network, which is
|
||||||
|
// what a lost segment looks like: only then does the clock move, so the
|
||||||
|
// RTO expires in a bounded number of rounds instead of in real time.
|
||||||
|
quietStep = 100 * time.Millisecond
|
||||||
|
maxRounds = 600
|
||||||
|
// Headers total 54 bytes, so a larger frame carries payload. Dropping a
|
||||||
|
// bare ACK would exercise the other direction's recovery instead.
|
||||||
|
minDataFrame = 14 + 20 + 20 + 8
|
||||||
|
)
|
||||||
|
client, sv := new(StackAsync), new(StackAsync)
|
||||||
|
if err := client.Reset(StackConfig{
|
||||||
|
Hostname: "rtx-client",
|
||||||
|
RandSeed: 11,
|
||||||
|
StaticAddress4: [4]byte{10, 0, 0, 90},
|
||||||
|
MaxActiveTCPPorts: 2,
|
||||||
|
HardwareAddress: [6]byte{0xbe, 0xef, 0, 0, 0, 90},
|
||||||
|
MTU: MTU,
|
||||||
|
ICMPQueueLimit: 2,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := sv.Reset(StackConfig{
|
||||||
|
Hostname: "rtx-server",
|
||||||
|
RandSeed: ^int64(11),
|
||||||
|
StaticAddress4: [4]byte{10, 0, 0, 91},
|
||||||
|
MaxActiveTCPPorts: 2,
|
||||||
|
HardwareAddress: [6]byte{0xbe, 0xef, 0, 0, 0, 91},
|
||||||
|
MTU: MTU,
|
||||||
|
ICMPQueueLimit: 2,
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
client.SetGatewayHardwareAddr(sv.HardwareAddr())
|
||||||
|
sv.SetGatewayHardwareAddr(client.HardwareAddr())
|
||||||
|
|
||||||
|
tsched := ltesto.NewSched(t)
|
||||||
|
svGoro, clGoro := tsched.Goro(), tsched.Goro()
|
||||||
|
|
||||||
|
// Simulated monotonic clock. Only the driver writes it, and only while every
|
||||||
|
// scheduled goroutine is parked, so it needs no synchronization of its own.
|
||||||
|
var now int64
|
||||||
|
nanotime := func() int64 { return now }
|
||||||
|
|
||||||
|
// Each side backs off into its own scheduler handle, so the driver can park
|
||||||
|
// and resume the two independently.
|
||||||
|
newPool := func(yield lneto.BackoffStrategy) TCPPoolConfig {
|
||||||
|
return TCPPoolConfig{
|
||||||
|
PoolSize: 2, QueueSize: 4,
|
||||||
|
TxBufSize: bufSize, RxBufSize: bufSize,
|
||||||
|
// Well past the simulated time this test spends, so the pool never
|
||||||
|
// reaps a connection out from under the retransmission.
|
||||||
|
EstablishedTimeout: 120 * time.Second,
|
||||||
|
ClosingTimeout: 120 * time.Second,
|
||||||
|
NanoTime: nanotime,
|
||||||
|
NewBackoff: func() lneto.BackoffStrategy { return yield },
|
||||||
|
NewPolicy: func() tcp.Policy {
|
||||||
|
timer := new(rto.Timer)
|
||||||
|
if err := timer.Configure(nanotime); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
return timer
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
svGo := sv.StackBlocking(svGoro.Yield).StackGo(StackGoConfig{
|
||||||
|
ListenerPoolConfig: newPool(svGoro.Yield),
|
||||||
|
})
|
||||||
|
clGo := client.StackBlocking(clGoro.Yield).StackGo(StackGoConfig{
|
||||||
|
ListenerPoolConfig: newPool(clGoro.Yield),
|
||||||
|
TCPDialTimeout: 60 * time.Second,
|
||||||
|
TCPDialRetries: 1,
|
||||||
|
})
|
||||||
|
svGo.blk._nanotime = nanotime
|
||||||
|
clGo.blk._nanotime = nanotime
|
||||||
|
|
||||||
|
lsAny, err := svGo.SocketNetip(context.Background(), "tcp", syscall.AF_INET, sockSTREAM,
|
||||||
|
netip.AddrPortFrom(netip.AddrFrom4(sv.Addr4()), svPort), netip.AddrPort{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
listener := lsAny.(net.Listener)
|
||||||
|
defer listener.Close()
|
||||||
|
|
||||||
|
// dropNext arms the driver to swallow the next server→client data frame. It
|
||||||
|
// is handed between the server goroutine and the driver by the scheduler
|
||||||
|
// handoff, which orders every access to it.
|
||||||
|
var dropNext, dropped bool
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
c, err := listener.Accept()
|
||||||
|
if err != nil {
|
||||||
|
svGoro.FinishWithErr(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
dropNext = true // The very next data frame is lost in transit.
|
||||||
|
_, err = c.Write([]byte(want))
|
||||||
|
c.Close() // Closing here is what makes #182's FIN-WAIT-1 retransmit matter.
|
||||||
|
svGoro.FinishWithErr(err)
|
||||||
|
}()
|
||||||
|
|
||||||
|
raddr := netip.AddrPortFrom(netip.AddrFrom4(sv.Addr4()), svPort)
|
||||||
|
go func() {
|
||||||
|
cAny, err := clGo.SocketNetip(context.Background(), "tcp", syscall.AF_INET, sockSTREAM,
|
||||||
|
netip.AddrPort{}, raddr)
|
||||||
|
if err != nil {
|
||||||
|
clGoro.FinishWithErr(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn := cAny.(net.Conn)
|
||||||
|
got := make([]byte, 0, len(want))
|
||||||
|
rb := make([]byte, 64)
|
||||||
|
for len(got) < len(want) {
|
||||||
|
n, err := conn.Read(rb)
|
||||||
|
got = append(got, rb[:n]...)
|
||||||
|
if err != nil {
|
||||||
|
clGoro.FinishWithErr(fmt.Errorf("read %d/%d bytes: %w", len(got), len(want), err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if string(got) != want {
|
||||||
|
clGoro.FinishWithErr(fmt.Errorf("read %q, want %q", got, want))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Closed before finishing: a Yield after FinishWithErr would never be
|
||||||
|
// serviced, since the driver stops resuming a goroutine it has reaped.
|
||||||
|
conn.Close()
|
||||||
|
clGoro.Finish()
|
||||||
|
}()
|
||||||
|
|
||||||
|
var buf [MTU + ethernet.MaxOverheadSize]byte
|
||||||
|
// pump moves one frame each way, dropping the armed one. Only ever called
|
||||||
|
// with both goroutines parked.
|
||||||
|
// Ingress errors are not fatal here: once a segment is dropped the frames
|
||||||
|
// behind it arrive past rcv.nxt and are rejected, which is precisely the
|
||||||
|
// stall the retransmission has to break. Egress errors are real faults.
|
||||||
|
pump := func() (moved bool) {
|
||||||
|
n, err := client.EgressEthernet(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client egress:", err)
|
||||||
|
} else if n > 0 {
|
||||||
|
sv.IngressEthernet(buf[:n])
|
||||||
|
moved = true
|
||||||
|
}
|
||||||
|
n, err = sv.EgressEthernet(buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("server egress:", err)
|
||||||
|
} else if n > 0 {
|
||||||
|
if dropNext && n > minDataFrame {
|
||||||
|
dropNext, dropped = false, true
|
||||||
|
} else {
|
||||||
|
client.IngressEthernet(buf[:n])
|
||||||
|
}
|
||||||
|
moved = true
|
||||||
|
}
|
||||||
|
return moved
|
||||||
|
}
|
||||||
|
|
||||||
|
for round := 0; ; round++ {
|
||||||
|
if round == maxRounds {
|
||||||
|
t.Fatalf("no retransmission after %d rounds and %v of simulated time (dropped=%v): is a Policy installed?",
|
||||||
|
maxRounds, time.Duration(now), dropped)
|
||||||
|
}
|
||||||
|
allFinished, err := tsched.AwaitAllParked()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("after losing one segment (dropped=%v): %v", dropped, err)
|
||||||
|
}
|
||||||
|
if allFinished {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !pump() {
|
||||||
|
now += int64(quietStep) // Both sides idle: let the RTO age.
|
||||||
|
}
|
||||||
|
tsched.YieldToAllParked()
|
||||||
|
}
|
||||||
|
if !dropped {
|
||||||
|
t.Fatal("no frame was dropped, so the test did not exercise retransmission")
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-1
@@ -53,6 +53,10 @@ type StackAsync struct {
|
|||||||
lookup dns.Message
|
lookup dns.Message
|
||||||
dnssv netip.Addr
|
dnssv netip.Addr
|
||||||
|
|
||||||
|
// ephPort drives sequential ephemeral-port allocation (see
|
||||||
|
// [StackAsync.ephemeralPort]); zero means not yet seeded.
|
||||||
|
ephPort uint32
|
||||||
|
|
||||||
ntpUDP internet.StackUDPPort
|
ntpUDP internet.StackUDPPort
|
||||||
ntp ntp.Client
|
ntp ntp.Client
|
||||||
|
|
||||||
@@ -125,8 +129,8 @@ func (s *StackAsync) IngressEthernet(ethernetFrame []byte) error {
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
s.stats.TotalReceived += uint64(len(ethernetFrame))
|
s.stats.TotalReceived += uint64(len(ethernetFrame))
|
||||||
err := s.link.Demux(ethernetFrame, 0)
|
|
||||||
debugPacket("IN ", ethernetFrame)
|
debugPacket("IN ", ethernetFrame)
|
||||||
|
err := s.link.Demux(ethernetFrame, 0)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
s.arpt.learnFromIngressEthernet(ethernetFrame)
|
s.arpt.learnFromIngressEthernet(ethernetFrame)
|
||||||
}
|
}
|
||||||
@@ -352,6 +356,23 @@ func (s *StackAsync) Prand32() (randval uint32) {
|
|||||||
return randval
|
return randval
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ephemeralPort returns the next port of the IANA dynamic range (49152-65535,
|
||||||
|
// RFC 6335 §6), allocated sequentially from a random per-stack start so a port is
|
||||||
|
// revisited only after the full 16384-port cycle. Random selection instead reuses
|
||||||
|
// a recent port at birthday-paradox rates, and a reused 4-tuple can collide with
|
||||||
|
// state the previous conversation left behind (a TIME-WAIT, a NAT flow entry)
|
||||||
|
// which swallows the new SYN.
|
||||||
|
func (s *StackAsync) ephemeralPort() uint16 {
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.ephPort == 0 {
|
||||||
|
s.ephPort = s.prand32()%16384 | 1
|
||||||
|
}
|
||||||
|
port := 49152 + s.ephPort%16384
|
||||||
|
s.ephPort++
|
||||||
|
s.mu.Unlock()
|
||||||
|
return uint16(port)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *StackAsync) prand32() uint32 {
|
func (s *StackAsync) prand32() uint32 {
|
||||||
/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
|
/* Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs" */
|
||||||
seed := internal.Prand32(s.prng)
|
seed := internal.Prand32(s.prng)
|
||||||
@@ -630,6 +651,9 @@ func (s *StackAsync) StartLookupIPType(host string, qtype dns.Type) error {
|
|||||||
s.ednsopt,
|
s.ednsopt,
|
||||||
},
|
},
|
||||||
EnableRecursion: true,
|
EnableRecursion: true,
|
||||||
|
// Leave headroom above the address buffer for CNAME records, which
|
||||||
|
// occupy answer slots before the addresses they alias.
|
||||||
|
MaxResponseAnswers: uint16(len(s.addrbufnip)) + 8,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
+11
-4
@@ -102,8 +102,9 @@ func (s StackGo) SocketNetip(ctx context.Context, network string, family, sotype
|
|||||||
isDial := raddr.IsValid() && !raddr.Addr().IsUnspecified()
|
isDial := raddr.IsValid() && !raddr.Addr().IsUnspecified()
|
||||||
if laddr.Port() == 0 {
|
if laddr.Port() == 0 {
|
||||||
// Auto-assign an ephemeral port for both outbound dials and for listeners
|
// Auto-assign an ephemeral port for both outbound dials and for listeners
|
||||||
// that did not request a fixed port.
|
// that did not request a fixed port. Sequential, not random: see
|
||||||
laddr = netip.AddrPortFrom(laddr.Addr(), uint16(49152+s.blk.async.Prand32()%16384))
|
// [StackAsync.ephemeralPort] for why random selection breaks dial churn.
|
||||||
|
laddr = netip.AddrPortFrom(laddr.Addr(), s.blk.async.ephemeralPort())
|
||||||
}
|
}
|
||||||
if laddr.Addr().IsUnspecified() {
|
if laddr.Addr().IsUnspecified() {
|
||||||
// Fill in the stack's configured address for the requested family.
|
// Fill in the stack's configured address for the requested family.
|
||||||
@@ -175,13 +176,19 @@ func (s StackGo) SocketNetip(ctx context.Context, network string, family, sotype
|
|||||||
if isDial {
|
if isDial {
|
||||||
var conn tcp.Conn
|
var conn tcp.Conn
|
||||||
// DIAL TCP: active connection a.k.a TCP Client branch.
|
// DIAL TCP: active connection a.k.a TCP Client branch.
|
||||||
err = conn.Configure(tcp.ConnConfig{
|
conncfg := tcp.ConnConfig{
|
||||||
// TODO(pato): Eventually add UDP configuration. we use TCP for now for simplicity's sake.
|
// TODO(pato): Eventually add UDP configuration. we use TCP for now for simplicity's sake.
|
||||||
TxBuf: make([]byte, s.plcfg.TxBufSize),
|
TxBuf: make([]byte, s.plcfg.TxBufSize),
|
||||||
RxBuf: make([]byte, s.plcfg.RxBufSize),
|
RxBuf: make([]byte, s.plcfg.RxBufSize),
|
||||||
TxPacketQueueSize: s.plcfg.QueueSize,
|
TxPacketQueueSize: s.plcfg.QueueSize,
|
||||||
RWBackoff: s.plcfg.NewBackoff(),
|
RWBackoff: s.plcfg.NewBackoff(),
|
||||||
})
|
}
|
||||||
|
if s.plcfg.NewPolicy != nil {
|
||||||
|
// A dialed connection needs loss recovery as much as a pooled
|
||||||
|
// one. See [TCPPoolConfig.NewPolicy].
|
||||||
|
conncfg.Policy = s.plcfg.NewPolicy()
|
||||||
|
}
|
||||||
|
err = conn.Configure(conncfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-2
@@ -42,8 +42,9 @@ type TCPPoolConfig struct {
|
|||||||
ConnLogger *slog.Logger
|
ConnLogger *slog.Logger
|
||||||
|
|
||||||
// NanoTime returns the current monotonic time in nanoseconds.
|
// NanoTime returns the current monotonic time in nanoseconds.
|
||||||
// Used for pool timeout tracking and passed to each [tcp.Conn] for
|
// Used for pool timeout tracking. If nil, defaults to time.Now().UnixNano().
|
||||||
// retransmission timing (RFC 6298). If nil, defaults to time.Now().UnixNano().
|
// Retransmission timing is not driven by this clock: a [tcp.Policy] carries
|
||||||
|
// its own. See NewPolicy.
|
||||||
NanoTime func() int64
|
NanoTime func() int64
|
||||||
// EstablishedTimeout sets the timeout for a TCP connection since it is acquired until it is established.
|
// EstablishedTimeout sets the timeout for a TCP connection since it is acquired until it is established.
|
||||||
// If the connection does not establish in this time it will be closed by the pool.
|
// If the connection does not establish in this time it will be closed by the pool.
|
||||||
@@ -56,6 +57,9 @@ type TCPPoolConfig struct {
|
|||||||
// NewBackoff returns the backoff to use for every newly configured TCP connection. Must be non-nil.
|
// NewBackoff returns the backoff to use for every newly configured TCP connection. Must be non-nil.
|
||||||
// This should always return a static(non-method) function unless you know what you are doing.
|
// This should always return a static(non-method) function unless you know what you are doing.
|
||||||
NewBackoff func() lneto.BackoffStrategy
|
NewBackoff func() lneto.BackoffStrategy
|
||||||
|
// NewPolicy if non-nil creates a [tcp.Policy] for each [tcp.Conn] used by the configured Listener.
|
||||||
|
// NewPolicy should not return reused policies unless the algorithm is stateless. See [tcp.Policy] for more information.
|
||||||
|
NewPolicy func() tcp.Policy
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTCPPool(cfg TCPPoolConfig) (*TCPPool, error) {
|
func NewTCPPool(cfg TCPPoolConfig) (*TCPPool, error) {
|
||||||
@@ -88,6 +92,11 @@ func NewTCPPool(cfg TCPPoolConfig) (*TCPPool, error) {
|
|||||||
Logger: cfg.ConnLogger,
|
Logger: cfg.ConnLogger,
|
||||||
RWBackoff: cfg.NewBackoff(),
|
RWBackoff: cfg.NewBackoff(),
|
||||||
}
|
}
|
||||||
|
if cfg.NewPolicy != nil {
|
||||||
|
// One Policy per connection: it shadows that connection's send
|
||||||
|
// sequence space and so cannot be shared.
|
||||||
|
conncfg.Policy = cfg.NewPolicy()
|
||||||
|
}
|
||||||
err := pool.conns[i].Configure(conncfg)
|
err := pool.conns[i].Configure(conncfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -156,6 +156,14 @@ func buildDNSResponsePacket(t *testing.T, txid uint16, dstPort uint16, hostname
|
|||||||
dns.NewResource(name, dns.TypeA, dns.ClassINET, 300, addr.AsSlice()),
|
dns.NewResource(name, dns.TypeA, dns.ClassINET, 300, addr.AsSlice()),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
return buildDNSMsgResponsePacket(t, txid, dstPort, msg, srcIP, srcMAC, dstIP, dstMAC, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildDNSMsgResponsePacket wraps a DNS response message into a complete
|
||||||
|
// Ethernet+IP+UDP packet with valid checksums.
|
||||||
|
func buildDNSMsgResponsePacket(t *testing.T, txid uint16, dstPort uint16, msg dns.Message,
|
||||||
|
srcIP netip.Addr, srcMAC [6]byte, dstIP netip.Addr, dstMAC [6]byte, buf []byte) ([]byte, error) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
// Response flags: QR=1 (response), RD=1 (recursion desired), RA=1 (recursion available).
|
// Response flags: QR=1 (response), RD=1 (recursion desired), RA=1 (recursion available).
|
||||||
responseFlags := dns.HeaderFlags(1<<15 | 1<<8 | 1<<7)
|
responseFlags := dns.HeaderFlags(1<<15 | 1<<8 | 1<<7)
|
||||||
@@ -237,3 +245,97 @@ var errBaseLenDNS = func() error {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
var errInvalidEtherType = errors.New("invalid ethernet type")
|
var errInvalidEtherType = errors.New("invalid ethernet type")
|
||||||
|
|
||||||
|
// TestDNS_CNAMEResponse verifies that a DNS response containing a CNAME record
|
||||||
|
// followed by an A record for the canonical name resolves to the A record's
|
||||||
|
// address: the CNAME RDATA must not be misinterpreted as an IP address.
|
||||||
|
func TestDNS_CNAMEResponse(t *testing.T) {
|
||||||
|
const seed = 9876
|
||||||
|
const MTU = ethernet.MaxMTU
|
||||||
|
|
||||||
|
client := new(StackAsync)
|
||||||
|
dnsServerAddr := netip.AddrFrom4([4]byte{8, 8, 8, 8})
|
||||||
|
clientAddr := netip.AddrFrom4([4]byte{10, 0, 0, 100})
|
||||||
|
clientMAC := [6]byte{0xde, 0xad, 0xbe, 0xef, 0x00, 0x01}
|
||||||
|
dnsServerMAC := [6]byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55}
|
||||||
|
|
||||||
|
err := client.Reset(StackConfig{
|
||||||
|
Hostname: "DNSClient",
|
||||||
|
RandSeed: seed,
|
||||||
|
StaticAddress4: clientAddr.As4(),
|
||||||
|
DNSServer: dnsServerAddr,
|
||||||
|
HardwareAddress: clientMAC,
|
||||||
|
MTU: uint16(MTU),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("client Reset failed:", err)
|
||||||
|
}
|
||||||
|
client.SetGatewayHardwareAddr(dnsServerMAC)
|
||||||
|
|
||||||
|
const hostname = "www.example.com"
|
||||||
|
const alias = "cdn.example.net"
|
||||||
|
wantAddr := netip.MustParseAddr("192.0.2.200")
|
||||||
|
|
||||||
|
err = client.StartLookupIP(hostname)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("StartLookupIP failed:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
const carrierDataSize = ethernet.MaxFrameLength
|
||||||
|
var buf [carrierDataSize]byte
|
||||||
|
|
||||||
|
// Client sends DNS query for www.example.com.
|
||||||
|
n, err := client.EgressEthernet(buf[:])
|
||||||
|
if err != nil || n == 0 {
|
||||||
|
t.Fatal("expected DNS query packet from client:", err, n)
|
||||||
|
}
|
||||||
|
txid, clientPort, err := extractDNSTxIDAndPort(buf[:n])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to extract DNS txid:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Respond with a CNAME record www.example.com -> cdn.example.net
|
||||||
|
// followed by the A record for cdn.example.net.
|
||||||
|
owner, err := dns.NewName(hostname)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
aliasName, err := dns.NewName(alias)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
aliasWire, err := aliasName.AppendTo(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
msg := dns.Message{
|
||||||
|
Questions: []dns.Question{{
|
||||||
|
Name: owner,
|
||||||
|
Type: dns.TypeA,
|
||||||
|
Class: dns.ClassINET,
|
||||||
|
}},
|
||||||
|
Answers: []dns.Resource{
|
||||||
|
dns.NewResource(owner, dns.TypeCNAME, dns.ClassINET, 300, aliasWire),
|
||||||
|
dns.NewResource(aliasName, dns.TypeA, dns.ClassINET, 300, wantAddr.AsSlice()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
responsePkt, err := buildDNSMsgResponsePacket(t, txid, clientPort, msg,
|
||||||
|
dnsServerAddr, dnsServerMAC, clientAddr, clientMAC, buf[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to build CNAME response packet:", err)
|
||||||
|
}
|
||||||
|
if err = client.IngressEthernet(responsePkt); err != nil {
|
||||||
|
t.Fatal("client Demux of CNAME response failed:", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
addrs, done, err := client.ResultLookupIP(hostname)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("ResultLookupIP error:", err)
|
||||||
|
}
|
||||||
|
if !done {
|
||||||
|
t.Fatal("DNS lookup not done after receiving CNAME response")
|
||||||
|
}
|
||||||
|
if !slices.Contains(addrs, wantAddr) {
|
||||||
|
t.Errorf("expected address %s not found in result %v", wantAddr, addrs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1196,3 +1196,39 @@ func TestEgressIP_TCPMSSAdvertisesMTU(t *testing.T) {
|
|||||||
t.Errorf("advertised MSS = %d, want %d (MTU %d - 40)", gotMSS, wantMSS, mtu)
|
t.Errorf("advertised MSS = %d, want %d (MTU %d - 40)", gotMSS, wantMSS, mtu)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestEphemeralPortSequence checks no ephemeral port is reused before the whole
|
||||||
|
// 16384-port dynamic range has cycled, which is what keeps a redial off the
|
||||||
|
// teardown state (TIME-WAIT, NAT flow entries) of the conversation before it.
|
||||||
|
func TestEphemeralPortSequence(t *testing.T) {
|
||||||
|
s := new(StackAsync)
|
||||||
|
err := s.Reset(StackConfig{
|
||||||
|
Hostname: "eph",
|
||||||
|
RandSeed: 42,
|
||||||
|
StaticAddress4: [4]byte{10, 0, 0, 50},
|
||||||
|
MaxActiveTCPPorts: 1,
|
||||||
|
HardwareAddress: [6]byte{0xbe, 0xef, 0, 0, 0, 50},
|
||||||
|
MTU: ethernet.MaxMTU,
|
||||||
|
ICMPQueueLimit: 2,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
const cycle = 16384
|
||||||
|
var seen [cycle]bool
|
||||||
|
for i := range cycle {
|
||||||
|
port := s.ephemeralPort()
|
||||||
|
if port < 49152 {
|
||||||
|
t.Fatalf("port %d below dynamic range (RFC 6335)", port)
|
||||||
|
}
|
||||||
|
idx := port - 49152
|
||||||
|
if seen[idx] {
|
||||||
|
t.Fatalf("port %d reused after only %d allocations (want full %d cycle)", port, i, cycle)
|
||||||
|
}
|
||||||
|
seen[idx] = true
|
||||||
|
}
|
||||||
|
// The cycle is exhausted: the next allocation may legitimately reuse.
|
||||||
|
if got := s.ephemeralPort(); got < 49152 {
|
||||||
|
t.Fatalf("post-cycle port %d below dynamic range", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user