mihomo/proxy/http/server.go

75 lines
1.2 KiB
Go
Raw Normal View History

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"
2018-09-30 12:25:52 +08:00
"github.com/Dreamacro/clash/adapters/inbound"
2018-11-21 13:47:46 +08:00
"github.com/Dreamacro/clash/log"
2018-06-14 01:00:58 +08:00
"github.com/Dreamacro/clash/tunnel"
2018-06-10 22:50:03 +08:00
)
2018-06-14 01:00:58 +08:00
var (
tun = tunnel.Instance()
2018-06-14 01:00:58 +08:00
)
type httpListener struct {
net.Listener
address string
closed bool
}
func NewHttpProxy(addr string) (*httpListener, error) {
2018-07-15 22:23:20 +08:00
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
2018-07-15 22:23:20 +08:00
}
hl := &httpListener{l, addr, false}
2018-07-15 22:23:20 +08:00
go func() {
2018-11-21 13:47:46 +08:00
log.Infoln("HTTP proxy listening at: %s", addr)
2018-08-11 22:51:30 +08:00
for {
c, err := hl.Accept()
2018-08-11 22:51:30 +08:00
if err != nil {
if hl.closed {
2018-08-11 22:51:30 +08:00
break
}
continue
}
go handleConn(c)
}
2018-07-15 22:23:20 +08:00
}()
return hl, nil
}
func (l *httpListener) Close() {
l.closed = true
l.Listener.Close()
}
2018-07-15 22:23:20 +08:00
func (l *httpListener) Address() string {
return l.address
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)
2018-08-27 00:06:40 +08:00
request, err := http.ReadRequest(br)
if err != nil {
conn.Close()
2018-08-11 22:51:30 +08:00
return
2018-06-10 22:50:03 +08:00
}
2018-08-27 00:06:40 +08:00
if request.Method == http.MethodConnect {
2018-08-11 22:51:30 +08:00
_, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
return
}
2018-08-27 00:06:40 +08:00
tun.Add(adapters.NewHTTPS(request, conn))
return
2018-06-10 22:50:03 +08:00
}
2018-08-11 22:51:30 +08:00
2018-08-27 00:06:40 +08:00
tun.Add(adapters.NewHTTP(request, conn))
2018-06-10 22:50:03 +08:00
}