2018-06-14 01:00:58 +08:00
|
|
|
package http
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
2018-08-11 22:51:30 +08:00
|
|
|
"bufio"
|
2018-06-10 22:50:03 +08:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2018-07-26 00:04:59 +08:00
|
|
|
"github.com/Dreamacro/clash/adapters/local"
|
2018-06-14 01:00:58 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2018-06-14 01:00:58 +08:00
|
|
|
var (
|
2018-07-26 00:04:59 +08:00
|
|
|
tun = tunnel.Instance()
|
2018-06-14 01:00:58 +08:00
|
|
|
)
|
|
|
|
|
2018-07-15 22:23:20 +08:00
|
|
|
func NewHttpProxy(addr string) (*C.ProxySignal, error) {
|
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
closed := make(chan struct{})
|
|
|
|
signal := &C.ProxySignal{
|
|
|
|
Done: done,
|
|
|
|
Closed: closed,
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Infof("HTTP proxy listening at: %s", addr)
|
2018-08-11 22:51:30 +08:00
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
if _, open := <-done; !open {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleConn(c)
|
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-done
|
2018-08-11 22:51:30 +08:00
|
|
|
close(done)
|
2018-07-15 22:23:20 +08:00
|
|
|
l.Close()
|
|
|
|
closed <- struct{}{}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return signal, nil
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
2018-08-11 22:51:30 +08:00
|
|
|
func handleConn(conn net.Conn) {
|
|
|
|
br := bufio.NewReader(conn)
|
|
|
|
method, hostName := httpHostHeader(br)
|
|
|
|
if hostName == "" {
|
|
|
|
return
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
2018-08-11 22:51:30 +08:00
|
|
|
if !strings.Contains(hostName, ":") {
|
|
|
|
hostName += ":80"
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2018-08-11 22:51:30 +08:00
|
|
|
|
|
|
|
var peeked []byte
|
|
|
|
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())
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
2018-08-11 22:51:30 +08:00
|
|
|
|
|
|
|
tun.Add(adapters.NewHttp(hostName, peeked, conn))
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|