This repository has been archived by the owner on Dec 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
228 lines (196 loc) · 5.59 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
package main
import (
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
)
type Server struct {
BaseDir string
DisallowDirectories bool
*UserStore
}
// ServeHTTP implements http.Handler by wrapping Handler with error handling and authentication
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Failed login requests are not logged
if s.UserStore.NeedAuth() {
uname, pw, ok := r.BasicAuth()
if !ok {
// We need authentication
w.Header().Set("WWW-Authenticate", `Basic realm="Upduck login"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
if !s.UserStore.IsValidUser(uname, pw) {
// Wrong Username/Password, try again
w.Header().Set("WWW-Authenticate", `Basic realm="Upduck login"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
log.Printf("%s: %s %s from %s\n", uname, r.Method, r.URL.String(), r.RemoteAddr)
} else {
// Normal logging
log.Println(r.Method, r.URL.String(), "from", r.RemoteAddr)
}
err := s.Handler(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("Error handling %s %s from %s: %s\n", r.Method, r.URL.String(), r.RemoteAddr, err.Error())
}
}
// Handler handles all requests
func (s *Server) Handler(w http.ResponseWriter, r *http.Request) (err error) {
if r.Method != http.MethodGet {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
p := strings.TrimPrefix(r.URL.Path, "/") // e.g. "http://server:port/test.pdf" => "test.pdf"
direct := filepath.Join(s.BaseDir, p)
// Prevent urls that go back too far, e.g. someone trying to access "/../secret.pdf"
relPath, err := filepath.Rel(s.BaseDir, direct)
if err != nil {
return
}
absPath := filepath.Join(s.BaseDir, relPath)
// Now, actually check the file
fi, err := os.Stat(absPath)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return nil
}
return
}
// Handle directory listings
if fi.IsDir() {
// If a directory contains index.html, we should always serve that instead
indexFile := filepath.Join(absPath, "index.html")
if _, err := os.Stat(indexFile); err == nil {
http.ServeFile(w, r, indexFile)
return nil
}
if s.DisallowDirectories {
// Listings *not* allowed
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
return s.Directory(absPath, w, r)
}
// Handle serving files
return s.File(absPath, w, r)
}
// File serves the given file
func (s *Server) File(filepath string, w http.ResponseWriter, r *http.Request) (err error) {
http.ServeFile(w, r, filepath)
return
}
// this isn't a good and correct HTML page, but it is supposed to be minimal and works in browsers
const templateText = `
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Index of {{.Name}}</title>
<style>
html, body {
background-color: #1a1a1a;
color: #ccc;
}
body {
margin: 0 auto;
text-align: center;
font-size: 1.25em;
}
a {
padding: 12px;
color: #2c2;
}
a:hover {
color: #2f2;
}
.dl {
font-size:0.75em;
}
.dl > a {
padding: 0;
}
</style>
<h2>Listing {{.Name}}</h2>
{{if .ShowBack}}<p><a href="../">Go back</a></p>{{end}}
<h3>Directories</h3>
<p class="dl">You can download this directory as <a href="?format=zip">zip</a>, <a href="?format=tar">tar</a> or <a href="?format=tar.gz">tar.gz</a> file.</p>
{{range .Dirs}}
<p><a href="{{.Name}}/">{{.Name}}</a></p>
{{end}}
{{with .Files}}
<h3>Files</h3>
{{range .}}
<p><a href="{{.Name}}">{{.Name}}</a></p>
{{end}}{{end}}
`
type dirListing struct {
Name string
ShowBack bool // Show link to ".."
Files []os.FileInfo
Dirs []os.FileInfo
}
var tmpl = template.Must(template.New("dirListing").Parse(templateText))
// Directory generates a directory listing
func (s *Server) Directory(dirPath string, w http.ResponseWriter, r *http.Request) (err error) {
var setDownloadHeaders = func(extension string, mimetype string) {
w.Header().Set("Content-Type", mimetype)
w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(dirPath)+"."+extension)
w.Header().Set("Pragma", "public")
w.Header().Set("Expires", "0")
w.Header().Set("Cache-Control", "must-revalidate, post-check=0, pre-check=0")
w.Header().Set("Cache-Control", "public")
}
switch strings.ToUpper(r.URL.Query().Get("format")) {
case "ZIP":
setDownloadHeaders("zip", "application/zip")
return GenerateZIPFromDir(w, dirPath, r.Context())
case "TAR":
setDownloadHeaders("tar", "application/x-tar")
return GenerateTARFromDir(w, dirPath, r.Context())
case "TAR.GZ":
setDownloadHeaders("tar.gz", "application/gzip")
return GenerateTARGZFromDir(w, dirPath, r.Context())
default:
dir, err := os.Open(dirPath)
if err != nil {
return err
}
defer dir.Close()
// List everything in the given directory
infos, err := dir.Readdir(0)
if err != nil {
return err
}
var dirs, files []os.FileInfo
// Put them in different lists
for _, f := range infos {
if f.IsDir() {
dirs = append(dirs, f)
} else {
files = append(files, f)
}
}
// Sort everything alphabetically
sort.Slice(dirs, func(i, j int) bool {
return dirs[i].Name() < dirs[j].Name()
})
sort.Slice(files, func(i, j int) bool {
return files[i].Name() < files[j].Name()
})
// If we serve the main directory, we don't show the go back link
var showBack = filepath.Clean(s.BaseDir) != filepath.Clean(dirPath)
dirBase := filepath.Base(dirPath)
w.Header().Set("Content-Type", "text/html")
return tmpl.Execute(w, dirListing{
Name: dirBase,
ShowBack: showBack,
Files: files,
Dirs: dirs,
})
}
}