mihomo/adapters/local/http.go

83 lines
1.5 KiB
Go
Raw Normal View History

package adapters
import (
"bufio"
"bytes"
"io"
2018-08-11 22:51:30 +08:00
"net"
"strings"
C "github.com/Dreamacro/clash/constant"
)
2018-08-12 16:18:58 +08:00
// PeekedConn handle http connection and buffed HTTP data
2018-08-11 22:51:30 +08:00
type PeekedConn struct {
net.Conn
Peeked []byte
host string
isHTTP bool
2018-08-11 22:51:30 +08:00
}
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
}
}
}
2018-08-11 22:51:30 +08:00
return c.Conn.Read(p)
}
2018-08-12 16:18:58 +08:00
// HTTPAdapter is a adapter for HTTP connection
type HTTPAdapter struct {
addr *C.Addr
2018-08-11 22:51:30 +08:00
conn *PeekedConn
}
2018-08-12 16:18:58 +08:00
// Close HTTP connection
func (h *HTTPAdapter) Close() {
2018-08-11 22:51:30 +08:00
h.conn.Close()
}
2018-08-12 16:18:58 +08:00
// Addr return destination address
func (h *HTTPAdapter) Addr() *C.Addr {
return h.addr
}
2018-08-12 16:18:58 +08:00
// Conn return raw net.Conn of HTTP
func (h *HTTPAdapter) Conn() net.Conn {
2018-08-11 22:51:30 +08:00
return h.conn
}
2018-08-12 16:18:58 +08:00
// NewHTTP is HTTPAdapter generator
func NewHTTP(host string, peeked []byte, isHTTP bool, conn net.Conn) *HTTPAdapter {
return &HTTPAdapter{
addr: parseHTTPAddr(host),
2018-08-11 22:51:30 +08:00
conn: &PeekedConn{
Peeked: peeked,
Conn: conn,
host: host,
isHTTP: isHTTP,
2018-08-11 22:51:30 +08:00
},
}
}