Improve: clean code

This commit is contained in:
Dreamacro 2018-08-12 16:18:58 +08:00
parent fc4f119049
commit ebe1cee6dc
7 changed files with 97 additions and 83 deletions

View file

@ -5,12 +5,12 @@ import (
"bytes" "bytes"
"io" "io"
"net" "net"
"net/http"
"strings" "strings"
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
) )
// PeekedConn handle http connection and buffed HTTP data
type PeekedConn struct { type PeekedConn struct {
net.Conn net.Conn
Peeked []byte Peeked []byte
@ -47,26 +47,31 @@ func (c *PeekedConn) Read(p []byte) (n int, err error) {
return c.Conn.Read(p) return c.Conn.Read(p)
} }
type HttpAdapter struct { // HTTPAdapter is a adapter for HTTP connection
type HTTPAdapter struct {
addr *C.Addr addr *C.Addr
conn *PeekedConn conn *PeekedConn
} }
func (h *HttpAdapter) Close() { // Close HTTP connection
func (h *HTTPAdapter) Close() {
h.conn.Close() h.conn.Close()
} }
func (h *HttpAdapter) Addr() *C.Addr { // Addr return destination address
func (h *HTTPAdapter) Addr() *C.Addr {
return h.addr return h.addr
} }
func (h *HttpAdapter) Conn() net.Conn { // Conn return raw net.Conn of HTTP
func (h *HTTPAdapter) Conn() net.Conn {
return h.conn return h.conn
} }
func NewHttp(host string, peeked []byte, isHTTP bool, conn net.Conn) *HttpAdapter { // NewHTTP is HTTPAdapter generator
return &HttpAdapter{ func NewHTTP(host string, peeked []byte, isHTTP bool, conn net.Conn) *HTTPAdapter {
addr: parseHttpAddr(host), return &HTTPAdapter{
addr: parseHTTPAddr(host),
conn: &PeekedConn{ conn: &PeekedConn{
Peeked: peeked, Peeked: peeked,
Conn: conn, Conn: conn,
@ -75,74 +80,3 @@ func NewHttp(host string, peeked []byte, isHTTP bool, conn net.Conn) *HttpAdapte
}, },
} }
} }
// ParserHTTPHostHeader returns the HTTP Host header from br without
// consuming any of its bytes. It returns "" if it can't find one.
func ParserHTTPHostHeader(br *bufio.Reader) (method, host string) {
// br := bufio.NewReader(bytes.NewReader(data))
const maxPeek = 4 << 10
peekSize := 0
for {
peekSize++
if peekSize > maxPeek {
b, _ := br.Peek(br.Buffered())
return method, httpHostHeaderFromBytes(b)
}
b, err := br.Peek(peekSize)
if n := br.Buffered(); n > peekSize {
b, _ = br.Peek(n)
peekSize = n
}
if len(b) > 0 {
if b[0] < 'A' || b[0] > 'Z' {
// Doesn't look like an HTTP verb
// (GET, POST, etc).
return
}
if bytes.Index(b, crlfcrlf) != -1 || bytes.Index(b, lflf) != -1 {
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(b)))
if err != nil {
return
}
if len(req.Header["Host"]) > 1 {
// TODO(bradfitz): what does
// ReadRequest do if there are
// multiple Host headers?
return
}
return req.Method, req.Host
}
}
if err != nil {
return method, httpHostHeaderFromBytes(b)
}
}
}
var (
lfHostColon = []byte("\nHost:")
lfhostColon = []byte("\nhost:")
crlf = []byte("\r\n")
lf = []byte("\n")
crlfcrlf = []byte("\r\n\r\n")
lflf = []byte("\n\n")
)
func httpHostHeaderFromBytes(b []byte) string {
if i := bytes.Index(b, lfHostColon); i != -1 {
return string(bytes.TrimSpace(untilEOL(b[i+len(lfHostColon):])))
}
if i := bytes.Index(b, lfhostColon); i != -1 {
return string(bytes.TrimSpace(untilEOL(b[i+len(lfhostColon):])))
}
return ""
}
// untilEOL returns v, truncated before the first '\n' byte, if any.
// The returned slice may include a '\r' at the end.
func untilEOL(v []byte) []byte {
if i := bytes.IndexByte(v, '\n'); i != -1 {
return v[:i]
}
return v
}

View file

@ -7,23 +7,28 @@ import (
"github.com/riobard/go-shadowsocks2/socks" "github.com/riobard/go-shadowsocks2/socks"
) )
// SocksAdapter is a adapter for socks and redir connection
type SocksAdapter struct { type SocksAdapter struct {
conn net.Conn conn net.Conn
addr *C.Addr addr *C.Addr
} }
// Close socks and redir connection
func (s *SocksAdapter) Close() { func (s *SocksAdapter) Close() {
s.conn.Close() s.conn.Close()
} }
// Addr return destination address
func (s *SocksAdapter) Addr() *C.Addr { func (s *SocksAdapter) Addr() *C.Addr {
return s.addr return s.addr
} }
// Conn return raw net.Conn
func (s *SocksAdapter) Conn() net.Conn { func (s *SocksAdapter) Conn() net.Conn {
return s.conn return s.conn
} }
// NewSocks is SocksAdapter generator
func NewSocks(target socks.Addr, conn net.Conn) *SocksAdapter { func NewSocks(target socks.Addr, conn net.Conn) *SocksAdapter {
return &SocksAdapter{ return &SocksAdapter{
conn: conn, conn: conn,

View file

@ -1,7 +1,10 @@
package adapters package adapters
import ( import (
"bufio"
"bytes"
"net" "net"
"net/http"
"strconv" "strconv"
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
@ -37,7 +40,7 @@ func parseSocksAddr(target socks.Addr) *C.Addr {
} }
} }
func parseHttpAddr(target string) *C.Addr { func parseHTTPAddr(target string) *C.Addr {
host, port, _ := net.SplitHostPort(target) host, port, _ := net.SplitHostPort(target)
ipAddr, err := net.ResolveIPAddr("ip", host) ipAddr, err := net.ResolveIPAddr("ip", host)
var resolveIP *net.IP var resolveIP *net.IP
@ -64,3 +67,74 @@ func parseHttpAddr(target string) *C.Addr {
Port: port, Port: port,
} }
} }
// ParserHTTPHostHeader returns the HTTP Host header from br without
// consuming any of its bytes. It returns "" if it can't find one.
func ParserHTTPHostHeader(br *bufio.Reader) (method, host string) {
// br := bufio.NewReader(bytes.NewReader(data))
const maxPeek = 4 << 10
peekSize := 0
for {
peekSize++
if peekSize > maxPeek {
b, _ := br.Peek(br.Buffered())
return method, httpHostHeaderFromBytes(b)
}
b, err := br.Peek(peekSize)
if n := br.Buffered(); n > peekSize {
b, _ = br.Peek(n)
peekSize = n
}
if len(b) > 0 {
if b[0] < 'A' || b[0] > 'Z' {
// Doesn't look like an HTTP verb
// (GET, POST, etc).
return
}
if bytes.Index(b, crlfcrlf) != -1 || bytes.Index(b, lflf) != -1 {
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(b)))
if err != nil {
return
}
if len(req.Header["Host"]) > 1 {
// TODO(bradfitz): what does
// ReadRequest do if there are
// multiple Host headers?
return
}
return req.Method, req.Host
}
}
if err != nil {
return method, httpHostHeaderFromBytes(b)
}
}
}
var (
lfHostColon = []byte("\nHost:")
lfhostColon = []byte("\nhost:")
crlf = []byte("\r\n")
lf = []byte("\n")
crlfcrlf = []byte("\r\n\r\n")
lflf = []byte("\n\n")
)
func httpHostHeaderFromBytes(b []byte) string {
if i := bytes.Index(b, lfHostColon); i != -1 {
return string(bytes.TrimSpace(untilEOL(b[i+len(lfHostColon):])))
}
if i := bytes.Index(b, lfhostColon); i != -1 {
return string(bytes.TrimSpace(untilEOL(b[i+len(lfhostColon):])))
}
return ""
}
// untilEOL returns v, truncated before the first '\n' byte, if any.
// The returned slice may include a '\r' at the end.
func untilEOL(v []byte) []byte {
if i := bytes.IndexByte(v, '\n'); i != -1 {
return v[:i]
}
return v
}

View file

@ -364,6 +364,7 @@ func newConfig() *Config {
return config return config
} }
// Instance return singleton instance of Config
func Instance() *Config { func Instance() *Config {
once.Do(func() { once.Do(func() {
config = newConfig() config = newConfig()

View file

@ -75,5 +75,5 @@ func handleConn(conn net.Conn) {
peeked, _ = br.Peek(br.Buffered()) peeked, _ = br.Peek(br.Buffered())
} }
tun.Add(adapters.NewHttp(hostName, peeked, method != http.MethodConnect, conn)) tun.Add(adapters.NewHTTP(hostName, peeked, method != http.MethodConnect, conn))
} }

View file

@ -7,7 +7,7 @@ import (
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
) )
func (t *Tunnel) handleHTTP(request *adapters.HttpAdapter, proxy C.ProxyAdapter) { func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, proxy C.ProxyAdapter) {
conn := newTrafficTrack(proxy.Conn(), t.traffic) conn := newTrafficTrack(proxy.Conn(), t.traffic)
// Before we unwrap src and/or dst, copy any buffered data. // Before we unwrap src and/or dst, copy any buffered data.

View file

@ -104,7 +104,7 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
defer remoConn.Close() defer remoConn.Close()
switch adapter := localConn.(type) { switch adapter := localConn.(type) {
case *LocalAdapter.HttpAdapter: case *LocalAdapter.HTTPAdapter:
t.handleHTTP(adapter, remoConn) t.handleHTTP(adapter, remoConn)
case *LocalAdapter.SocksAdapter: case *LocalAdapter.SocksAdapter:
t.handleSOCKS(adapter, remoConn) t.handleSOCKS(adapter, remoConn)