forked from happyharryh/gost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wg.go
97 lines (77 loc) · 2.28 KB
/
wg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package gost
import (
"context"
"fmt"
"log"
"net"
"reflect"
_ "unsafe"
"github.com/pufferffish/wireproxy"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun/netstack"
)
//go:linkname createIPCRequest github.com/pufferffish/wireproxy.createIPCRequest
func createIPCRequest(conf *wireproxy.DeviceConfig) (*wireproxy.DeviceSetting, error)
func NewWireguardTun(confPath string) (*netstack.Net, error) {
conf, err := wireproxy.ParseConfig(confPath)
if err != nil {
return nil, err
}
setting, err := createIPCRequest(conf.Device)
if err != nil {
return nil, err
}
tun, tnet, err := netstack.CreateNetTUN(conf.Device.Endpoint, conf.Device.DNS, conf.Device.MTU)
if err != nil {
return nil, err
}
logger := &device.Logger{
Verbosef: device.DiscardLogf,
Errorf: func(f string, v ...any) { log.Output(2, "[wg] [E] "+fmt.Sprintf(f, v...)) },
}
if Debug {
logger.Verbosef = func(f string, v ...any) { log.Output(2, "[wg] [D] "+fmt.Sprintf(f, v...)) }
}
dev := device.NewDevice(tun, conn.NewDefaultBind(), logger)
err = dev.IpcSet(reflect.ValueOf(setting).Elem().FieldByName("ipcRequest").String())
if err != nil {
return nil, err
}
err = dev.Up()
if err != nil {
return nil, err
}
return tnet, nil
}
type wireguardConnector struct {
tnet *netstack.Net
}
func WireguardConnector(tnet *netstack.Net) Connector {
return &wireguardConnector{tnet: tnet}
}
func (c *wireguardConnector) Connect(conn net.Conn, address string, options ...ConnectOption) (net.Conn, error) {
return c.ConnectContext(context.Background(), conn, "tcp", address, options...)
}
func (c *wireguardConnector) ConnectContext(ctx context.Context, conn net.Conn, network, address string, options ...ConnectOption) (net.Conn, error) {
opts := &ConnectOptions{}
for _, option := range options {
option(opts)
}
timeout := opts.Timeout
if timeout <= 0 {
timeout = ConnectTimeout
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return c.tnet.DialContext(ctx, network, address)
}
type wireguardTransporter struct {
tcpTransporter
}
func WireguardTransporter() Transporter {
return &wireguardTransporter{}
}
func (tr *wireguardTransporter) Dial(addr string, options ...DialOption) (conn net.Conn, err error) {
return nopClientConn, nil
}