feat: use internal resolver for wg network

master
Shengjing Zhu 2022-07-23 02:06:45 +08:00
parent 5dc8b57908
commit 9298006bc7
4 changed files with 171 additions and 65 deletions

94
internal/proxy/proxy.go Normal file
View File

@ -0,0 +1,94 @@
package proxy
import (
"context"
"encoding/json"
"net"
"net/http"
"github.com/zhsj/wghttp/internal/resolver"
"github.com/zhsj/wghttp/internal/third_party/tailscale/httpproxy"
"github.com/zhsj/wghttp/internal/third_party/tailscale/proxymux"
"github.com/zhsj/wghttp/internal/third_party/tailscale/socks5"
)
type dialer func(ctx context.Context, network, address string) (net.Conn, error)
type Proxy struct {
Dial dialer
DNS string
Stats func() (any, error)
}
func statsHandler(next http.Handler, stats func() (any, error)) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Host != "" || r.URL.Path != "/stats" {
next.ServeHTTP(rw, r)
return
}
s, err := stats()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
} else {
resp, _ := json.MarshalIndent(s, "", " ")
rw.Header().Set("Content-Type", "application/json")
_, _ = rw.Write(append(resp, '\n'))
}
})
}
func dialWithDNS(dial dialer, dns string) dialer {
resolv := resolver.New(dns, dial)
return func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
if err == nil {
if ip := net.ParseIP(host); ip != nil {
return dial(ctx, network, address)
}
}
ips, err := resolv.LookupHost(ctx, host)
if err != nil {
return nil, err
}
var (
lastErr error
conn net.Conn
)
for _, ip := range ips {
addr := net.JoinHostPort(ip, port)
conn, lastErr = dial(ctx, network, addr)
if lastErr == nil {
return conn, nil
}
}
return nil, lastErr
}
}
func (p Proxy) Serve(ln net.Listener) {
d := dialWithDNS(p.Dial, p.DNS)
socksListener, httpListener := proxymux.SplitSOCKSAndHTTP(ln)
httpProxy := &http.Server{Handler: statsHandler(httpproxy.Handler(d), p.Stats)}
socksProxy := &socks5.Server{Dialer: d}
errc := make(chan error, 2)
go func() {
if err := httpProxy.Serve(httpListener); err != nil {
errc <- err
}
}()
go func() {
if err := socksProxy.Serve(socksListener); err != nil {
errc <- err
}
}()
<-errc
}

View File

@ -0,0 +1,45 @@
package proxy
import (
"context"
"fmt"
"net"
"testing"
)
func TestDialWithDNS(t *testing.T) {
if testing.Short() {
t.Skip()
}
stdDiar := net.Dialer{
Resolver: &net.Resolver{
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return nil, fmt.Errorf("dial to %s", address)
},
},
}
// d := dialWithDNS(stdDiar.DialContext, "https://223.5.5.5")
d := dialWithDNS(func(ctx context.Context, network, address string) (net.Conn, error) {
t.Logf("dial to %s:%s", network, address)
return stdDiar.DialContext(ctx, network, address)
}, "tls://223.5.5.5")
for _, addr := range []string{
"example.com:80",
"223.6.6.6:80",
"localhost:22",
"127.0.0.1:22",
} {
t.Run(addr, func(t *testing.T) {
conn, err := d(context.Background(), "tcp", addr)
if err != nil {
t.Error(err)
} else {
t.Logf("remote %s", conn.RemoteAddr())
conn.Close()
}
})
}
}

44
main.go
View File

@ -6,7 +6,6 @@ import (
_ "embed"
"fmt"
"net"
"net/http"
"net/netip"
"os"
"strings"
@ -16,9 +15,7 @@ import (
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun/netstack"
"github.com/zhsj/wghttp/internal/third_party/tailscale/httpproxy"
"github.com/zhsj/wghttp/internal/third_party/tailscale/proxymux"
"github.com/zhsj/wghttp/internal/third_party/tailscale/socks5"
"github.com/zhsj/wghttp/internal/proxy"
)
//go:embed README.md
@ -33,7 +30,7 @@ type options struct {
ClientIPs []string `long:"client-ip" env:"CLIENT_IP" env-delim:"," description:"[Interface].Address\tfor WireGuard client (can be set multiple times)"`
ClientPort int `long:"client-port" env:"CLIENT_PORT" description:"[Interface].ListenPort\tfor WireGuard client (optional)"`
PrivateKey string `long:"private-key" env:"PRIVATE_KEY" description:"[Interface].PrivateKey\tfor WireGuard client (format: base64)"`
DNS string `long:"dns" env:"DNS" description:"[Interface].DNS\tfor WireGuard network (format: IP)"`
DNS string `long:"dns" env:"DNS" description:"[Interface].DNS\tfor WireGuard network (format: protocol://ip:port)\nProtocol includes udp(default), tcp, tls(DNS over TLS) and https(DNS over HTTPS)"`
MTU int `long:"mtu" env:"MTU" default:"1280" description:"[Interface].MTU\tfor WireGuard network"`
PeerEndpoint string `long:"peer-endpoint" env:"PEER_ENDPOINT" description:"[Peer].Endpoint\tfor WireGuard server (format: host:port)"`
@ -41,7 +38,7 @@ type options struct {
PresharedKey string `long:"preshared-key" env:"PRESHARED_KEY" description:"[Peer].PresharedKey\tfor WireGuard network (optional, format: base64)"`
KeepaliveInterval time.Duration `long:"keepalive-interval" env:"KEEPALIVE_INTERVAL" description:"[Peer].PersistentKeepalive\tfor WireGuard network (optional)"`
ResolveDNS string `long:"resolve-dns" env:"RESOLVE_DNS" description:"DNS for resolving WireGuard server address (optional, format: protocol://ip:port)\nProtocol includes tcp, udp, tls(DNS over TLS) and https(DNS over HTTPS)"`
ResolveDNS string `long:"resolve-dns" env:"RESOLVE_DNS" description:"DNS for resolving WireGuard server address (optional, format: protocol://ip:port)\nProtocol includes udp(default), tcp, tls(DNS over TLS) and https(DNS over HTTPS)"`
ResolveInterval time.Duration `long:"resolve-interval" env:"RESOLVE_INTERVAL" default:"1m" description:"Interval for resolving WireGuard server address (set 0 to disable)"`
Listen string `long:"listen" env:"LISTEN" default:"localhost:8080" description:"HTTP & SOCKS5 server address"`
@ -89,26 +86,11 @@ Description:`
os.Exit(1)
}
socksListener, httpListener := proxymux.SplitSOCKSAndHTTP(listener)
dialer := proxyDialer(tnet)
proxier := proxy.Proxy{
Dial: proxyDialer(tnet), DNS: opts.DNS, Stats: stats(dev),
}
proxier.Serve(listener)
httpProxy := &http.Server{Handler: statsHandler(httpproxy.Handler(dialer), dev)}
socksProxy := &socks5.Server{Dialer: dialer}
errc := make(chan error, 2)
go func() {
if err := httpProxy.Serve(httpListener); err != nil {
logger.Errorf("Serving http proxy: %v", err)
errc <- err
}
}()
go func() {
if err := socksProxy.Serve(socksListener); err != nil {
logger.Errorf("Serving socks5 proxy: %v", err)
errc <- err
}
}()
<-errc
os.Exit(1)
}
@ -151,7 +133,7 @@ func setupNet() (*device.Device, *netstack.Net, error) {
if len(opts.ClientIPs) == 0 {
return nil, nil, fmt.Errorf("client IP is required")
}
var clientIPs, dnsServers []netip.Addr
var clientIPs []netip.Addr
for _, s := range opts.ClientIPs {
ip, err := netip.ParseAddr(s)
if err != nil {
@ -159,14 +141,8 @@ func setupNet() (*device.Device, *netstack.Net, error) {
}
clientIPs = append(clientIPs, ip)
}
if opts.DNS != "" {
ip, err := netip.ParseAddr(opts.DNS)
if err != nil {
return nil, nil, fmt.Errorf("parse DNS IP: %w", err)
}
dnsServers = append(dnsServers, ip)
}
tun, tnet, err := netstack.CreateNetTUN(clientIPs, dnsServers, opts.MTU)
tun, tnet, err := netstack.CreateNetTUN(clientIPs, nil, opts.MTU)
if err != nil {
return nil, nil, fmt.Errorf("create netstack tun: %w", err)
}

View File

@ -3,8 +3,6 @@ package main
import (
"bufio"
"bytes"
"encoding/json"
"net/http"
"runtime"
"strconv"
"strings"
@ -12,11 +10,12 @@ import (
"golang.zx2c4.com/wireguard/device"
)
func statsHandler(next http.Handler, dev *device.Device) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Host != "" || r.URL.Path != "/stats" {
next.ServeHTTP(rw, r)
return
func stats(dev *device.Device) func() (any, error) {
return func() (any, error) {
var buf bytes.Buffer
if err := dev.IpcGetOperation(&buf); err != nil {
logger.Errorf("Get device config: %v", err)
return nil, err
}
stats := struct {
@ -30,30 +29,22 @@ func statsHandler(next http.Handler, dev *device.Device) http.Handler {
NumGoroutine: runtime.NumGoroutine(),
}
var buf bytes.Buffer
if err := dev.IpcGetOperation(&buf); err != nil {
logger.Errorf("Get device config: %v", err)
rw.WriteHeader(http.StatusInternalServerError)
} else {
scanner := bufio.NewScanner(&buf)
for scanner.Scan() {
line := scanner.Text()
if prefix := "endpoint="; strings.HasPrefix(line, prefix) {
stats.Endpoint = strings.TrimPrefix(line, prefix)
}
if prefix := "last_handshake_time_sec="; strings.HasPrefix(line, prefix) {
stats.LastHandshakeTimestamp, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
if prefix := "rx_bytes="; strings.HasPrefix(line, prefix) {
stats.ReceivedBytes, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
if prefix := "tx_bytes="; strings.HasPrefix(line, prefix) {
stats.SentBytes, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
scanner := bufio.NewScanner(&buf)
for scanner.Scan() {
line := scanner.Text()
if prefix := "endpoint="; strings.HasPrefix(line, prefix) {
stats.Endpoint = strings.TrimPrefix(line, prefix)
}
if prefix := "last_handshake_time_sec="; strings.HasPrefix(line, prefix) {
stats.LastHandshakeTimestamp, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
if prefix := "rx_bytes="; strings.HasPrefix(line, prefix) {
stats.ReceivedBytes, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
if prefix := "tx_bytes="; strings.HasPrefix(line, prefix) {
stats.SentBytes, _ = strconv.ParseInt(strings.TrimPrefix(line, prefix), 10, 64)
}
resp, _ := json.MarshalIndent(stats, "", " ")
rw.Header().Set("Content-Type", "application/json")
_, _ = rw.Write(append(resp, '\n'))
}
})
return stats, nil
}
}