-
Notifications
You must be signed in to change notification settings - Fork 10
/
proxy.go
117 lines (92 loc) · 2.33 KB
/
proxy.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
package main
import (
"fmt"
"log"
"net"
"github.com/gorilla/websocket"
)
// Proxy interface
type Proxy interface {
Initialize(*websocket.Conn, *net.TCPAddr) *ProxyServer
Start()
Dial() error
Teardown()
}
// ProxyServer holds state information about the connection
// being proxied.
type ProxyServer struct {
wsConn *websocket.Conn
tcpAddr *net.TCPAddr
tcpConn *net.TCPConn
}
// Initialize ProxyServer and return struct.
func (p *ProxyServer) Initialize(wsConn *websocket.Conn, tcpAddr *net.TCPAddr) *ProxyServer {
p.wsConn = wsConn
p.tcpAddr = tcpAddr
return p
}
// Start the bidirectional communcation channel
// between the WebSocket and the remote conection.
func (p *ProxyServer) Start() {
go p.ReadWebSocket()
go p.ReadTCP()
}
// Dial is a function of proxyserver struct that
// instantiates a TCP connection to proxyserver.tcpAddr
func (p *ProxyServer) Dial() error {
tcpConn, err := net.DialTCP(p.tcpAddr.Network(), nil, p.tcpAddr)
if err != nil {
message := "dialing fail: " + err.Error()
log.Println(message)
p.wsConn.WriteMessage(websocket.TextMessage, []byte(message))
return err
}
p.tcpConn = tcpConn
tcpConnCounter.Inc()
success := fmt.Sprintf("WebSocket %s connected to %+v:%d", p.wsConn.RemoteAddr(), p.tcpAddr.IP, p.tcpAddr.Port)
log.Println(success)
return nil
}
// ReadWebSocket reads from the WebSocket and
// writes to the backend TCP connection.
func (p *ProxyServer) ReadWebSocket() {
for {
_, data, err := p.wsConn.ReadMessage()
if err != nil {
p.Teardown()
break
}
_, err = p.tcpConn.Write(data)
if err != nil {
log.Println("webSocketToTCP:", err.Error())
p.Dial()
p.tcpConn.Write(data)
}
bytesTx.Add(float64(len(data)))
}
}
// ReadTCP reads from the backend TCP connection and
// writes to the WebSocket.
func (p *ProxyServer) ReadTCP() {
buffer := make([]byte, config.bufferSize)
for {
bytesRead, err := p.tcpConn.Read(buffer)
if err != nil {
p.Teardown()
break
}
if err := p.wsConn.WriteMessage(websocket.BinaryMessage, buffer[:bytesRead]); err != nil {
log.Println("tcpToWebSocket:", err.Error())
break
}
bytesRx.Add(float64(bytesRead))
}
}
// Teardown the WebSocket and backend TCP connection.
func (p *ProxyServer) Teardown() {
p.tcpConn.Close()
p.wsConn.Close()
// Decrement Prometheus counters
tcpConnCounter.Dec()
wsConnCounter.Dec()
}