-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
254 lines (215 loc) · 5.93 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
package main
import (
"bytes"
"fmt"
"io"
"log"
"net"
"net/http"
"regexp"
"time"
"encoding/base64"
"github.com/caarlos0/env/v6"
"github.com/gorilla/websocket"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
connectionsProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "wsproxy_connections_total",
Help: "The total number of processed connections",
})
activeConnections = promauto.NewGauge(prometheus.GaugeOpts{
Name: "wsproxy_active_connections",
Help: "The number of active connections",
})
proxiedBytes = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "wsproxy_bytes_total",
Help: "The total number of proxied bytes",
}, []string{"source"})
)
type Config struct {
ListenPort string `env:"LISTEN_PORT" envDefault:":80"`
PrometheusBind string `env:"PROMETHEUS_BIND" envDefault:":2112"`
AllowAddrRegex string `env:"ALLOW_ADDR_REGEX" envDefault:"^[a-zA-Z\\-0-9\\.]*\\.neon\\.tech\\:5432$"`
AppendPort string `env:"APPEND_PORT" envDefault:""`
UseHostHeader bool `env:"USE_HOST_HEADER" envDefault:"false"`
LogTraffic bool `env:"LOG_TRAFFIC" envDefault:"false"`
LogConnInfo bool `env:"LOG_CONN_INFO" envDefault:"true"`
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func IsAddrAllowed(addr string, reg *regexp.Regexp) bool {
if reg == nil {
return true
}
return reg.MatchString(addr)
}
type ProxyHandler struct {
cfg *Config
addrRegex *regexp.Regexp
}
func NewProxyHandler(config *Config) (*ProxyHandler, error) {
var (
addrRegex *regexp.Regexp
err error
)
if config.AllowAddrRegex != "" {
addrRegex, err = regexp.Compile(config.AllowAddrRegex)
if err != nil {
return nil, err
}
}
return &ProxyHandler{
cfg: config,
addrRegex: addrRegex,
}, nil
}
func (h *ProxyHandler) ExtractProxyDest(r *http.Request) (string, error) {
addressArg := r.URL.Query().Get("address")
hostHeader := r.Host
addr := addressArg
if h.cfg.UseHostHeader {
addr = hostHeader
}
if h.cfg.AppendPort != "" {
addr += h.cfg.AppendPort
}
allowed := IsAddrAllowed(addr, h.addrRegex)
if h.cfg.LogConnInfo {
log.Printf(
"Got request from %s, proxying to %s, allowed=%v, addressArg=%v, hostHeader=%v",
r.RemoteAddr,
addr, allowed,
addressArg,
hostHeader,
)
}
if !allowed {
return "", fmt.Errorf("proxying to specified address not allowed")
}
return addr, nil
}
func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.cfg.LogConnInfo {
log.Printf("Got request from %s", r.RemoteAddr)
}
addr, err := h.ExtractProxyDest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("failed to upgrade: %v\n", err)
return
}
defer conn.Close()
err = h.HandleWS(conn, addr)
if err != nil {
log.Printf("failed to handle websocket: %v\n", err)
return
}
}
func (h *ProxyHandler) HandleWS(conn *websocket.Conn, addr string) error {
connectionsProcessed.Inc()
activeConnections.Inc()
defer activeConnections.Dec()
socket, err := net.Dial("tcp", addr)
if err != nil {
return err
}
defer socket.Close()
go func() {
message := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "TCP connection is closed")
// Close the websocket connection when TCP connection loop is finished.
defer func() {
err := conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second))
if err != nil {
log.Printf("failed to send close to websocket connection: %v\n", err)
}
}()
const bufferSize = 32 * 1024
buf := make([]byte, bufferSize)
for {
n, err := socket.Read(buf)
if err != nil {
log.Printf("failed to read from socket: %v\n", err)
return
}
proxiedBytes.WithLabelValues("tcp").Add(float64(n))
if h.cfg.LogTraffic {
log.Printf("Got %d bytes pg->client: %s\n", n, base64.StdEncoding.EncodeToString(buf[:n]))
}
err = conn.WriteMessage(websocket.BinaryMessage, buf[:n])
if err != nil {
log.Printf("failed to write to websocket: %v\n", err)
return
}
}
}()
for {
_, b, err := conn.ReadMessage()
if err != nil {
return err
}
proxiedBytes.WithLabelValues("ws").Add(float64(len(b)))
if h.cfg.LogTraffic {
log.Printf("Got %d bytes client->pg: %s\n", len(b), base64.StdEncoding.EncodeToString(b))
}
_, err = io.Copy(socket, bytes.NewReader(b))
if err != nil {
return err
}
}
}
// SecureListenAndServe is a usual http.ListenAndServe that
// fixes https://deepsource.io/directory/analyzers/go/issues/GO-S2114
func SecureListenAndServe(addr string, handler http.Handler) error {
server := &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 3 * time.Second,
}
err := server.ListenAndServe()
if err == http.ErrServerClosed {
// This is a normal shutdown, we don't want to log it.
return nil
}
return err
}
func ServeMetrics(prometheusBind string) {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
err := SecureListenAndServe(prometheusBind, mux)
if err != nil {
log.Fatalf("HTTP ListenAndServe for prometheus finished with error: %v", err)
}
}
func main() {
var cfg Config
err := env.Parse(&cfg)
if err != nil {
log.Fatalf("Failed to parse config: %v", err)
}
if cfg.AllowAddrRegex == "" {
log.Printf("WARN: No regex for allowed addresses, allowing all")
} else {
log.Printf("Using regex for allowed addresses: %v", cfg.AllowAddrRegex)
}
go ServeMetrics(cfg.PrometheusBind)
handler, err := NewProxyHandler(&cfg)
if err != nil {
log.Fatalf("Failed to create proxy handler: %v", err)
}
http.Handle("/v1", handler)
log.Printf("Starting server on port %s", cfg.ListenPort)
err = SecureListenAndServe(cfg.ListenPort, nil)
if err != nil {
log.Fatalf("HTTP ListenAndServe finished with error: %v", err)
}
}