这个 mod 通过劫持 net.Conn
实现了一个功能:
当用户使用 http 协议访问 https 端口时,服务器返回302重定向。
改编自 net/http
。
This mod implements a feature by hijacking net.Conn
:
If a user accesses an https port using http, the server returns 302 redirection.
Adapted from net/http
.
Related Issue:
net/http: configurable error message for Client sent an HTTP request to an HTTPS server. #49310
go get github.com/bddjr/hlfhr
HTTPS Server Start -> Hijacking net.Listener.Accept
Client HTTPS -> Accept hijacking net.Conn.Read -> Not looks like HTTP -> ✅Continue...
Client HTTP/1.1 -> Accept hijacking net.Conn.Read -> Looks like HTTP -> 🔄302 Redirect.
Client HTTP/??? -> Accept hijacking net.Conn.Read -> Looks like HTTP -> Missing Host header -> ❌400 Script.
Example:
var srv *hlfhr.Server
func main() {
srv = hlfhr.New(&http.Server{
Addr: ":5678",
Handler: http.HandlerFunc(httpResponseHandle),
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 10 * time.Second,
})
// Then just use it like http.Server .
err := srv.ListenAndServeTLS("localhost.crt", "localhost.key")
fmt.Println(err)
}
Run:
git clone https://github.com/bddjr/hlfhr
cd hlfhr
cd example
go build
./example
Hlfhr_ReadFirstRequestBytesLen
srv.Hlfhr_ReadFirstRequestBytesLen = 4096
Hlfhr_HttpOnHttpsPortErrorHandler
srv.Hlfhr_HttpOnHttpsPortErrorHandler = func(rb []byte, conn net.Conn) {
resp := hlfhr.NewResponse(conn)
// 302 Found
if host, path, ok := hlfhr.ReadReqHostPath(rb); ok {
resp.Redirect(302, fmt.Sprint("https://", host, path))
return
}
// script
resp.ScriptRedirect()
}
New
srv := hlfhr.New(&http.Server{})
NewServer
srv := hlfhr.NewServer(&http.Server{})
ReadReqHostPath
var rb []byte
host, path, ok := hlfhr.ReadReqHostPath(rb)
ReadReq
var rb []byte
req, err := hlfhr.ReadReq(rb)
NewResponse
var conn net.Conn
resp := hlfhr.NewResponse(conn)
Response.SetContentType
var resp *hlfhr.Response
resp.SetContentType("text/html")
Response.Write
var resp *hlfhr.Response
resp.Write(
"Hello world!\n",
"Hello hlfhr!\n",
)
Response.Redirect
var resp *hlfhr.Response
resp.Redirect(302, "https://example.com")
Response.ScriptRedirect
var resp *hlfhr.Response
resp.ScriptRedirect()