-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
319 lines (297 loc) · 8.43 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
// Command leproxy implements https reverse proxy with automatic Letsencrypt usage for multiple
// hostnames/backends
package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/artyom/autoflags"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/sync/errgroup"
)
func main() {
args := runArgs{
Addr: ":https",
HTTP: ":http",
Conf: "mapping.txt",
Cache: "/var/cache/letsencrypt",
RTo: time.Minute,
WTo: 5 * time.Minute,
}
autoflags.Parse(&args)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
if err := run(ctx, args); err != nil {
log.Fatal(err)
}
}
type runArgs struct {
Addr string `flag:"addr,address to listen at"`
Conf string `flag:"map,file with host/backend mapping"`
Cache string `flag:"cacheDir,path to directory to cache key and certificates"`
HSTS bool `flag:"hsts,add Strict-Transport-Security header"`
Email string `flag:"email,contact email address presented to letsencrypt CA"`
HTTP string `flag:"http,optional address to serve http-to-https redirects and ACME http-01 challenge responses"`
RTo time.Duration `flag:"rto,maximum duration before timing out read of the request"`
WTo time.Duration `flag:"wto,maximum duration before timing out write of the response"`
Idle time.Duration `flag:"idle,how long idle connection is kept before closing (set rto, wto to 0 to use this)"`
}
func run(ctx context.Context, args runArgs) error {
if args.Cache == "" {
return fmt.Errorf("no cache specified")
}
srv, httpHandler, err := setupServer(args.Addr, args.Conf, args.Cache, args.Email, args.HSTS)
if err != nil {
return err
}
srv.ReadHeaderTimeout = 5 * time.Second
if args.RTo > 0 {
srv.ReadTimeout = args.RTo
}
if args.WTo > 0 {
srv.WriteTimeout = args.WTo
}
group, ctx := errgroup.WithContext(ctx)
if args.HTTP != "" {
httpServer := http.Server{
Addr: args.HTTP,
Handler: httpHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
group.Go(func() error { return httpServer.ListenAndServe() })
group.Go(func() error {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
return httpServer.Shutdown(ctx)
})
}
if srv.ReadTimeout != 0 || srv.WriteTimeout != 0 || args.Idle == 0 {
group.Go(func() error { return srv.ListenAndServeTLS("", "") })
} else {
group.Go(func() error {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
defer ln.Close()
ln = tcpKeepAliveListener{d: args.Idle,
TCPListener: ln.(*net.TCPListener)}
return srv.ServeTLS(ln, "", "")
})
}
group.Go(func() error {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
return srv.Shutdown(ctx)
})
return group.Wait()
}
func setupServer(addr, mapfile, cacheDir, email string, hsts bool) (*http.Server, http.Handler, error) {
mapping, err := readMapping(mapfile)
if err != nil {
return nil, nil, err
}
proxy, err := setProxy(mapping)
if err != nil {
return nil, nil, err
}
if hsts {
proxy = &hstsProxy{proxy}
}
if err := os.MkdirAll(cacheDir, 0700); err != nil {
return nil, nil, fmt.Errorf("cannot create cache directory %q: %v", cacheDir, err)
}
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache(cacheDir),
HostPolicy: autocert.HostWhitelist(keys(mapping)...),
Email: email,
}
srv := &http.Server{
Handler: proxy,
Addr: addr,
TLSConfig: m.TLSConfig(),
}
return srv, m.HTTPHandler(nil), nil
}
func setProxy(mapping map[string]string) (http.Handler, error) {
if len(mapping) == 0 {
return nil, fmt.Errorf("empty mapping")
}
mux := http.NewServeMux()
for hostname, backendAddr := range mapping {
hostname, backendAddr := hostname, backendAddr // intentional shadowing
if strings.ContainsRune(hostname, os.PathSeparator) {
return nil, fmt.Errorf("invalid hostname: %q", hostname)
}
network := "tcp"
if backendAddr != "" && backendAddr[0] == '@' && runtime.GOOS == "linux" {
// append \0 to address so addrlen for connect(2) is
// calculated in a way compatible with some other
// implementations (i.e. uwsgi)
network, backendAddr = "unix", backendAddr+string(byte(0))
} else if filepath.IsAbs(backendAddr) {
network = "unix"
if strings.HasSuffix(backendAddr, string(os.PathSeparator)) {
// path specified as directory with explicit trailing
// slash; add this path as static site
mux.Handle(hostname+"/", http.FileServer(http.Dir(backendAddr)))
continue
}
} else if u, err := url.Parse(backendAddr); err == nil {
switch u.Scheme {
case "http", "https":
rp := newSingleHostReverseProxy(u)
rp.ErrorLog = log.New(io.Discard, "", 0)
rp.BufferPool = bufPool{}
mux.Handle(hostname+"/", rp)
continue
}
}
rp := &httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = "http"
req.URL.Host = req.Host
req.Header.Set("X-Forwarded-Proto", "https")
},
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
return net.DialTimeout(network, backendAddr, 5*time.Second)
},
},
ErrorLog: log.New(io.Discard, "", 0),
BufferPool: bufPool{},
}
mux.Handle(hostname+"/", rp)
}
return mux, nil
}
func readMapping(file string) (map[string]string, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
m := make(map[string]string)
sc := bufio.NewScanner(f)
for sc.Scan() {
if b := sc.Bytes(); len(b) == 0 || b[0] == '#' {
continue
}
s := strings.SplitN(sc.Text(), ":", 2)
if len(s) != 2 {
return nil, fmt.Errorf("invalid line: %q", sc.Text())
}
m[strings.TrimSpace(s[0])] = strings.TrimSpace(s[1])
}
return m, sc.Err()
}
func keys(m map[string]string) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
type hstsProxy struct {
http.Handler
}
func (p *hstsProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
p.Handler.ServeHTTP(w, r)
}
type bufPool struct{}
func (bp bufPool) Get() []byte { return *(bufferPool.Get().(*[]byte)) }
func (bp bufPool) Put(b []byte) { bufferPool.Put(&b) }
var bufferPool = &sync.Pool{
New: func() interface{} {
buf := make([]byte, 32*1024)
return &buf
},
}
// newSingleHostReverseProxy is a copy of httputil.NewSingleHostReverseProxy
// with addition of "X-Forwarded-Proto" header.
func newSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
targetQuery := target.RawQuery
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
req.Header.Set("User-Agent", "")
}
req.Header.Set("X-Forwarded-Proto", "https")
}
return &httputil.ReverseProxy{Director: director}
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
type tcpKeepAliveListener struct {
d time.Duration
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
tc, err := ln.AcceptTCP()
if err != nil {
return nil, err
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
if ln.d == 0 {
return tc, nil
}
return timeoutConn{d: ln.d, TCPConn: tc}, nil
}
// timeoutConn extends deadline after successful read or write operations
type timeoutConn struct {
d time.Duration
*net.TCPConn
}
func (c timeoutConn) Read(b []byte) (int, error) {
n, err := c.TCPConn.Read(b)
if err == nil {
_ = c.TCPConn.SetDeadline(time.Now().Add(c.d))
}
return n, err
}
func (c timeoutConn) Write(b []byte) (int, error) {
n, err := c.TCPConn.Write(b)
if err == nil {
_ = c.TCPConn.SetDeadline(time.Now().Add(c.d))
}
return n, err
}