-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
254 lines (219 loc) · 6.44 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
// Copyright 2016 by Chris Palmer (https://noncombatant.org)
// SPDX-License-Identifier: GPL-3.0
package main
import (
"encoding/pem"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path"
"regexp"
"strings"
"time"
"github.com/NYTimes/gziphandler"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/css"
"github.com/tdewolff/minify/html"
"github.com/tdewolff/minify/js"
"github.com/tdewolff/minify/json"
"github.com/tdewolff/minify/svg"
"github.com/tdewolff/minify/xml"
)
const (
configurationBasename = ".bean-machine"
serverKeyBasename = "server-key.pem"
serverCertificateBasename = "server-certificate.pem"
passwordsBasename = "passwords"
sessionsDirectoryName = "sessions"
)
func generateServerCredentials(hosts []string, configurationPathname string) (string, string) {
certificatePathname := path.Join(configurationPathname, serverCertificateBasename)
keyPathname := path.Join(configurationPathname, serverKeyBasename)
_, e1 := os.Stat(certificatePathname)
_, e2 := os.Stat(keyPathname)
if e1 == nil && e2 == nil {
return certificatePathname, keyPathname
}
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * time.Hour)
key, der, e := generateCertificate(hosts, "Bean Machine Server", notBefore, notAfter)
if e != nil {
log.Fatal(e)
}
keyFile, e := os.OpenFile(keyPathname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if e != nil {
log.Fatal(e)
}
if keyPEM, e := pemBlockForKey(key); e != nil {
log.Fatal(e)
} else {
if e := pem.Encode(keyFile, keyPEM); e != nil {
log.Fatal(e)
}
}
if e := keyFile.Close(); e != nil {
log.Fatal(e)
}
certificateFile, e := os.Create(certificatePathname)
if e != nil {
log.Fatal(e)
}
if e := pem.Encode(certificateFile, pemBlockForCertificate(der)); e != nil {
log.Fatal(e)
}
if e := certificateFile.Close(); e != nil {
log.Fatal(e)
}
return certificatePathname, keyPathname
}
func promptForCredentials(r io.Reader, w io.Writer) (string, string) {
var username, password string
fmt.Fprint(w, "Username: ")
fmt.Fscanln(r, &username)
fmt.Fprint(w, "Password: ")
fmt.Fscanln(r, &password)
return username, password
}
func getHomePathname() string {
homes := []string{
"HOME",
"USERPROFILE",
}
for _, home := range homes {
pathname := os.Getenv(home)
if pathname != "" {
return pathname
}
}
return ""
}
func makeConfigurationDirectory(configurationPathname string) {
if e := os.MkdirAll(configurationPathname, 0755); e != nil {
log.Fatal(e)
}
if e := os.MkdirAll(path.Join(configurationPathname, sessionsDirectoryName), 0755); e != nil {
log.Fatal(e)
}
}
// `port` is a string (not an integer) of the form ":1234".
func serveApp(root, port, configurationPathname string, c *Catalog) {
addresses, e := net.InterfaceAddrs()
if e != nil || len(addresses) == 0 {
log.Fatal(e)
}
message := "Starting the web server. Point your browser to any of these addresses:"
if len(addresses) == 1 {
message = "Starting the web server. Point your browser to this address:"
}
log.Print(message)
var hosts []string
for _, address := range addresses {
switch a := address.(type) {
case *net.IPNet:
if a.IP.To4() == nil {
continue
}
names, e := net.LookupAddr(a.IP.String())
if e != nil || len(names) == 0 {
log.Printf(" https://%s%s/", a.IP, port)
hosts = append(hosts, "%s", a.IP.String())
} else {
for _, name := range names {
log.Printf(" https://%s%s/", name, port)
hosts = append(hosts, name)
}
}
}
}
handler := httpHandler{Root: root, ConfigurationPathname: configurationPathname, Catalog: c, Logger: log.Default()}
minifier := minify.New()
minifier.AddFunc("text/css", css.Minify)
minifier.AddFunc("text/html", html.Minify)
minifier.AddFunc("image/svg+xml", svg.Minify)
minifier.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
minifier.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
minifier.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)
mux := http.NewServeMux()
mux.Handle("/", gziphandler.GzipHandler(minifier.Middleware(&handler)))
certificatePathname, keyPathname := generateServerCredentials(hosts, configurationPathname)
log.Fatal(http.ListenAndServeTLS(port, certificatePathname, keyPathname, mux))
}
func printHelp() {
fmt.Println(`Usage:
bean-machine -m music-directory serve
bean-machine set-password
Here is what the commands do:
serve
Scans music-directory for music files, and creates a database of their
metadata.
Starts a web server rooted at music-directory, and prints out the URL(s)
of the Bean Machine web app.
set-password
Prompts for a username and password, and sets the password for the given
username.`)
os.Exit(1)
}
func assertDirectory(pathname string) {
info, e := os.Stat(pathname)
if e != nil {
log.Fatal(e)
}
if !info.IsDir() {
log.Fatalf("%q is not a directory", pathname)
}
}
func main() {
log.SetFlags(log.Ldate | log.LUTC | log.Ltime | log.Lmicroseconds | log.Lshortfile)
needsHelp1 := flag.Bool("help", false, "Print the help message.")
needsHelp2 := flag.Bool("h", false, "Print the help message.")
rawRoot := flag.String("m", "", "Set the music directory.")
port := flag.Int("p", 0, "Set the port the server listens on.")
flag.Parse()
root := strings.TrimRight(*rawRoot, string(os.PathSeparator))
portString := ":1234"
if *port > 0 && *port < 65536 {
portString = fmt.Sprintf(":%d", *port)
} else if *port != 0 {
log.Fatal("The port number must be in the range 1 – 65535.")
}
if *needsHelp1 || *needsHelp2 || flag.NArg() == 0 {
printHelp()
}
configurationPathname := path.Join(getHomePathname(), configurationBasename)
makeConfigurationDirectory(configurationPathname)
for i := 0; i < flag.NArg(); i++ {
command := flag.Arg(i)
switch command {
case "catalog":
assertDirectory(root)
c, e := newCatalog(log.Default(), root)
if e != nil {
log.Fatal(e)
}
e = c.writeToFile(path.Join(root, catalogBasename))
if e != nil {
log.Fatal(e)
}
case "help":
printHelp()
case "serve":
assertDirectory(root)
catalog, e := readCatalogFromFile(path.Join(root, catalogBasename))
if e != nil {
log.Fatal(e)
}
serveApp(root, portString, configurationPathname, catalog)
case "set-password":
username, password := promptForCredentials(os.Stdin, os.Stdout)
if e := setPassword(configurationPathname, username, password); e != nil {
log.Fatal(e)
}
default:
printHelp()
}
}
}