-
Notifications
You must be signed in to change notification settings - Fork 5
/
src_conn.go
98 lines (84 loc) · 1.8 KB
/
src_conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package hlfhr
import (
"crypto/tls"
"errors"
"io"
"log"
"net"
"net/http"
"unsafe"
)
var ErrHttpOnHttpsPort = errors.New("client sent an HTTP request to an HTTPS server")
type conn struct {
net.Conn
tc *tls.Conn // reading tls if nil
srv *Server
}
func (c *conn) setRawConn() {
(*struct {
conn net.Conn
})(unsafe.Pointer(c.tc)).conn = c.Conn
}
func (c *conn) log(v ...any) {
if c.srv.ErrorLog != nil {
c.srv.ErrorLog.Print(v...)
} else {
log.Print(v...)
}
}
func (c *conn) readRequest(b []byte, n int) (*http.Request, error) {
rd := &io.LimitedReader{
R: c.Conn,
N: http.DefaultMaxHeaderBytes,
}
if c.srv.MaxHeaderBytes != 0 {
rd.N = int64(c.srv.MaxHeaderBytes)
}
rd.N -= int64(n)
br := NewBufioReaderWithBytes(b, n, rd)
req, err := http.ReadRequest(br)
if err == nil {
BufioSetReader(br, c.Conn)
}
return req, err
}
func (c *conn) Read(b []byte) (int, error) {
n, err := c.Conn.Read(b)
if c.tc == nil || err != nil || n <= 0 {
return n, err
}
if !ConnFirstByteLooksLikeHttp(b[0]) {
// Not looks like HTTP.
// TLS handshake: 0x16
c.setRawConn()
c.tc = nil
return n, nil
}
// Looks like HTTP.
// len(b) == 576
// Read request
r, err := c.readRequest(b, n)
if err != nil {
c.log("hlfhr: Read request error from ", c.Conn.RemoteAddr(), ": ", err)
return 0, ErrHttpOnHttpsPort
}
// Response
w := NewResponse(c.Conn, true)
if r.Host == "" {
// missing "Host" header
w.WriteHeader(400)
w.WriteString("missing required Host header")
} else if c.srv.HttpOnHttpsPortErrorHandler != nil {
// Handler
c.srv.HttpOnHttpsPortErrorHandler.ServeHTTP(w, r)
} else {
// Redirect
RedirectToHttps(w, r, 302)
}
// Write
err = w.FlushError()
if err != nil {
c.log("hlfhr: Write error for ", c.Conn.RemoteAddr(), ": ", err)
}
return 0, ErrHttpOnHttpsPort
}