-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
278 lines (242 loc) · 6.31 KB
/
main.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"github.com/mholt/certmagic"
"github.com/oxtoacart/bpool"
"io"
"log"
"net"
"os"
"strings"
"sync"
)
var ENDING = []byte("\r\n\r\n")
var ErrHeaderToLong = errors.New("header too long")
type Config struct {
Listen string `json:"listen"`
Certificates []certificate `json:"certificates"`
AutoAuthorityCertificates []string `json:"autoAuthorityCertificates"`
BypassAddr string `json:"bypassAddr"`
MethodAddrs []*methodAddr `json:"methodsAddrs"`
BufSize int `json:"bufSize"`
MaxHeaderSize int `json:"maxHeaderSize"`
}
type certificate struct {
CertificateFile string `json:"certificateFile"`
KeyFile string `json:"keyFile"`
}
type methodAddr struct {
MethodName string `json:"methodName"`
MethodBuf []byte `json:"_"`
Addr string `json:"addr"`
}
var config = Config{
BufSize: 128,
MaxHeaderSize: 128,
}
var methodBufPool *bpool.BytePool
var headerBufPool *bpool.BytePool
func main() {
initConfig()
server()
}
func initConfig() {
var method, destination, cert, key, configPath string
flag.StringVar(&config.Listen, "l", ":443", "listen address")
flag.StringVar(&destination, "d", "127.0.0.1:8000", "v2ray server address")
flag.StringVar(&config.BypassAddr, "b", "127.0.0.1:80", "bypass server address")
flag.StringVar(&cert, "cert", "", "path to certificate file, blank to disable TLS")
flag.StringVar(&key, "key", "", "path to key file, blank to disable TLS")
flag.StringVar(&method, "method", "V2RAY", "method name of v2ray http header")
flag.StringVar(&configPath, "config", "", "path to config file")
flag.Parse()
if configPath == "" {
config.MethodAddrs = []*methodAddr{{
MethodName: method,
Addr: destination,
}}
if cert != "" && key != "" {
certs := strings.Split(cert, ",")
keys := strings.Split(key, ",")
config.Certificates = make([]certificate, len(certs))
for i := 0; i < len(config.Certificates); i++ {
config.Certificates[i] = certificate{
CertificateFile: certs[i],
KeyFile: keys[i],
}
}
}
} else {
configFile, err := os.Open(configPath)
if err != nil {
log.Fatalf("fail to open file %s: %v", configPath, err)
}
defer func() { _ = configFile.Close() }()
err = json.NewDecoder(configFile).Decode(&config)
if err != nil {
log.Fatalf("fail to parse config: %v", err)
}
}
var methodBufLen int
for _, ma := range config.MethodAddrs {
ma.MethodBuf = []byte(ma.MethodName)
mbl := len(ma.MethodBuf) + 1
if mbl > methodBufLen {
methodBufLen = mbl
}
}
methodBufPool = bpool.NewBytePool(config.BufSize, methodBufLen)
headerBufPool = bpool.NewBytePool(config.BufSize, config.MaxHeaderSize)
}
func listenTls() (ln net.Listener, err error) {
magic := certmagic.NewDefault()
magic.Agreed = true
for _, cert := range config.Certificates {
err = magic.CacheUnmanagedCertificatePEMFile(cert.CertificateFile, cert.KeyFile, nil)
if err != nil {
return
}
}
err = magic.Manage(config.AutoAuthorityCertificates)
if err != nil {
return
}
tlsConfig := &tls.Config{
GetCertificate: magic.GetCertificate,
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_AES_128_GCM_SHA256,
tls.TLS_AES_256_GCM_SHA384,
tls.TLS_CHACHA20_POLY1305_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
},
}
ln, err = tls.Listen("tcp", config.Listen, tlsConfig)
return
}
func listenTcp() (ln net.Listener, err error) {
ln, err = net.Listen("tcp", config.Listen)
return
}
func server() {
var ln net.Listener
var err error
if len(config.Certificates) != 0 {
ln, err = listenTls()
} else {
ln, err = listenTcp()
}
if err != nil {
log.Fatalf("failed to listen on %s: %v", config.Listen, err)
}
defer func() { _ = ln.Close() }()
for {
conn, err := ln.Accept()
if err != nil {
log.Printf("fail to establish conn: %v\n", err)
continue
}
go handle(conn)
}
}
func handle(srcConn net.Conn) {
defer func() { _ = srcConn.Close() }()
buf := methodBufPool.Get()
var once sync.Once
putBuf := func() {
once.Do(func() {
methodBufPool.Put(buf)
})
}
defer putBuf()
_, err := srcConn.Read(buf)
if err != nil && err != io.EOF {
log.Printf("fail to read method:%v\n", err)
return
}
var isSpecifiedMethod bool
var addr string
var leftOver []byte
for i, b := range buf {
if b == ' ' {
for _, ma := range config.MethodAddrs {
if bytes.Compare(buf[0:i], ma.MethodBuf) == 0 {
isSpecifiedMethod = true
putBuf()
addr = ma.Addr
leftOver, err = removeHttpHeader(srcConn)
if err != nil && err != io.EOF {
log.Printf("fail to remove http header:%v\n", err)
return
}
break
}
}
break
}
}
if addr == "" {
addr = config.BypassAddr
}
var dstConn net.Conn
if strings.HasPrefix(addr, "unix:") {
dstConn, err = net.Dial("unix", addr[5:])
} else {
dstConn, err = net.Dial("tcp", addr)
}
if err != nil {
log.Printf("fail to connect to %s :%v\n", addr, err)
return
}
defer func() { _ = dstConn.Close() }()
var wg sync.WaitGroup
wg.Add(2)
go func(srcConn net.Conn, dstConn net.Conn) {
if !isSpecifiedMethod {
_, _ = dstConn.Write(buf)
putBuf()
} else {
_, _ = dstConn.Write(leftOver)
}
_, err := io.Copy(dstConn, srcConn)
if err != nil && err != io.EOF {
log.Printf("failed to send to %s:%v\n", addr, err)
}
wg.Done()
}(srcConn, dstConn)
go func(srcConn net.Conn, dstConn net.Conn) {
if isSpecifiedMethod {
_, _ = srcConn.Write(ENDING)
}
_, err := io.Copy(srcConn, dstConn)
if err != nil && err != io.EOF {
log.Printf("failed to read from %s: %v\n", addr, err)
}
wg.Done()
}(srcConn, dstConn)
wg.Wait()
}
func removeHttpHeader(reader io.Reader) (leftOver []byte, err error) {
buf := headerBufPool.Get()
defer headerBufPool.Put(buf)
n, err := reader.Read(buf)
if err != nil && err != io.EOF {
return
}
idxEnding := bytes.Index(buf[0:n], ENDING)
if idxEnding < 0 {
err = ErrHeaderToLong
return
}
leftOver = buf[idxEnding+len(ENDING) : n]
return
}