Skip to content

Commit f4967a8

Browse files
committed
net/http: configurable error message for Client sent an HTTP request to an HTTPS server.
1 parent e41fabd commit f4967a8

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

src/crypto/tls/common.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,10 @@ type Config struct {
785785
// autoSessionTicketKeys is like sessionTicketKeys but is owned by the
786786
// auto-rotation logic. See Config.ticketKeys.
787787
autoSessionTicketKeys []ticketKey
788+
789+
// If tlsRecordHeaderLooksLikeHTTP, call this function,
790+
// then get return string to io.WriteString
791+
LooksLikeHttpResponseHandler func(RecondBytes []byte) string
788792
}
789793

790794
const (

src/crypto/tls/conn.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,9 @@ type RecordHeaderError struct {
568568
// RecordHeader contains the five bytes of TLS record header that
569569
// triggered the error.
570570
RecordHeader [5]byte
571+
// RecondBytes contains all the bytes of the TLS record header that
572+
// triggered the error.
573+
RecondBytes []byte
571574
// Conn provides the underlying net.Conn in the case that a client
572575
// sent an initial handshake that didn't look like TLS.
573576
// It is nil if there's already been a handshake or a TLS alert has
@@ -580,7 +583,8 @@ func (e RecordHeaderError) Error() string { return "tls: " + e.Msg }
580583
func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) {
581584
err.Msg = msg
582585
err.Conn = conn
583-
copy(err.RecordHeader[:], c.rawInput.Bytes())
586+
err.RecondBytes = c.rawInput.Bytes()
587+
copy(err.RecordHeader[:], err.RecondBytes)
584588
return err
585589
}
586590

src/net/http/server.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1923,7 +1923,12 @@ func (c *conn) serve(ctx context.Context) {
19231923
// TLS, assume they're speaking plaintext HTTP and write a
19241924
// 400 response on the TLS conn's underlying net.Conn.
19251925
if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
1926-
io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1926+
if handler := c.server.TLSConfig.LooksLikeHttpResponseHandler; handler != nil {
1927+
// configurable error message for Client sent an HTTP request to an HTTPS server.
1928+
io.WriteString(re.Conn, handler(re.RecondBytes))
1929+
} else {
1930+
io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
1931+
}
19271932
re.Conn.Close()
19281933
return
19291934
}

0 commit comments

Comments
 (0)