2018-06-14 01:00:58 +08:00
|
|
|
package http
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
2018-07-15 22:23:20 +08:00
|
|
|
"context"
|
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,
|
|
|
|
}
|
|
|
|
|
2018-06-10 22:50:03 +08:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
}
|
2018-07-15 22:23:20 +08:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Infof("HTTP proxy listening at: %s", addr)
|
|
|
|
server.Serve(l)
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
<-done
|
|
|
|
server.Shutdown(context.Background())
|
|
|
|
l.Close()
|
|
|
|
closed <- struct{}{}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return signal, nil
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
addr := r.Host
|
|
|
|
// padding default port
|
|
|
|
if !strings.Contains(addr, ":") {
|
|
|
|
addr += ":80"
|
|
|
|
}
|
2018-07-26 00:04:59 +08:00
|
|
|
req, done := adapters.NewHttp(addr, w, r)
|
2018-06-14 01:00:58 +08:00
|
|
|
tun.Add(req)
|
|
|
|
<-done
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleTunneling(w http.ResponseWriter, r *http.Request) {
|
|
|
|
hijacker, ok := w.(http.Hijacker)
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
2018-06-14 01:00:58 +08:00
|
|
|
conn, _, err := hijacker.Hijack()
|
2018-06-10 22:50:03 +08:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-06-12 22:43:34 +08:00
|
|
|
// w.WriteHeader(http.StatusOK) doesn't works in Safari
|
|
|
|
conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
|
2018-07-26 00:04:59 +08:00
|
|
|
tun.Add(adapters.NewHttps(r.Host, conn))
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|