package paneltls import ( "bufio" "crypto/tls" "net" "time" ) // muxListener upgrades connections that start with a TLS handshake and leaves // everything else as plain HTTP. The panel therefore keeps answering on the // same port for old bookmarks, the installer and nginx reverse proxies while // the browser can switch to https:// without any configuration. type muxListener struct { inner net.Listener conf *tls.Config } // Mux wraps ln so it accepts both HTTP and HTTPS on a single port. func Mux(ln net.Listener, conf *tls.Config) net.Listener { if conf == nil { return ln } return &muxListener{inner: ln, conf: conf} } func (l *muxListener) Accept() (net.Conn, error) { for { conn, err := l.inner.Accept() if err != nil { return nil, err } // A first byte of 0x16 is a TLS handshake record, which covers TLS 1.2 // and 1.3 alike. Any plain HTTP method starts with an ASCII letter. _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) pc := &peekingConn{Conn: conn, r: bufio.NewReaderSize(conn, 512)} first, err := pc.r.Peek(1) _ = conn.SetReadDeadline(time.Time{}) if err != nil { _ = conn.Close() continue } if first[0] == 0x16 { return tls.Server(pc, l.conf), nil } return pc, nil } } func (l *muxListener) Close() error { return l.inner.Close() } func (l *muxListener) Addr() net.Addr { return l.inner.Addr() } // peekingConn keeps the bytes consumed by Peek available to the reader. type peekingConn struct { net.Conn r *bufio.Reader } func (c *peekingConn) Read(b []byte) (int, error) { return c.r.Read(b) }