Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions client_hello.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (c *clientHello) marshal(aad bool) ([]byte, error) {
for _, ext := range c.Extensions {
b.AddUint16(ext.Type)
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
if aad && ext.Type == 0xfe0d {
if aad && ext.Type == 0xfe0d && c.echExt != nil && len(ext.Data) >= len(c.echExt.Payload) {
n := len(ext.Data) - len(c.echExt.Payload)
b.AddBytes(ext.Data[:n])
b.AddBytes(make([]byte, len(ext.Data[n:])))
Expand Down Expand Up @@ -231,7 +231,12 @@ func (c *clientHello) parseExtensions() error {
c.tls13 = false
c.echExt = nil

seen := make(map[uint16]bool, len(c.Extensions))
for _, ext := range c.Extensions {
if seen[ext.Type] {
return fmt.Errorf("%w: duplicate extension 0x%x", ErrIllegalParameter, ext.Type)
}
seen[ext.Type] = true
data := cryptobyte.String(ext.Data)
switch ext.Type {
case 0:
Expand All @@ -256,7 +261,7 @@ func (c *clientHello) parseExtensions() error {
// } ServerNameList;

var serverNameList cryptobyte.String
if !data.ReadUint16LengthPrefixed(&serverNameList) {
if !data.ReadUint16LengthPrefixed(&serverNameList) || !data.Empty() {
return fmt.Errorf("%w: serverNameList", ErrDecodeError)
}
for !serverNameList.Empty() {
Expand Down Expand Up @@ -291,7 +296,7 @@ func (c *clientHello) parseExtensions() error {
// ProtocolName protocol_name_list<2..2^16-1>
// } ProtocolNameList;
var protocolNameList cryptobyte.String
if !data.ReadUint16LengthPrefixed(&protocolNameList) {
if !data.ReadUint16LengthPrefixed(&protocolNameList) || !data.Empty() {
return fmt.Errorf("%w: protocol name list", ErrDecodeError)
}
for !protocolNameList.Empty() {
Expand All @@ -312,7 +317,7 @@ func (c *clientHello) parseExtensions() error {
// };
// } SupportedVersions;
var versions cryptobyte.String
if !data.ReadUint8LengthPrefixed(&versions) {
if !data.ReadUint8LengthPrefixed(&versions) || !data.Empty() {
return fmt.Errorf("%w: supported versions", ErrDecodeError)
}
for !versions.Empty() {
Expand Down Expand Up @@ -380,6 +385,9 @@ func (c *clientHello) parseExtensions() error {
}
c.echExt.Payload = slices.Clone(v)
}
if !data.Empty() {
return fmt.Errorf("%w: ech ext trailing data", ErrDecodeError)
}
}
}
return nil
Expand Down
25 changes: 22 additions & 3 deletions dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"io"
"iter"
"net"
"reflect"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -113,6 +114,10 @@ type Dialer[T any] struct {
// DialFunc must be set to a function that will be used to connect to
// a network address. NewDialer automatically sets this value.
DialFunc func(ctx context.Context, network, addr string, tc *tls.Config) (T, error)
// CloseFunc is an optional function used to close a connection when
// another concurrent connection attempt has already succeeded. If nil,
// io.Closer is used when implemented by T.
CloseFunc func(T) error
}

// Dial connects to the given network and address. It uses HTTPS DNS records to
Expand Down Expand Up @@ -197,8 +202,17 @@ func (d *Dialer[T]) Dial(ctx context.Context, network, addr string, tc *tls.Conf
sendConn := func(conn T) {
select {
case <-ctx.Done():
if c, ok := any(conn).(io.Closer); ok {
if d.CloseFunc != nil {
d.CloseFunc(conn)
} else if c, ok := any(conn).(io.Closer); ok {
c.Close()
} else if v := reflect.ValueOf(conn); v.IsValid() {
if m := v.MethodByName("CloseWithError"); m.IsValid() {
t := m.Type()
if t.NumIn() == 2 && t.In(0).Kind() == reflect.Uint64 && t.In(1).Kind() == reflect.String {
m.Call([]reflect.Value{reflect.Zero(t.In(0)), reflect.ValueOf("")})
}
}
}
case connChan <- conn:
}
Expand Down Expand Up @@ -280,17 +294,22 @@ func (d *Dialer[T]) Dial(ctx context.Context, network, addr string, tc *tls.Conf

go func() {
first := true
loop:
for target := range targets {
if !first {
select {
case <-ctx.Done():
break
break loop
case <-wakeChan:
case <-time.After(delay):
}
}
first = false
targetChan <- target
select {
case <-ctx.Done():
break loop
case targetChan <- target:
}
}
close(targetChan)
}()
Expand Down
165 changes: 165 additions & 0 deletions dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import (
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -276,3 +279,165 @@ func TestDialer(t *testing.T) {
}
})
}

type fakeCloserConn struct {
addr string
closed *atomic.Int32
}

func (c *fakeCloserConn) Close() error {
c.closed.Add(1)
return nil
}

type fakeAppErrorCode uint64

type fakeQUICConn struct {
addr string
closed *atomic.Int32
}

func (c *fakeQUICConn) CloseWithError(_ fakeAppErrorCode, _ string) error {
c.closed.Add(1)
return nil
}

func TestDialerStopsAndClosesLosingConns(t *testing.T) {
var resolvedH2 atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
body, _ := io.ReadAll(req.Body)
qq, err := dns.DecodeMessage(body)
if err != nil {
t.Errorf("dns.DecodeMessage: %v", err)
return
}
qq.QR = 1
q := qq.Question[0]
switch q.Name {
case "h1.example.com":
if q.Type == 1 {
qq.Answer = []dns.RR{
{Name: "h1.example.com", Type: 1, Class: 1, TTL: 60, Data: net.IP{1, 0, 0, 1}},
{Name: "h1.example.com", Type: 1, Class: 1, TTL: 60, Data: net.IP{1, 0, 0, 2}},
{Name: "h1.example.com", Type: 1, Class: 1, TTL: 60, Data: net.IP{1, 0, 0, 3}},
}
}
case "h2.example.com":
resolvedH2.Add(1)
if q.Type == 1 {
qq.Answer = []dns.RR{
{Name: "h2.example.com", Type: 1, Class: 1, TTL: 60, Data: net.IP{2, 0, 0, 1}},
}
}
}
w.Write(qq.Bytes())
}))
defer ts.Close()

t.Run("IOCloser", func(t *testing.T) {
resolvedH2.Store(0)
var dialed atomic.Int32
var closedConns atomic.Int32
loseDone := make(chan struct{})

dialer := &Dialer[*fakeCloserConn]{
Resolver: &Resolver{
baseURL: url.URL{Scheme: "http", Host: ts.Listener.Addr().String(), Path: "/dns-query"},
},
MaxConcurrency: 3,
ConcurrencyDelay: 20 * time.Millisecond,
Timeout: time.Second,
DialFunc: func(ctx context.Context, network, addr string, tc *tls.Config) (*fakeCloserConn, error) {
dialed.Add(1)
switch addr {
case "1.0.0.1:443":
time.Sleep(35 * time.Millisecond)
return &fakeCloserConn{addr: addr, closed: &closedConns}, nil
case "1.0.0.2:443":
time.Sleep(55 * time.Millisecond)
defer close(loseDone)
return &fakeCloserConn{addr: addr, closed: &closedConns}, nil
default:
return &fakeCloserConn{addr: addr, closed: &closedConns}, nil
}
},
}

conn, err := dialer.Dial(t.Context(), "tcp", "h1.example.com,h2.example.com", nil)
if err != nil {
t.Fatalf("Dial: %v", err)
}
if conn.addr != "1.0.0.1:443" {
t.Errorf("conn.addr = %q, want 1.0.0.1:443", conn.addr)
}

<-loseDone
deadline := time.Now().Add(time.Second)
for closedConns.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if got := closedConns.Load(); got != 1 {
t.Errorf("closedConns = %d, want 1", got)
}
if got := resolvedH2.Load(); got != 0 {
t.Errorf("resolvedH2 = %d, want 0", got)
}
if got := dialed.Load(); got != 2 {
t.Errorf("dialed = %d, want 2", got)
}
})

t.Run("CloseWithError", func(t *testing.T) {
resolvedH2.Store(0)
var dialed atomic.Int32
var closedConns atomic.Int32
loseDone := make(chan struct{})

dialer := &Dialer[*fakeQUICConn]{
Resolver: &Resolver{
baseURL: url.URL{Scheme: "http", Host: ts.Listener.Addr().String(), Path: "/dns-query"},
},
MaxConcurrency: 3,
ConcurrencyDelay: 20 * time.Millisecond,
Timeout: time.Second,
DialFunc: func(ctx context.Context, network, addr string, tc *tls.Config) (*fakeQUICConn, error) {
dialed.Add(1)
switch addr {
case "1.0.0.1:443":
time.Sleep(35 * time.Millisecond)
return &fakeQUICConn{addr: addr, closed: &closedConns}, nil
case "1.0.0.2:443":
time.Sleep(55 * time.Millisecond)
defer close(loseDone)
return &fakeQUICConn{addr: addr, closed: &closedConns}, nil
default:
return &fakeQUICConn{addr: addr, closed: &closedConns}, nil
}
},
}

conn, err := dialer.Dial(t.Context(), "udp", "h1.example.com,h2.example.com", nil)
if err != nil {
t.Fatalf("Dial: %v", err)
}
if conn.addr != "1.0.0.1:443" {
t.Errorf("conn.addr = %q, want 1.0.0.1:443", conn.addr)
}

<-loseDone
deadline := time.Now().Add(time.Second)
for closedConns.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
if got := closedConns.Load(); got != 1 {
t.Errorf("closedConns = %d, want 1", got)
}
if got := resolvedH2.Load(); got != 0 {
t.Errorf("resolvedH2 = %d, want 0", got)
}
if got := dialed.Load(); got != 2 {
t.Errorf("dialed = %d, want 2", got)
}
})
}
Loading
Loading