-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrivethru.go
449 lines (360 loc) · 10.1 KB
/
drivethru.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
package main
import (
"archive/tar"
"compress/gzip"
"context"
"crypto/md5"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"strings"
ini "gopkg.in/ini.v1"
"github.com/asaskevich/govalidator"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/goware/cors"
"github.com/murdinc/terminal"
)
// Global
var menu *Menu
type Menu struct {
URL string
Host string
Port string
Root string
Profiles []Profile
}
type Profile struct {
Name string `ini:"-"` // actually the section name
Source string `ini:"source"`
Destination string `ini:"destination"`
Github string `ini:"github"`
Universal bool `ini:"universal"`
Extra []string `ini:"extra"`
URL string `ini:"-"`
}
func main() {
terminal.Information("loading config...")
var err error
menu, err = loadMenu()
if err != nil {
terminal.ErrorLine(err.Error())
return
}
terminal.Delta("config loaded.")
r := chi.NewRouter()
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET"},
AllowCredentials: true,
})
r.Use(cors.Handler)
r.Use(middleware.StripSlashes)
r.Use(middleware.Recoverer)
r.Route("/get", func(r chi.Router) {
r.Route("/{name}", func(r chi.Router) {
r.Use(NameCtx)
r.Get("/", getScript)
})
})
r.Route("/hash", func(r chi.Router) {
r.Route("/{name}", func(r chi.Router) {
r.Use(NameCtx)
r.Get("/", getHash)
r.Route("/{os}/{arch}", func(r chi.Router) {
r.Get("/", getHash)
})
})
})
r.Route("/download", func(r chi.Router) {
r.Route("/{name}", func(r chi.Router) {
r.Use(NameCtx)
r.Get("/", getDownload)
r.Route("/{os}/{arch}", func(r chi.Router) {
r.Get("/", getDownload)
})
})
})
// Default port
if menu.Port == "" {
menu.Port = "2468"
}
// Default host
if menu.Host == "" {
menu.Host = "localhost"
}
// Default URL
if menu.URL == "" {
menu.URL = menu.Host + ":" + menu.Port
}
terminal.Delta("server started: " + menu.Host + ":" + menu.Port + ", with URL: " + menu.URL)
http.ListenAndServe(menu.Host+":"+menu.Port, r)
}
func NameCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
classType := chi.URLParam(r, "name")
ctx := context.WithValue(r.Context(), "name", classType)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func getScript(w http.ResponseWriter, r *http.Request) {
profileName := r.Context().Value("name").(string)
Loop:
for _, profile := range menu.Profiles {
if profile.Name == profileName {
profile.URL = menu.URL
_, err := os.Stat(menu.Root + profile.Source)
if err != nil {
terminal.ErrorLine(err.Error() + " : " + profile.Source)
break Loop
}
// If universal, pass them the universal script
if profile.Universal {
t, _ := template.New("script").Parse(universalScriptTemplate)
t.Execute(w, profile)
return
}
t, _ := template.New("script").Parse(scriptTemplate)
t.Execute(w, profile)
return
}
}
t, _ := template.New("script").Parse(errorScriptTemplate)
t.Execute(w, profileName)
}
func getDownload(w http.ResponseWriter, r *http.Request) {
profileName := r.Context().Value("name").(string)
osName := chi.URLParam(r, "os")
archName := chi.URLParam(r, "arch")
switch archName {
case "x86_64":
archName = "amd64"
}
terminal.Information(fmt.Sprintf("Download request for: %s, OS: %s, Arch: %s\n", profileName, osName, archName))
for _, profile := range menu.Profiles {
if profile.Name == profileName {
source := menu.Root + profile.Source + "/"
if !profile.Universal {
if osName != "" && archName != "" {
source = source + osName + "/" + archName + "/"
} else {
terminal.ErrorLine("Invalid request.")
http.Error(w, "Invalid request.", 500)
return
}
}
terminal.Information(fmt.Sprintf("Download request file source: %s\n", source))
err := zipIt(profile.Name, source, w)
if err != nil {
terminal.ErrorLine(err.Error())
}
return
}
}
}
func getHash(w http.ResponseWriter, r *http.Request) {
profileName := r.Context().Value("name").(string)
osName := chi.URLParam(r, "os")
archName := chi.URLParam(r, "arch")
switch archName {
case "x86_64":
archName = "amd64"
}
terminal.Information(fmt.Sprintf("Download request for: %s, OS: %s, Arch: %s\n", profileName, osName, archName))
for _, profile := range menu.Profiles {
if profile.Name == profileName {
source := menu.Root + profile.Source + "/"
if !profile.Universal {
if osName != "" && archName != "" {
source = source + osName + "/" + archName + "/"
} else {
terminal.ErrorLine("Invalid request.")
http.Error(w, "Invalid request.", 500)
return
}
}
terminal.Information(fmt.Sprintf("Download request file source: %s\n", source))
md5Hash := md5.New()
err := zipIt(profile.Name, source, md5Hash)
if err != nil {
terminal.ErrorLine(err.Error())
http.Error(w, err.Error(), 500)
return
}
hashString := fmt.Sprintf("%x", md5Hash.Sum(nil))
io.WriteString(w, hashString)
terminal.Information("Returned Hash: " + hashString + " for file source: " + source + ".\n")
return
}
}
}
func zipIt(name, source string, w io.Writer) (err error) {
// gzip writer
gz := gzip.NewWriter(w)
defer gz.Close()
gz.Name = name
// tarball
tarball := tar.NewWriter(gz)
defer tarball.Close()
info, err := os.Stat(source)
if err != nil {
return
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(name)
}
return filepath.Walk(source,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
if err := tarball.WriteHeader(header); err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tarball, file)
return err
})
}
func loadMenu() (*Menu, error) {
menu := new(Menu)
cfg, err := ini.Load("/etc/drivethru/drivethru.conf")
if err != nil {
return menu, err
}
apps := cfg.Sections()
for _, app := range apps {
if app.Name() == "DEFAULT" {
menu.URL = app.Key("url").String()
menu.Host = app.Key("host").String()
menu.Port = app.Key("port").String()
menu.Root = app.Key("root").String()
continue
}
profile := new(Profile)
err := app.MapTo(profile)
if err != nil {
return menu, err
}
profile.Name = app.Name()
menu.Profiles = append(menu.Profiles, *profile)
// Add path separators if needed
// Source
if profile.Source[0] != os.PathSeparator {
profile.Source = fmt.Sprintf("%s%s", string(os.PathSeparator), profile.Source)
}
if profile.Source[len(profile.Source)-1] != os.PathSeparator {
profile.Source = fmt.Sprintf("%s%s", profile.Source, string(os.PathSeparator))
}
// Destination
if profile.Destination[0] != os.PathSeparator {
profile.Destination = fmt.Sprintf("%s%s", string(os.PathSeparator), profile.Destination)
}
if profile.Destination[len(profile.Destination)-1] != os.PathSeparator {
profile.Destination = fmt.Sprintf("%s%s", profile.Destination, string(os.PathSeparator))
}
terminal.Information(fmt.Sprintf("- found profile named %s.", profile.Name))
}
if len(menu.Host) > 0 && !govalidator.IsHost(menu.Host) {
return menu, errors.New("host specified in conf is invalid: " + menu.Host)
}
if len(menu.Port) > 0 && !govalidator.IsPort(menu.Port) {
return menu, errors.New("port specified in conf is invalid: " + menu.Host)
}
// Add path separator if needed
if menu.Root[len(menu.Root)-1] != os.PathSeparator {
menu.Root = fmt.Sprintf("%s%s", menu.Root, string(os.PathSeparator))
}
terminal.Delta(fmt.Sprintf("loaded %d profiles.", len(menu.Profiles)))
return menu, err
}
// TEMPLATES
////////////////
var scriptTemplate = `#!/bin/sh
FORMAT="tar.gz"
TEMPFOLDER="/tmp/drivethru-{{ .Name }}-$$"
TARBALL="$TEMPFOLDER/tar/{{ .Name }}.$FORMAT"
OS=$(uname)
ARCH=$(uname -m)
URL="http://{{ .URL }}/download/{{ .Name }}/$OS/$ARCH/"
DEST={{ .Destination }}
sudo mkdir -p /tmp/$$/ && sudo chmod 777 /tmp/$$/
sudo mkdir -p "$TEMPFOLDER/tar"
sudo mkdir -p "$TEMPFOLDER/expanded"
sudo chmod -R 777 "$TEMPFOLDER"
echo "Downloading $URL"
curl -o $TARBALL -L -f $URL
if [ $? -eq 0 ]
then
echo "\nCopying {{ .Name }} into $DEST\n"
sudo mkdir -p $DEST/
tar -xzf $TARBALL -C $TEMPFOLDER/expanded && sudo cp -av $TEMPFOLDER/expanded/{{ .Name }}/* $DEST/ && rm -rf $TARBALL
if [ $? -eq 0 ]
then
sudo rm -rf "$TEMPFOLDER"
echo "\n{{ .Name }} has been installed into $DEST\n"
{{ if .Extra }}{{ $url := .URL }}
{{ range .Extra }}curl -s http://{{ $url }}/get/{{ . }} | sh
{{end}}{{ else }}echo "Done!"{{end}}
exit 0
fi
else
echo "Failed to install {{ .Name }}.\nPlease try downloading from {{ .Github }} instead."
sudo rm -rf "$TEMPFOLDER"
fi
exit 1
`
var universalScriptTemplate = `#!/bin/sh
FORMAT="tar.gz"
TEMPFOLDER="/tmp/drivethru-{{ .Name }}-$$"
TARBALL="$TEMPFOLDER/tar/{{ .Name }}.$FORMAT"
URL="http://{{ .URL }}/download/{{ .Name }}/"
DEST="{{ .Destination }}"
sudo mkdir -p "$TEMPFOLDER/tar"
sudo mkdir -p "$TEMPFOLDER/expanded"
sudo chmod -R 777 "$TEMPFOLDER"
echo "Downloading $URL"
curl -o $TARBALL -L -f $URL
if [ $? -eq 0 ]
then
echo "\nCopying {{ .Name }} into $DEST\n"
sudo mkdir -p $DEST/
tar -xzf $TARBALL -C $TEMPFOLDER/expanded && sudo cp -av $TEMPFOLDER/expanded/{{ .Name }}/* $DEST/ && rm -rf $TARBALL
if [ $? -eq 0 ]
then
sudo rm -rf "$TEMPFOLDER"
echo "\n{{ .Name }} has been installed into $DEST\n"
{{ if .Extra }}{{range .Extra}}http://{{ .URL }}/get/{{ . }}/ | sh
{{end}}{{end}}
echo "Done!"
exit 0
fi
else
echo "Failed to install {{ .Name }}.\nPlease try downloading from {{ .Github }} instead."
sudo rm -rf "$TEMPFOLDER"
fi
exit 1
`
var errorScriptTemplate = `#!/bin/sh
echo "There was an error building your script for the download of {{ . }}, please contact the developer."
exit 1
`