仰望星辰工作室

miaopanel

miaopanel/ internal/paneltls/mux.go 1.6 KB · 59 行 原始文件
1package paneltls
2
3import (
4 "bufio"
5 "crypto/tls"
6 "net"
7 "time"
8)
9
10// muxListener upgrades connections that start with a TLS handshake and leaves
11// everything else as plain HTTP. The panel therefore keeps answering on the
12// same port for old bookmarks, the installer and nginx reverse proxies while
13// the browser can switch to https:// without any configuration.
14type muxListener struct {
15 inner net.Listener
16 conf *tls.Config
17}
18
19// Mux wraps ln so it accepts both HTTP and HTTPS on a single port.
20func Mux(ln net.Listener, conf *tls.Config) net.Listener {
21 if conf == nil {
22 return ln
23 }
24 return &muxListener{inner: ln, conf: conf}
25}
26
27func (l *muxListener) Accept() (net.Conn, error) {
28 for {
29 conn, err := l.inner.Accept()
30 if err != nil {
31 return nil, err
32 }
33 // A first byte of 0x16 is a TLS handshake record, which covers TLS 1.2
34 // and 1.3 alike. Any plain HTTP method starts with an ASCII letter.
35 _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
36 pc := &peekingConn{Conn: conn, r: bufio.NewReaderSize(conn, 512)}
37 first, err := pc.r.Peek(1)
38 _ = conn.SetReadDeadline(time.Time{})
39 if err != nil {
40 _ = conn.Close()
41 continue
42 }
43 if first[0] == 0x16 {
44 return tls.Server(pc, l.conf), nil
45 }
46 return pc, nil
47 }
48}
49
50func (l *muxListener) Close() error { return l.inner.Close() }
51func (l *muxListener) Addr() net.Addr { return l.inner.Addr() }
52
53// peekingConn keeps the bytes consumed by Peek available to the reader.
54type peekingConn struct {
55 net.Conn
56 r *bufio.Reader
57}
58
59func (c *peekingConn) Read(b []byte) (int, error) { return c.r.Read(b) }