2018-06-14 01:00:58 +08:00
|
|
|
package http
|
2018-06-10 22:50:03 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
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
|
|
|
|
|
|
|
"github.com/riobard/go-shadowsocks2/socks"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2018-06-14 01:00:58 +08:00
|
|
|
var (
|
|
|
|
tun = tunnel.GetInstance()
|
|
|
|
)
|
|
|
|
|
2018-06-10 22:50:03 +08:00
|
|
|
func NewHttpProxy(port string) {
|
|
|
|
server := &http.Server{
|
|
|
|
Addr: fmt.Sprintf(":%s", port),
|
|
|
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.Method == http.MethodConnect {
|
|
|
|
handleTunneling(w, r)
|
|
|
|
} else {
|
|
|
|
handleHTTP(w, r)
|
|
|
|
}
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
log.Infof("HTTP proxy :%s", port)
|
|
|
|
server.ListenAndServe()
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
addr := r.Host
|
|
|
|
// padding default port
|
|
|
|
if !strings.Contains(addr, ":") {
|
|
|
|
addr += ":80"
|
|
|
|
}
|
2018-06-14 01:00:58 +08:00
|
|
|
req, done := NewHttp(addr, w, r)
|
|
|
|
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-06-14 01:00:58 +08:00
|
|
|
tun.Add(NewHttps(r.Host, conn))
|
2018-06-10 22:50:03 +08:00
|
|
|
}
|
|
|
|
|
2018-06-14 01:00:58 +08:00
|
|
|
func parseHttpAddr(target string) *C.Addr {
|
2018-06-10 22:50:03 +08:00
|
|
|
host, port, _ := net.SplitHostPort(target)
|
2018-06-15 00:44:31 +08:00
|
|
|
ipAddr, err := net.ResolveIPAddr("ip", host)
|
|
|
|
var resolveIP *net.IP
|
|
|
|
if err == nil {
|
|
|
|
resolveIP = &ipAddr.IP
|
|
|
|
}
|
|
|
|
|
2018-06-10 22:50:03 +08:00
|
|
|
var addType int
|
|
|
|
ip := net.ParseIP(host)
|
|
|
|
switch {
|
|
|
|
case ip == nil:
|
|
|
|
addType = socks.AtypDomainName
|
|
|
|
case ip.To4() == nil:
|
|
|
|
addType = socks.AtypIPv6
|
|
|
|
default:
|
|
|
|
addType = socks.AtypIPv4
|
|
|
|
}
|
|
|
|
|
2018-06-14 01:00:58 +08:00
|
|
|
return &C.Addr{
|
|
|
|
NetWork: C.TCP,
|
2018-06-10 22:50:03 +08:00
|
|
|
AddrType: addType,
|
|
|
|
Host: host,
|
2018-06-15 00:44:31 +08:00
|
|
|
IP: resolveIP,
|
2018-06-10 22:50:03 +08:00
|
|
|
Port: port,
|
|
|
|
}
|
|
|
|
}
|