-
Notifications
You must be signed in to change notification settings - Fork 8
/
configure.go
128 lines (100 loc) · 2.48 KB
/
configure.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package tunio
import (
"errors"
"log"
"math/rand"
"net"
"sync"
"time"
"unsafe"
)
/*
#include "tun2io.c"
*/
import "C"
type dialer func(proto, addr string) (net.Conn, error)
var (
debug = true
)
var (
errBufferIsFull = errors.New("Buffer is full.")
)
const (
readBufSize = 1024 * 64
)
var (
udpGwServerAddress string
)
var ioTimeout = time.Second * 30
var (
tunnels map[uint32]*TunIO
tunnelMu sync.Mutex
)
func init() {
tunnels = make(map[uint32]*TunIO)
//rand.Seed(time.Now().UnixNano())
rand.Seed(1)
udpgwInit()
}
var Dialer dialer
func dummyDialer(proto, addr string) (net.Conn, error) {
return net.Dial(proto, addr)
}
type Status uint
const (
StatusNew Status = iota // 0
StatusConnecting // 1
StatusConnectionFailed // 2
StatusConnected // 3
StatusReady // 4
StatusProxying // 5
StatusClosing // 6
StatusClosed // 7
)
// ConfigureTUN sets up the tun device, this is equivalent to the
// badvpn-tun2socks configuration, except for the --socks-server-addr.
func ConfigureTUN(tundev, ipaddr, netmask, udpgw string, d dialer) error {
if d == nil {
d = dummyDialer
}
Dialer = d
udpGwServerAddress = udpgw
ctundev := C.CString(tundev)
cipaddr := C.CString(ipaddr)
cnetmask := C.CString(netmask)
cudpgw_addr := C.CString(udpgw)
defer func() {
C.free(unsafe.Pointer(ctundev))
C.free(unsafe.Pointer(cipaddr))
C.free(unsafe.Pointer(cnetmask))
C.free(unsafe.Pointer(cudpgw_addr))
}()
log.Printf("Configuring with TUN device...")
if err_t := C.configure_tun(ctundev, cipaddr, cnetmask, cudpgw_addr); err_t != C.ERR_OK {
return errors.New("Failed to configure device.")
}
return nil
}
// ConfigureFD sets up the tun device using a file descriptor.
func ConfigureFD(tunFd int, tunMTU int, ipaddr, netmask, udpgw string, d dialer) error {
if d == nil {
d = dummyDialer
}
Dialer = d
udpGwServerAddress = udpgw
ctunFd := C.int(tunFd)
ctunMTU := C.int(tunMTU)
cipaddr := C.CString(ipaddr)
cnetmask := C.CString(netmask)
cudpgw_addr := C.CString(udpgw)
defer func() {
C.free(unsafe.Pointer(cipaddr))
C.free(unsafe.Pointer(cnetmask))
C.free(unsafe.Pointer(cudpgw_addr))
}()
log.Printf("Configuring with file descriptor...")
if err_t := C.configure_fd(ctunFd, ctunMTU, cipaddr, cnetmask, cudpgw_addr); err_t != C.ERR_OK {
return errors.New("Failed to configure device.")
}
return nil
}