2018-06-13 17:00:58 +00:00
|
|
|
package http
|
2018-06-10 14:50:03 +00:00
|
|
|
|
|
|
|
import (
|
2018-08-11 14:51:30 +00:00
|
|
|
"bufio"
|
2018-06-10 14:50:03 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
|
2019-02-18 12:14:18 +00:00
|
|
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
2018-11-21 05:47:46 +00:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2018-06-13 17:00:58 +00:00
|
|
|
"github.com/Dreamacro/clash/tunnel"
|
2018-06-10 14:50:03 +00:00
|
|
|
)
|
|
|
|
|
2018-06-13 17:00:58 +00:00
|
|
|
var (
|
2018-07-25 16:04:59 +00:00
|
|
|
tun = tunnel.Instance()
|
2018-06-13 17:00:58 +00:00
|
|
|
)
|
|
|
|
|
2018-12-05 13:13:29 +00:00
|
|
|
type HttpListener struct {
|
2018-11-22 03:54:01 +00:00
|
|
|
net.Listener
|
|
|
|
address string
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
2018-12-05 13:13:29 +00:00
|
|
|
func NewHttpProxy(addr string) (*HttpListener, error) {
|
2018-07-15 14:23:20 +00:00
|
|
|
l, err := net.Listen("tcp", addr)
|
|
|
|
if err != nil {
|
2018-11-22 03:54:01 +00:00
|
|
|
return nil, err
|
2018-07-15 14:23:20 +00:00
|
|
|
}
|
2018-12-05 13:13:29 +00:00
|
|
|
hl := &HttpListener{l, addr, false}
|
2018-07-15 14:23:20 +00:00
|
|
|
|
|
|
|
go func() {
|
2018-11-21 05:47:46 +00:00
|
|
|
log.Infoln("HTTP proxy listening at: %s", addr)
|
2018-08-11 14:51:30 +00:00
|
|
|
for {
|
2018-11-22 03:54:01 +00:00
|
|
|
c, err := hl.Accept()
|
2018-08-11 14:51:30 +00:00
|
|
|
if err != nil {
|
2018-11-22 03:54:01 +00:00
|
|
|
if hl.closed {
|
2018-08-11 14:51:30 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
go handleConn(c)
|
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
}()
|
|
|
|
|
2018-11-22 03:54:01 +00:00
|
|
|
return hl, nil
|
|
|
|
}
|
|
|
|
|
2018-12-05 13:13:29 +00:00
|
|
|
func (l *HttpListener) Close() {
|
2018-11-22 03:54:01 +00:00
|
|
|
l.closed = true
|
|
|
|
l.Listener.Close()
|
|
|
|
}
|
2018-07-15 14:23:20 +00:00
|
|
|
|
2018-12-05 13:13:29 +00:00
|
|
|
func (l *HttpListener) Address() string {
|
2018-11-22 03:54:01 +00:00
|
|
|
return l.address
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
|
2018-08-11 14:51:30 +00:00
|
|
|
func handleConn(conn net.Conn) {
|
|
|
|
br := bufio.NewReader(conn)
|
2018-08-26 16:06:40 +00:00
|
|
|
request, err := http.ReadRequest(br)
|
2019-02-18 12:14:18 +00:00
|
|
|
if err != nil || !request.URL.IsAbs() {
|
2018-08-26 16:06:40 +00:00
|
|
|
conn.Close()
|
2018-08-11 14:51:30 +00:00
|
|
|
return
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
|
|
|
|
2018-08-26 16:06:40 +00:00
|
|
|
if request.Method == http.MethodConnect {
|
2018-08-11 14:51:30 +00:00
|
|
|
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2018-08-26 16:06:40 +00:00
|
|
|
tun.Add(adapters.NewHTTPS(request, conn))
|
|
|
|
return
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|
2018-08-11 14:51:30 +00:00
|
|
|
|
2018-08-26 16:06:40 +00:00
|
|
|
tun.Add(adapters.NewHTTP(request, conn))
|
2018-06-10 14:50:03 +00:00
|
|
|
}
|