mirror of
https://github.com/soypat/lneto.git
synced 2026-08-30 03:19:07 +00:00
Compare commits
8 Commits
tcp-policy
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d219daa2c4 | |||
| 75f1e02a20 | |||
| ab9d3ee691 | |||
| e6a5be3628 | |||
| 56f943ed30 | |||
| c879d0497c | |||
| 6313b1570d | |||
| 21f477b86e |
@@ -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,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)
|
||||||
|
|||||||
+4
-2
@@ -25,7 +25,9 @@ type ResolveConfig struct {
|
|||||||
Additional []Resource
|
Additional []Resource
|
||||||
EnableRecursion bool
|
EnableRecursion bool
|
||||||
// MaxResponseAnswers limits how many answer records are decoded from the
|
// MaxResponseAnswers limits how many answer records are decoded from the
|
||||||
// DNS response. If zero it defaults to the number of Questions.
|
// 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
|
MaxResponseAnswers uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +39,7 @@ 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
|
maxAns := cfg.MaxResponseAnswers
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
+72
-16
@@ -99,6 +99,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 +305,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()
|
||||||
}
|
}
|
||||||
@@ -411,6 +447,15 @@ 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()}
|
||||||
|
}
|
||||||
|
|
||||||
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.
|
||||||
@@ -460,8 +505,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) {
|
||||||
|
|||||||
+148
-2
@@ -239,6 +239,152 @@ func TestDecodeMessage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Regression test for CNAME-following: a response for www.yahoo.co.jp
|
||||||
|
// contains a CNAME record to edge12.g.yimg.jp (with compressed labels in its
|
||||||
|
// 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)
|
||||||
|
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: (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)
|
||||||
|
var client Client
|
||||||
|
err := client.StartResolve(clientPort, txid, ResolveConfig{
|
||||||
|
Questions: []Question{{
|
||||||
|
Name: name,
|
||||||
|
Type: TypeA,
|
||||||
|
Class: ClassINET,
|
||||||
|
}},
|
||||||
|
EnableRecursion: true,
|
||||||
|
MaxResponseAnswers: 6,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
var addrs [4]netip.Addr
|
||||||
|
n, err := client.ResponseAnswerLookup(addrs[:], hostname)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("failed to look up DNS response answers:", err)
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
t.Fatalf("expected 1 answer, got %d: %v", n, addrs[:n])
|
||||||
|
}
|
||||||
|
if addrs[0] != (netip.AddrFrom4([4]byte{182, 22, 23, 124})) {
|
||||||
|
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) {
|
func TestClient_ReceivesDNSResponse(t *testing.T) {
|
||||||
const hostname = "example.com"
|
const hostname = "example.com"
|
||||||
const txid = uint16(12345)
|
const txid = uint16(12345)
|
||||||
@@ -254,7 +400,7 @@ func TestClient_ReceivesDNSResponse(t *testing.T) {
|
|||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
responseIPs [][4]byte
|
responseIPs [][4]byte
|
||||||
wantAnswers int
|
wantAnswers int // Addresses returned by ResponseAnswerLookup and copied by ResponseCopyTo.
|
||||||
}{
|
}{
|
||||||
{name: "single_answer", responseIPs: allIPs[:1], wantAnswers: 1},
|
{name: "single_answer", responseIPs: allIPs[:1], wantAnswers: 1},
|
||||||
{name: "multiple_answers", responseIPs: allIPs[:4], wantAnswers: 4},
|
{name: "multiple_answers", responseIPs: allIPs[:4], wantAnswers: 4},
|
||||||
@@ -312,7 +458,7 @@ func TestClient_ReceivesDNSResponse(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("failed to look up DNS response answers:", err)
|
t.Fatal("failed to look up DNS response answers:", err)
|
||||||
}
|
}
|
||||||
if answers != uint16(tt.wantAnswers) {
|
if int(answers) != tt.wantAnswers {
|
||||||
t.Fatalf("expected %d answers, got %d", tt.wantAnswers, answers)
|
t.Fatalf("expected %d answers, got %d", tt.wantAnswers, answers)
|
||||||
}
|
}
|
||||||
for i := 0; i < tt.wantAnswers; i++ {
|
for i := 0; i < tt.wantAnswers; i++ {
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
}
|
||||||
|
|||||||
+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
|
||||||
|
|||||||
+8
-5
@@ -279,10 +279,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.
|
||||||
@@ -522,8 +521,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
|
||||||
|
|||||||
@@ -329,6 +329,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 {
|
||||||
|
|||||||
@@ -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,120 @@
|
|||||||
|
package tcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/soypat/lneto/ethernet"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestHandlerRetransmitsAfterRTO covers the seam between a Handler and its
|
||||||
|
// LossRecovery, which the RTO unit tests do not: a lost data segment must be
|
||||||
|
// resent once the timer expires, with nothing arriving to prompt it.
|
||||||
|
func TestHandlerRetransmitsAfterRTO(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.SetLossRecovery(new(RTO), 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 loss-recovery 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHandlerRetransmitsAfterCloseWithUnackedData 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 TestHandlerRetransmitsAfterCloseWithUnackedData(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.SetLossRecovery(new(RTO), 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
-3
@@ -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)
|
||||||
@@ -629,8 +650,10 @@ func (s *StackAsync) StartLookupIPType(host string, qtype dns.Type) error {
|
|||||||
Additional: []dns.Resource{
|
Additional: []dns.Resource{
|
||||||
s.ednsopt,
|
s.ednsopt,
|
||||||
},
|
},
|
||||||
EnableRecursion: true,
|
EnableRecursion: true,
|
||||||
MaxResponseAnswers: uint16(len(s.addrbufnip)),
|
// 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
|
||||||
|
|||||||
+3
-2
@@ -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.
|
||||||
|
|||||||
@@ -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