Skip to content

Commit 739714b

Browse files
committed
Fix server crash when connection fails during TLS protocol detection
Wrap peek errors as temporary so http.Server retries instead of exiting. This fixes crashes on Windows where security software or browsers may connect and immediately disconnect during certificate pre-checks. Also adds a 5-second read deadline during peek to prevent hanging on slow or malicious clients.
1 parent 43db917 commit 739714b

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

internal/certs/mux.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,20 @@ package certs
33
import (
44
"crypto/tls"
55
"net"
6+
"time"
67
)
78

9+
// tempError wraps an error to be treated as temporary by http.Server.
10+
// This prevents the server from exiting when a connection fails during
11+
// protocol detection (e.g., client disconnects before sending data).
12+
type tempError struct {
13+
err error
14+
}
15+
16+
func (e *tempError) Error() string { return e.err.Error() }
17+
func (e *tempError) Timeout() bool { return false }
18+
func (e *tempError) Temporary() bool { return true }
19+
820
// MuxListener wraps a net.Listener and routes connections to either
921
// TLS or plain HTTP based on the first byte of the connection.
1022
// TLS connections start with 0x16 (TLS handshake), HTTP starts with ASCII.
@@ -29,12 +41,20 @@ func (m *MuxListener) Accept() (net.Conn, error) {
2941
return nil, err
3042
}
3143

44+
// Set a deadline for the peek to avoid hanging on slow/malicious clients
45+
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
46+
3247
// Wrap connection to peek at first byte
3348
pc := &peekConn{Conn: conn}
3449
b, err := pc.peek()
50+
51+
// Clear the deadline for normal operation
52+
conn.SetReadDeadline(time.Time{})
53+
3554
if err != nil {
3655
conn.Close()
37-
return nil, err
56+
// Wrap as temporary error so http.Server retries instead of exiting
57+
return nil, &tempError{err: err}
3858
}
3959

4060
// TLS handshake starts with 0x16 (ContentType: Handshake)

0 commit comments

Comments
 (0)