-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
283 lines (231 loc) · 5.85 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
package main
import (
"errors"
"fmt"
"html/template"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/alecthomas/kingpin/v2"
)
const (
defaultPort = "8080"
readTimeout = 5 * time.Second
writeTimeout = 10 * time.Second
rootModeSingleDir int = iota
rootModeExports
rootModeSingleFile
)
var (
portFlag = kingpin.Flag("port", "The port to serve.").Short('p').Default("8080").String()
port string
useTLSFlag = kingpin.Flag("tls", "Enable TLS.").Short('t').Bool()
useTLS bool
tlsCertFlag = kingpin.Flag("cert", "Path to TLS certificate file.").Short('c').ExistingFile()
tlsCert string
tlsKeyFlag = kingpin.Flag("key", "Path to the TLS key file.").Short('k').ExistingFile()
tlsKey string
exportsArg = kingpin.Arg("files", "The files or directories to share.").Default(".").ExistingFilesOrDirs()
exports []string
tmpl = template.Must(template.New("").Parse(tmplStr))
rootMode int
)
func main() {
kingpin.Parse()
port = *portFlag
useTLS = *useTLSFlag
tlsCert = *tlsCertFlag
tlsKey = *tlsKeyFlag
for _, export := range *exportsArg {
abs, err := filepath.Abs(export)
if err != nil {
kingpin.Fatalf("error while getting export %s's absolute path: %s", export, err)
}
for _, export := range exports {
if filepath.Base(export) == filepath.Base(abs) {
kingpin.Fatalf("can't have 2 exports with same base name: %s, %s", export, abs)
}
}
exports = append(exports, abs)
}
if len(exports) == 1 {
info, err := os.Stat(exports[0])
if err != nil {
kingpin.Fatalf("error while finding root mode: %s", err)
}
if info.IsDir() {
rootMode = rootModeSingleDir
} else {
rootMode = rootModeSingleFile
}
} else {
rootMode = rootModeExports
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
if err := serveRoot(w, r); err != nil {
httpErr(w, err)
}
return
}
if err := serveExports(w, r); err != nil {
httpErr(w, err)
}
})
s := &http.Server{
Addr: ":" + port,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
}
if useTLS {
if tlsCert == "" || tlsKey == "" {
kingpin.Fatalf("flags --cert and --key are required when --tls is set")
}
fmt.Printf("https://127.0.0.1:%s/\n", port)
if err := s.ListenAndServeTLS(tlsCert, tlsKey); err != nil {
kingpin.Fatalf("error while serving: %s", err)
}
} else {
fmt.Printf("http://127.0.0.1:%s/\n", port)
if err := s.ListenAndServe(); err != nil {
kingpin.Fatalf("error while serving: %s", err)
}
}
}
func serveRoot(w http.ResponseWriter, r *http.Request) error {
export := exports[0]
if rootMode == rootModeSingleDir {
dir, err := os.ReadDir(export)
if err != nil {
return err
}
return executeDirEntries(w, dir)
} else if rootMode == rootModeSingleFile {
http.Redirect(w, r, filepath.Base(export), http.StatusPermanentRedirect)
return nil
}
return executeExports(w)
}
func serveExports(w http.ResponseWriter, r *http.Request) error {
path := filepath.Clean(r.URL.Path[1:])
var file string
getFile := func(export string, file string) (string, error) {
path := filepath.Join(export, file)
_, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return "", nil
} else if err != nil {
return "", err
}
relPath, err := filepath.Rel(export, path)
if err != nil {
return "", err
}
if !strings.HasPrefix(relPath, "..") {
return path, nil
}
return "", nil
}
if rootMode == rootModeSingleDir {
for _, export := range exports {
var err error
file, err = getFile(export, path)
if err != nil {
kingpin.Errorf("error while finding requested file: %s", err)
continue
}
if file != "" {
break
}
}
} else {
split := strings.Split(path, string(filepath.Separator))
reqExport := split[0]
reqFile := filepath.Join(split[1:]...)
for _, export := range exports {
if filepath.Base(export) == reqExport {
var err error
file, err = getFile(export, reqFile)
if err != nil {
kingpin.Errorf("error while finding requested file: %s", err)
}
break
}
}
}
if file == "" {
http.NotFound(w, r)
return nil
}
fileinfo, err := os.Stat(file)
if err != nil {
return err
}
if fileinfo.IsDir() {
if !strings.HasSuffix(r.URL.Path, "/") {
http.Redirect(w, r, r.URL.Path+"/", http.StatusPermanentRedirect)
return nil
}
dir, err := os.ReadDir(file)
if err != nil {
return err
}
return executeDirEntries(w, dir)
}
return serveFile(w, r, file)
}
func executeDirEntries(w http.ResponseWriter, dir []fs.DirEntry) error {
var links []string
for _, file := range dir {
name := file.Name()
if file.IsDir() {
name += "/"
}
links = append(links, name)
}
return tmpl.Execute(w, links)
}
func executeExports(w http.ResponseWriter) error {
var links []string
for _, file := range exports {
fileinfo, err := os.Stat(file)
if err != nil {
return err
}
name := filepath.Base(file)
if fileinfo.IsDir() {
name += "/"
}
links = append(links, filepath.Base(file))
}
return tmpl.Execute(w, links)
}
func httpErr(w http.ResponseWriter, err error) {
if !errors.Is(err, http.ErrHandlerTimeout) {
kingpin.Errorf("[%s] %s\n", time.Now().Format(time.DateTime), err.Error())
}
if w.Header().Get("Content-Type") == "" {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func serveFile(w http.ResponseWriter, r *http.Request, filename string) error {
file, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm)
if err != nil {
return err
}
defer file.Close()
fileinfo, err := os.Stat(filename)
if err != nil {
return err
}
http.ServeContent(w, r, filename, fileinfo.ModTime(), file)
return nil
}
const tmplStr string = `<!DOCTYPE html>
<html data-fbscriptallow="true"><head><meta name="viewport" content="width=device-width"></head><body>
<pre>{{range .}}<a href="{{.}}">{{.}}</a>
{{end}}</pre>
</body></html>`