Fix: issue #3

This commit is contained in:
gVisor bot 2018-08-11 22:51:30 +08:00
parent 47df357e75
commit 6c38fce2cb
6 changed files with 146 additions and 126 deletions

View file

@ -1,32 +1,51 @@
package adapters package adapters
import ( import (
"net/http" "net"
C "github.com/Dreamacro/clash/constant" C "github.com/Dreamacro/clash/constant"
) )
type PeekedConn struct {
net.Conn
Peeked []byte
}
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
}
return c.Conn.Read(p)
}
type HttpAdapter struct { type HttpAdapter struct {
addr *C.Addr addr *C.Addr
R *http.Request conn *PeekedConn
W http.ResponseWriter
done chan struct{}
} }
func (h *HttpAdapter) Close() { func (h *HttpAdapter) Close() {
h.done <- struct{}{} h.conn.Close()
} }
func (h *HttpAdapter) Addr() *C.Addr { func (h *HttpAdapter) Addr() *C.Addr {
return h.addr return h.addr
} }
func NewHttp(host string, w http.ResponseWriter, r *http.Request) (*HttpAdapter, chan struct{}) { func (h *HttpAdapter) Conn() net.Conn {
done := make(chan struct{}) return h.conn
}
func NewHttp(host string, peeked []byte, conn net.Conn) *HttpAdapter {
return &HttpAdapter{ return &HttpAdapter{
addr: parseHttpAddr(host), addr: parseHttpAddr(host),
R: r, conn: &PeekedConn{
W: w, Peeked: peeked,
done: done, Conn: conn,
}, done },
}
} }

View file

@ -1,33 +0,0 @@
package adapters
import (
"bufio"
"net"
C "github.com/Dreamacro/clash/constant"
)
type HttpsAdapter struct {
addr *C.Addr
conn net.Conn
rw *bufio.ReadWriter
}
func (h *HttpsAdapter) Close() {
h.conn.Close()
}
func (h *HttpsAdapter) Addr() *C.Addr {
return h.addr
}
func (h *HttpsAdapter) Conn() net.Conn {
return h.conn
}
func NewHttps(host string, conn net.Conn) *HttpsAdapter {
return &HttpsAdapter{
addr: parseHttpAddr(host),
conn: conn,
}
}

View file

@ -1,7 +1,7 @@
package http package http
import ( import (
"context" "bufio"
"net" "net"
"net/http" "net/http"
"strings" "strings"
@ -30,24 +30,23 @@ func NewHttpProxy(addr string) (*C.ProxySignal, error) {
Closed: closed, Closed: closed,
} }
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
handleTunneling(w, r)
} else {
handleHTTP(w, r)
}
}),
}
go func() { go func() {
log.Infof("HTTP proxy listening at: %s", addr) log.Infof("HTTP proxy listening at: %s", addr)
server.Serve(l) for {
c, err := l.Accept()
if err != nil {
if _, open := <-done; !open {
break
}
continue
}
go handleConn(c)
}
}() }()
go func() { go func() {
<-done <-done
server.Shutdown(context.Background()) close(done)
l.Close() l.Close()
closed <- struct{}{} closed <- struct{}{}
}() }()
@ -55,27 +54,26 @@ func NewHttpProxy(addr string) (*C.ProxySignal, error) {
return signal, nil return signal, nil
} }
func handleHTTP(w http.ResponseWriter, r *http.Request) { func handleConn(conn net.Conn) {
addr := r.Host br := bufio.NewReader(conn)
// padding default port method, hostName := httpHostHeader(br)
if !strings.Contains(addr, ":") { if hostName == "" {
addr += ":80" return
} }
req, done := adapters.NewHttp(addr, w, r)
tun.Add(req)
<-done
}
func handleTunneling(w http.ResponseWriter, r *http.Request) { if !strings.Contains(hostName, ":") {
hijacker, ok := w.(http.Hijacker) hostName += ":80"
if !ok {
return
} }
conn, _, err := hijacker.Hijack()
if err != nil { var peeked []byte
return if method == http.MethodConnect {
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
return
}
} else if n := br.Buffered(); n > 0 {
peeked, _ = br.Peek(br.Buffered())
} }
// w.WriteHeader(http.StatusOK) doesn't works in Safari
conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n")) tun.Add(adapters.NewHttp(hostName, peeked, conn))
tun.Add(adapters.NewHttps(r.Host, conn))
} }

77
proxy/http/util.go Normal file
View file

@ -0,0 +1,77 @@
package http
import (
"bufio"
"bytes"
"net/http"
)
// httpHostHeader returns the HTTP Host header from br without
// consuming any of its bytes. It returns ""if it can't find one.
func httpHostHeader(br *bufio.Reader) (method, host string) {
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

@ -2,47 +2,22 @@ package tunnel
import ( import (
"io" "io"
"net"
"net/http"
"time"
"github.com/Dreamacro/clash/adapters/local" "github.com/Dreamacro/clash/adapters/local"
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) {
req := http.Transport{
Dial: func(string, string) (net.Conn, error) {
conn := newTrafficTrack(proxy.Conn(), t.traffic)
return conn, nil
},
// from http.DefaultTransport
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
resp, err := req.RoundTrip(request.R)
if err != nil {
return
}
defer resp.Body.Close()
header := request.W.Header()
for k, vv := range resp.Header {
for _, v := range vv {
header.Add(k, v)
}
}
request.W.WriteHeader(resp.StatusCode)
var writer io.Writer = request.W
if len(resp.TransferEncoding) > 0 && resp.TransferEncoding[0] == "chunked" {
writer = ChunkWriter{Writer: request.W}
}
io.Copy(writer, resp.Body)
}
func (t *Tunnel) handleHTTPS(request *adapters.HttpsAdapter, 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.
if wc, ok := request.Conn().(*adapters.PeekedConn); ok && len(wc.Peeked) > 0 {
if _, err := conn.Write(wc.Peeked); err != nil {
return
}
wc.Peeked = nil
}
go io.Copy(request.Conn(), conn) go io.Copy(request.Conn(), conn)
io.Copy(conn, request.Conn()) io.Copy(conn, request.Conn())
} }
@ -52,16 +27,3 @@ func (t *Tunnel) handleSOCKS(request *adapters.SocksAdapter, proxy C.ProxyAdapte
go io.Copy(request.Conn(), conn) go io.Copy(request.Conn(), conn)
io.Copy(conn, request.Conn()) io.Copy(conn, request.Conn())
} }
// ChunkWriter is a writer wrapper and used when TransferEncoding is chunked
type ChunkWriter struct {
io.Writer
}
func (cw ChunkWriter) Write(b []byte) (int, error) {
n, err := cw.Writer.Write(b)
if err == nil {
cw.Writer.(http.Flusher).Flush()
}
return n, err
}

View file

@ -107,9 +107,6 @@ func (t *Tunnel) handleConn(localConn C.ServerAdapter) {
case *LocalAdapter.HttpAdapter: case *LocalAdapter.HttpAdapter:
t.handleHTTP(adapter, remoConn) t.handleHTTP(adapter, remoConn)
break break
case *LocalAdapter.HttpsAdapter:
t.handleHTTPS(adapter, remoConn)
break
case *LocalAdapter.SocksAdapter: case *LocalAdapter.SocksAdapter:
t.handleSOCKS(adapter, remoConn) t.handleSOCKS(adapter, remoConn)
break break