Improve: HTTP proxy server handler
This commit is contained in:
@ -1,56 +1,18 @@
|
||||
package adapters
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
C "github.com/Dreamacro/clash/constant"
|
||||
)
|
||||
|
||||
// PeekedConn handle http connection and buffed HTTP data
|
||||
type PeekedConn struct {
|
||||
net.Conn
|
||||
Peeked []byte
|
||||
host string
|
||||
isHTTP bool
|
||||
}
|
||||
|
||||
func (c *PeekedConn) Read(p []byte) (n int, err error) {
|
||||
if len(c.Peeked) > 0 {
|
||||
n = copy(p, c.Peeked)
|
||||
c.Peeked = c.Peeked[n:]
|
||||
if len(c.Peeked) == 0 {
|
||||
c.Peeked = nil
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Sometimes firefox just open a socket to process multiple domains in HTTP
|
||||
// The temporary solution is to return io.EOF when encountering different HOST
|
||||
if c.isHTTP {
|
||||
br := bufio.NewReader(bytes.NewReader(p))
|
||||
_, hostName := ParserHTTPHostHeader(br)
|
||||
if hostName != "" {
|
||||
if !strings.Contains(hostName, ":") {
|
||||
hostName += ":80"
|
||||
}
|
||||
|
||||
if hostName != c.host {
|
||||
return 0, io.EOF
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return c.Conn.Read(p)
|
||||
}
|
||||
|
||||
// HTTPAdapter is a adapter for HTTP connection
|
||||
type HTTPAdapter struct {
|
||||
addr *C.Addr
|
||||
conn *PeekedConn
|
||||
conn net.Conn
|
||||
R *http.Request
|
||||
}
|
||||
|
||||
// Close HTTP connection
|
||||
@ -69,14 +31,34 @@ func (h *HTTPAdapter) Conn() net.Conn {
|
||||
}
|
||||
|
||||
// NewHTTP is HTTPAdapter generator
|
||||
func NewHTTP(host string, peeked []byte, isHTTP bool, conn net.Conn) *HTTPAdapter {
|
||||
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
||||
return &HTTPAdapter{
|
||||
addr: parseHTTPAddr(host),
|
||||
conn: &PeekedConn{
|
||||
Peeked: peeked,
|
||||
Conn: conn,
|
||||
host: host,
|
||||
isHTTP: isHTTP,
|
||||
},
|
||||
addr: parseHTTPAddr(request),
|
||||
R: request,
|
||||
conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
// RemoveHopByHopHeaders remove hop-by-hop header
|
||||
func RemoveHopByHopHeaders(header http.Header) {
|
||||
// Strip hop-by-hop header based on RFC:
|
||||
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
|
||||
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
|
||||
|
||||
header.Del("Proxy-Connection")
|
||||
header.Del("Proxy-Authenticate")
|
||||
header.Del("Proxy-Authorization")
|
||||
header.Del("TE")
|
||||
header.Del("Trailers")
|
||||
header.Del("Transfer-Encoding")
|
||||
header.Del("Upgrade")
|
||||
|
||||
connections := header.Get("Connection")
|
||||
header.Del("Connection")
|
||||
if len(connections) == 0 {
|
||||
return
|
||||
}
|
||||
for _, h := range strings.Split(connections, ",") {
|
||||
header.Del(strings.TrimSpace(h))
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user