-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
391 lines (335 loc) · 9.46 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package main
import (
"bufio"
"flag"
"fmt"
goconf "github.com/akrennmair/goconf"
"io"
"log"
"net"
"net/http"
"os"
"strings"
)
type Backend struct {
Name string
ConnectString string
}
type Frontend struct {
Name string
BindString string
HTTPS bool
AddForwarded bool
Hosts []string
Backends []string
//AddHeader struct { Key string; Value string }
KeyFile string
CertFile string
}
func Copy(dest *bufio.ReadWriter, src *bufio.ReadWriter) {
buf := make([]byte, 40*1024)
for {
n, err := src.Read(buf)
if err != nil && err != io.EOF {
log.Printf("Read failed: %v", err)
return
}
if n == 0 {
return
}
dest.Write(buf[0:n])
dest.Flush()
}
}
func CopyBidir(conn1 io.ReadWriteCloser, rw1 *bufio.ReadWriter, conn2 io.ReadWriteCloser, rw2 *bufio.ReadWriter) {
finished := make(chan bool)
go func() {
Copy(rw2, rw1)
conn2.Close()
finished <- true
}()
go func() {
Copy(rw1, rw2)
conn1.Close()
finished <- true
}()
<-finished
<-finished
}
type RequestHandler struct {
Transport *http.Transport
Frontend *Frontend
HostBackends map[string]chan *Backend
Backends chan *Backend
}
func (h *RequestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//log.Printf("incoming request: %#v", *r)
r.RequestURI = ""
r.URL.Scheme = "http"
if h.Frontend.AddForwarded {
remote_addr := r.RemoteAddr
idx := strings.LastIndex(remote_addr, ":")
if idx != -1 {
remote_addr = remote_addr[0:idx]
if remote_addr[0] == '[' && remote_addr[len(remote_addr)-1] == ']' {
remote_addr = remote_addr[1 : len(remote_addr)-1]
}
}
r.Header.Add("X-Forwarded-For", remote_addr)
}
if len(h.Frontend.Hosts) == 0 {
backend := <-h.Backends
r.URL.Host = backend.ConnectString
h.Backends <- backend
} else {
backend_list := h.HostBackends[r.Host]
if backend_list == nil {
if len(h.Frontend.Backends) == 0 {
http.Error(w, "no suitable backend found for request", http.StatusServiceUnavailable)
return
} else {
backend := <-h.Backends
r.URL.Host = backend.ConnectString
h.Backends <- backend
}
} else {
backend := <-backend_list
r.URL.Host = backend.ConnectString
backend_list <- backend
}
}
conn_hdr := ""
conn_hdrs := r.Header["Connection"]
log.Printf("Connection headers: %v", conn_hdrs)
if len(conn_hdrs) > 0 {
conn_hdr = conn_hdrs[0]
}
upgrade_websocket := false
if strings.ToLower(conn_hdr) == "upgrade" {
log.Printf("got Connection: Upgrade")
upgrade_hdrs := r.Header["Upgrade"]
log.Printf("Upgrade headers: %v", upgrade_hdrs)
if len(upgrade_hdrs) > 0 {
upgrade_websocket = (strings.ToLower(upgrade_hdrs[0]) == "websocket")
}
}
if upgrade_websocket {
hj, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, bufrw, err := hj.Hijack()
defer conn.Close()
conn2, err := net.Dial("tcp", r.URL.Host)
if err != nil {
http.Error(w, "couldn't connect to backend server", http.StatusServiceUnavailable)
return
}
defer conn2.Close()
err = r.Write(conn2)
if err != nil {
log.Printf("writing WebSocket request to backend server failed: %v", err)
return
}
CopyBidir(conn, bufrw, conn2, bufio.NewReadWriter(bufio.NewReader(conn2), bufio.NewWriter(conn2)))
} else {
resp, err := h.Transport.RoundTrip(r)
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "Error: %v", err)
return
}
for k, v := range resp.Header {
for _, vv := range v {
w.Header().Add(k, vv)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
resp.Body.Close()
}
}
func usage() {
fmt.Fprintf(os.Stdout, "usage: %s -config=<configfile>\n", os.Args[0])
os.Exit(1)
}
func main() {
var cfgfile *string = flag.String("config", "", "configuration file")
backends := make(map[string]*Backend)
hosts := make(map[string][]*Backend)
frontends := make(map[string]*Frontend)
flag.Parse()
if *cfgfile == "" {
usage()
}
cfg, err := goconf.ReadConfigFile(*cfgfile)
if err != nil {
log.Printf("opening %s failed: %v", *cfgfile, err)
os.Exit(1)
}
var access_f io.WriteCloser
accesslog_file, err := cfg.GetString("global", "accesslog")
if err == nil {
access_f, err = os.OpenFile(accesslog_file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
if err == nil {
defer access_f.Close()
} else {
log.Printf("Opening access log %s failed: %v", accesslog_file, err)
}
}
// first, extract backends
for _, section := range cfg.GetSections() {
if strings.HasPrefix(section, "backend ") {
tokens := strings.Split(section, " ")
if len(tokens) < 2 {
log.Printf("backend section has no name, ignoring.")
continue
}
connect_str, _ := cfg.GetString(section, "connect")
if connect_str == "" {
log.Printf("empty connect string for backend %s, ignoring.", tokens[1])
continue
}
b := &Backend{Name: tokens[1], ConnectString: connect_str}
backends[b.Name] = b
}
}
// then extract hosts
for _, section := range cfg.GetSections() {
if strings.HasPrefix(section, "host ") {
tokens := strings.Split(section, " ")
if len(tokens) < 2 {
log.Printf("host section has no name, ignoring.")
continue
}
backends_str, _ := cfg.GetString(section, "backends")
backends_list := strings.Split(backends_str, " ")
if len(backends_list) == 0 {
log.Printf("host %s has no backends, ignoring.", tokens[1])
continue
}
for _, host := range tokens[1:] {
backends_for_host := []*Backend{}
for _, backend := range backends_list {
b := backends[backend]
if b == nil {
log.Printf("backend %s doesn't exist, ignoring.", backend)
}
backends_for_host = append(backends_for_host, b)
}
hosts[host] = backends_for_host
}
}
}
// and finally, extract frontends
for _, section := range cfg.GetSections() {
if strings.HasPrefix(section, "frontend ") {
tokens := strings.Split(section, " ")
if len(tokens) < 2 {
log.Printf("frontend section has no name, ignoring.")
continue
}
frontend_name := tokens[1]
frontend := &Frontend{}
frontend.Name = frontend_name
frontend.BindString, err = cfg.GetString(section, "bind")
if err != nil {
log.Printf("error while getting [%s]bind: %v, ignoring.", section, err)
continue
}
if frontend.BindString == "" {
log.Printf("frontend %s has no bind argument, ignoring.", frontend_name)
continue
}
frontend.HTTPS, err = cfg.GetBool(section, "https")
if err != nil {
frontend.HTTPS = false
}
if frontend.HTTPS {
frontend.KeyFile, err = cfg.GetString(section, "keyfile")
if err != nil {
log.Printf("error while getting[%s]keyfile: %v, ignoring.", section, err)
continue
}
if frontend.KeyFile == "" {
log.Printf("frontend %s has HTTPS enabled but no keyfile, ignoring.", frontend_name)
continue
}
frontend.CertFile, err = cfg.GetString(section, "certfile")
if err != nil {
log.Printf("error while getting[%s]certfile: %v, ignoring.", section, err)
continue
}
if frontend.CertFile == "" {
log.Printf("frontend %s has HTTPS enabled but no certfile, ignoring.", frontend_name)
continue
}
}
frontend_hosts, err := cfg.GetString(section, "hosts")
if err == nil && frontend_hosts != "" {
frontend.Hosts = strings.Split(frontend_hosts, " ")
}
frontend_backends, err := cfg.GetString(section, "backends")
if err == nil && frontend_backends != "" {
frontend.Backends = strings.Split(frontend_backends, " ")
}
frontend.AddForwarded, _ = cfg.GetBool(section, "add-x-forwarded-for")
if len(frontend.Backends) == 0 && len(frontend.Hosts) == 0 {
log.Printf("frontend %s has neither backends nor hosts configured, ignoring.", frontend_name)
continue
}
frontends[frontend_name] = frontend
}
}
count := 0
exit_chan := make(chan int)
for name, frontend := range frontends {
log.Printf("Starting frontend %s...", name)
go func(fe *Frontend, name string) {
var accesslogger *log.Logger
if access_f != nil {
accesslogger = log.New(access_f, "frontend:"+name+" ", log.Ldate|log.Ltime|log.Lmicroseconds)
} else {
log.Printf("Not creating logger for frontend %s", name)
}
fe.Start(hosts, backends, accesslogger)
exit_chan <- 1
}(frontend, name)
count++
}
// this shouldn't return
for i := 0; i < count; i++ {
<-exit_chan
}
}
func (f *Frontend) Start(hosts map[string][]*Backend, backends map[string]*Backend, logger *log.Logger) {
mux := http.NewServeMux()
hosts_chans := make(map[string]chan *Backend)
for _, h := range f.Hosts {
host_chan := make(chan *Backend, len(hosts[h]))
for _, b := range hosts[h] {
host_chan <- b
}
hosts_chans[h] = host_chan
}
backends_chan := make(chan *Backend, len(f.Backends))
for _, b := range f.Backends {
backends_chan <- backends[b]
}
var request_handler http.Handler = &RequestHandler{Transport: &http.Transport{DisableKeepAlives: false, DisableCompression: false}, Frontend: f, HostBackends: hosts_chans, Backends: backends_chan}
if logger != nil {
request_handler = NewRequestLogger(request_handler, *logger)
}
mux.Handle("/", request_handler)
srv := &http.Server{Handler: mux, Addr: f.BindString}
if f.HTTPS {
if err := srv.ListenAndServeTLS(f.CertFile, f.KeyFile); err != nil {
log.Printf("Starting HTTPS frontend %s failed: %v", f.Name, err)
}
} else {
if err := srv.ListenAndServe(); err != nil {
log.Printf("Starting frontend %s failed: %v", f.Name, err)
}
}
}