-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.go
586 lines (540 loc) · 13.3 KB
/
server.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package server
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"errors"
"flag"
"fmt"
"io"
"log"
"math/big"
"mime"
"net"
"net/http"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/acme/autocert"
)
const pathSeperator = "/"
const (
cert = "cert.pem"
key = "key.pem"
certDir = ".autocert"
)
// httpServer holds the relavent info/state
type httpServer struct {
Port int
TLSPort int
HTTPS bool
dir string
log *log.Logger
waiter sync.WaitGroup
handler func(w http.ResponseWriter, r *http.Request)
}
type writerExtra struct {
base http.ResponseWriter
log *log.Logger
dir string
}
func (w *writerExtra) Header() http.Header { return w.base.Header() }
func (w *writerExtra) WriteHeader(code int) { w.base.WriteHeader(code) }
func (w *writerExtra) Write(p []byte) (int, error) { return w.base.Write(p) }
func (w *writerExtra) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hj, ok := w.base.(http.Hijacker)
if !ok {
return nil, nil, errors.New("base response does not implement http.Hijacker")
}
return hj.Hijack()
}
// ServeHTTP handles inbound requests
func (h *httpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.waiter.Wait()
if h.HTTPS && req.TLS == nil {
url := "https://" + strings.Split(req.Host, ":")[0]
if h.TLSPort != 443 {
url = url + ":" + strconv.FormatInt(int64(h.TLSPort), 10)
}
url += req.URL.String()
http.Redirect(w, req, url, 302)
return
}
h.handler(&writerExtra{w, h.log, h.dir}, req)
}
type keepAliveListener struct {
*net.TCPListener
}
func (k keepAliveListener) Accept() (net.Conn, error) {
tc, err := k.AcceptTCP()
if err != nil {
return nil, err
}
if err := tc.SetKeepAlive(true); err != nil {
return nil, err
}
if err := tc.SetKeepAlivePeriod(time.Minute * 3); err != nil {
return nil, err
}
return tc, nil
}
func getpwd() string {
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
return pwd
}
func homeDir() string {
u, err := user.Current()
if err != nil {
panic(err)
}
return u.HomeDir
}
const usage = `{{NAME}} version: {{VERSION}}
Usage: {{NAME}} [-p port] [-l domain]
Options:
-h : this help
-v : show version and exit
-g : enable TLS/HTTPS generate and use a self signed certificate
-p port : bind HTTP port (default: 8000)
-l domain : enable TLS/HTTPS with Let's Encrypt for the given domain name.
-c path : enable TLS/HTTPS use a predefined HTTPS certificate
-t port : bind HTTPS port (default: 443, 4433 for -g)
-r path : use directory as root for static files (default: {{DEFDIR}})
{{USAGE}}
Examples: {{NAME}} start {{NAME}}. http://localhost:8000
or: {{NAME}} -p 80 use HTTP port 80. http://localhost
or: {{NAME}} -g enable HTTPS generated certificate. https://localhost:4433
or: {{NAME}} -l example.com enable HTTPS with Let's Encrypt. https://example.com
`
// Options are server options
type Options struct {
// Name gives the server binary a name.
Name string
// Version is the version of the server.
Version string
// Init is an optional function that fires after the server is listening
// but before allowing incoming requests.
Init func()
// Flags is an optional function that allows for adding command line flags.
Flags func()
// FlagsParsed is an optional function that fires immediately after flags are parsed.
FlagsParsed func()
// Usage is an optional function that allows for altering the usage text.
Usage func(usage string) string
// Logger is a custom logger
Logger *log.Logger
// Dir is the directory static files. Default is "."
Dir string
// NoFlags disables automated flags and the the help menu
NoFlags bool
// Port bind HTTP port. default is 8000.
Port int
// LetsEncryptDomain enable TLS/HTTPS with Let's Encrypt for the given
// domain name.
LetsEncryptDomain string
}
// Main starts the server environment.
func Main(handler func(w http.ResponseWriter, r *http.Request), opts *Options) {
if opts == nil {
opts = &Options{}
}
if opts.Name == "" {
opts.Name = "server"
}
if opts.Version == "" {
opts.Version = "0.0.0"
}
if opts.Dir == "" {
opts.Dir = "."
}
if opts.Port == 0 {
opts.Port = 8000
}
l := opts.Logger
if l == nil {
l = log.New(os.Stderr, "", log.LstdFlags)
}
port := opts.Port
le := opts.LetsEncryptDomain
dir := opts.Dir
var gs bool
var tlsPort int
var tlsCert string
var vers bool
if !opts.NoFlags {
flag.Usage = func() {
w := os.Stderr
for _, arg := range os.Args {
if arg == "-h" {
w = os.Stdout
break
}
}
s := usage
s = strings.Replace(s, "{{VERSION}}", opts.Version, -1)
s = strings.Replace(s, "{{NAME}}", opts.Name, -1)
s = strings.Replace(s, "{{DEFDIR}}", opts.Dir, -1)
if opts.Usage != nil {
s = opts.Usage(s)
}
s = strings.Replace(s, "{{USAGE}}", "", -1)
w.Write([]byte(s))
}
flag.BoolVar(&vers, "v", false, "")
flag.IntVar(&port, "p", port, "")
flag.StringVar(&le, "l", le, "")
flag.StringVar(&dir, "r", dir, "")
flag.StringVar(&tlsCert, "c", "", "")
flag.BoolVar(&gs, "g", false, "")
flag.IntVar(&tlsPort, "t", -1, "")
if opts.Flags != nil {
opts.Flags()
}
flag.Parse()
if opts.FlagsParsed != nil {
opts.FlagsParsed()
}
}
if vers {
fmt.Fprintf(os.Stdout, "%s version: %s\n", opts.Name, opts.Version)
return
}
if tlsPort == -1 {
if gs {
tlsPort = 4433
} else {
tlsPort = 443
}
}
if le != "" {
// flags that are not allowed with Let's Encrypt
badFlags := []string{"p", "c", "g", "t"}
var bad bool
for _, f := range badFlags {
var found bool
flag.Visit(func(ff *flag.Flag) {
if ff.Name == f {
found = true
}
})
if found {
bad = true
fmt.Fprintf(os.Stderr, "flags -l and -%s cannot be used together\n", f)
}
}
if bad {
os.Exit(1)
}
tlsPort = 443
port = 80
}
var adir string
var err error
if dir != "" {
adir, err = filepath.Abs(dir)
} else {
adir, err = filepath.Abs(".")
}
if err != nil {
l.Fatalf("invalid directory: %s", dir)
}
dir = adir
h := &httpServer{
Port: port,
TLSPort: tlsPort,
log: l,
handler: handler,
HTTPS: le != "" || tlsCert != "" || gs,
dir: dir,
}
pinit := func() {
h.waiter.Add(1)
defer h.waiter.Done()
if opts.Init != nil {
opts.Init()
}
}
if le != "" {
// Let's Encrypt!
cacheDir := filepath.Join(homeDir(), certDir)
if err := os.MkdirAll(cacheDir, 0700); err != nil {
l.Fatalf("could not create cache directory: %s" + err.Error())
}
m := &autocert.Manager{
Cache: autocert.DirCache(cacheDir),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(le),
}
go http.ListenAndServe(":http", m.HTTPHandler(h))
go func() {
time.Sleep(time.Millisecond * 100)
l.Printf("Serving with Let's Encrypt!...\n")
pinit()
}()
s := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
Handler: h,
}
l.Fatal(s.ListenAndServeTLS("", ""))
return
}
if h.HTTPS {
var certPath, keyPath string
switch {
case tlsCert != "":
if gs {
l.Fatal("cannot specify both -tls-cert and -g")
}
certPath, keyPath = tlsCert, tlsCert // assume a single PEM format
case gs:
hd := homeDir()
certPath = filepath.Join(hd, certDir, cert)
keyPath = filepath.Join(hd, certDir, key)
if err := generateCertificates(certPath, keyPath); err != nil {
l.Fatalln(err)
}
}
go l.Fatal(http.ListenAndServeTLS(fmt.Sprintf(":%d", tlsPort), certPath, keyPath, h))
go func() {
time.Sleep(time.Millisecond * 100)
l.Printf("Serving HTTP on port %v, HTTPS on port %v...\n", h.Port, tlsPort)
pinit()
}()
} else {
go func() {
time.Sleep(time.Millisecond * 100)
l.Printf("Serving HTTP on port %v ...\n", h.Port)
pinit()
}()
}
l.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), h))
}
// most of the certificate stuff shamelessly lifted from the
// example found here https://golang.org/src/crypto/tls/generate_cert.go
// namesAndAddresses generates a slice of hostnames and addresses
// to generate certificates for
func namesAndAddresses() ([]string, error) {
var r []string
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
r = append(r, v.IP.String())
}
}
}
h, err := os.Hostname()
if err != nil {
return nil, err
}
r = append(r, h)
return r, nil
}
var (
ecdsaCurve = ""
)
func publicKey(priv interface{}) interface{} {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(priv interface{}) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
os.Exit(2)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
default:
return nil
}
}
// generateCertificates will generate a certificate and key and save them to
// the given paths
func generateCertificates(certPath, keyPath string) error {
var priv interface{}
var err error
switch ecdsaCurve {
case "":
priv, err = rsa.GenerateKey(rand.Reader, 4096)
case "P224":
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "P256":
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "P384":
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "P521":
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
return fmt.Errorf("unrecognized elliptic curve: %q", ecdsaCurve)
}
if err != nil {
return err
}
start := time.Now()
expire := start.Add(365 * 24 * time.Hour)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: start,
NotAfter: expire,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts, err := namesAndAddresses()
if err != nil {
return err
}
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
return err
}
certOut, err := os.Create(certPath)
if err != nil {
return err
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return err
}
if err := certOut.Close(); err != nil {
return err
}
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
if err := pem.Encode(keyOut, pemBlockForKey(priv)); err != nil {
return err
}
return keyOut.Close()
}
// HandleFiles is handler for ... wait for it ... handling files.
// It just handles static files from your current directory.
func HandleFiles(w http.ResponseWriter, r *http.Request) {
var l *log.Logger
var dir string
if w, ok := w.(*writerExtra); ok {
l = w.log
dir = w.dir
}
code := 200
path := r.URL.Path[1:]
opath := path
if l != nil {
defer func() {
l.Printf("%s %d /%s", r.RemoteAddr, code, opath)
}()
}
if r.Method != "GET" && r.Method != "HEAD" {
http.Error(w, "Method Not Allowed", 405)
return
}
if path == "" {
path = "."
}
if strings.Contains(path, "../") || strings.Contains(path, "/..") {
code = 404
http.NotFound(w, r)
return
}
again:
apath := filepath.Join(dir, path)
if !strings.HasPrefix(apath, dir) {
code = 404
http.NotFound(w, r)
return
}
f, err := os.Open(apath)
if os.IsNotExist(err) && filepath.Ext(apath) == "" {
apath = apath + ".html"
f, err = os.Open(apath)
}
if err != nil {
if os.IsNotExist(err) {
code = 404
http.NotFound(w, r)
} else {
code = 500
http.Error(w, err.Error(), 500)
}
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
code = 500
http.Error(w, err.Error(), 500)
return
}
if fi.IsDir() {
f.Close()
path = filepath.Join(path, "index.html")
goto again
}
sum := md5.Sum([]byte(fmt.Sprintf("%d-%s", fi.Size(), fi.ModTime())))
etag := hex.EncodeToString(sum[:])
petag := r.Header.Get("If-None-Match")
if petag != "" && etag == petag {
code = http.StatusNotModified
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(apath)))
w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
w.Header().Set("Last-Modified", fi.ModTime().Format(time.RFC1123))
w.Header().Set("ETag", etag)
w.WriteHeader(200)
if r.Method != "HEAD" {
io.Copy(w, f)
}
}