-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
114 lines (92 loc) · 1.77 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
package main
import (
"crypto/tls"
"flag"
"fmt"
"io"
"log"
"net"
"time"
)
var dialer = &net.Dialer{Timeout: 10 * time.Second}
func main() {
var configfile string
flag.StringVar(&configfile, "c", "config.yaml", "config file")
flag.Parse()
cfg, err := loadConfig(configfile)
if err != nil {
log.Fatal(err)
}
initServer(cfg)
select {}
}
func initServer(cfg *conf) {
for _, srv := range *cfg {
go initListener(srv)
}
}
func initListener(srv server) {
var l net.Listener
var err error
host := net.JoinHostPort(srv.Listen.Host, fmt.Sprintf("%d", srv.Listen.Port))
if srv.Listen.Cert != "" && srv.Listen.Key != "" {
cert, err := tls.LoadX509KeyPair(srv.Listen.Cert, srv.Listen.Key)
if err != nil {
log.Fatal(err)
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
}
l, err = tls.Listen("tcp", host, config)
} else {
l, err = net.Listen("tcp", host)
}
if err != nil {
log.Fatal(err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Println(err)
break
}
go handleConn(conn, srv.Backend)
}
}
func handleConn(conn net.Conn, b backend) {
var c net.Conn
var err error
host := net.JoinHostPort(b.Host, fmt.Sprintf("%d", b.Port))
if b.TLS {
hostname := b.Host
if b.Hostname != "" {
hostname = b.Hostname
}
config := &tls.Config{
ServerName: hostname,
InsecureSkipVerify: b.Insecure,
}
c, err = tls.DialWithDialer(dialer, "tcp", host, config)
} else {
c, err = dialer.Dial("tcp", host)
}
if err != nil {
log.Println(err)
return
}
pipeAndClose(conn, c)
}
func pipeAndClose(c1, c2 net.Conn) {
defer c1.Close()
defer c2.Close()
ch := make(chan struct{}, 2)
go func() {
io.Copy(c1, c2)
ch <- struct{}{}
}()
go func() {
io.Copy(c2, c1)
ch <- struct{}{}
}()
<-ch
}