/
handlers.go
252 lines (230 loc) · 6.48 KB
/
handlers.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
package main
import (
"crypto/sha256"
"crypto/subtle"
"encoding/json"
"html/template"
"io"
"log"
"net/http"
"strings"
"time"
)
func Handler(s *Store, tmpls *template.Template) http.HandlerFunc {
get := FileGetHandler(s, tmpls)
new_ := NewHandler(s, tmpls)
list := ListFilesHandler(s)
edit := EditHandler(s, tmpls, "/edit/")
update := FileWriteHandler(s, "/edit/")
write := FileWriteHandler(s, "/_new")
shell := ShellHandler(s, tmpls)
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wr := &ResponseWriter{ResponseWriter: w}
switch {
case r.URL.Path == "/":
if shouldReject(w, r, http.MethodGet) {
return
}
http.Redirect(w, r, "/"+s.Index(), http.StatusTemporaryRedirect)
case r.URL.Path == "/_sh":
shell(wr, r)
case r.URL.Path == "/_new":
switch r.Method {
case http.MethodGet:
new_(wr, r)
case http.MethodPost:
write(wr, r)
}
case r.URL.Path == "/_ls":
switch r.Method {
case http.MethodGet:
list(wr, r)
}
case strings.HasPrefix(r.URL.Path, "/edit"):
switch r.Method {
case http.MethodGet:
edit(wr, r)
case http.MethodPost:
update(wr, r)
}
default:
switch r.Method {
case http.MethodGet:
get(wr, r)
case http.MethodPost:
write(wr, r)
}
}
since := time.Since(start)
log.Println(since, wr.StatusCode(), r.Method, r.URL)
}
}
func NewHandler(s *Store, tmpls *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := tmpls.ExecuteTemplate(w, "edit.html", nil); err != nil {
log.Printf("executing list template: %s", err)
writeError(w, http.StatusInternalServerError)
return
}
}
}
func EditHandler(s *Store, tmpls *template.Template, path string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Path[len(path):]
file, err := s.Get(name)
if err != nil {
// File doesn't exist, let's render a template with the name
file = Dummy(s.root, name)
}
if err := tmpls.ExecuteTemplate(w, "edit.html", file); err != nil {
log.Printf("executing list template: %s", err)
writeError(w, http.StatusInternalServerError)
return
}
}
}
func FileGetHandler(s *Store, tmpls *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimLeft(r.URL.Path, "/")
if name == "" {
writeError(w, http.StatusNotFound)
return
}
f, err := s.Get(name)
if err != nil {
// File doesn't exist, let's render a template with the name
f = Dummy(s.root, name)
}
defer f.Close()
if f.Type == "text/plain" {
if err := tmpls.ExecuteTemplate(w, "file.html", f); err != nil {
log.Printf("executing file template: %s", err)
writeError(w, http.StatusInternalServerError)
return
}
} else {
http.ServeFile(w, r, s.path(name))
}
}
}
func FileWriteHandler(s *Store, path string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(10 << 20); err != nil { //10 MB
log.Printf("couldn't parse form: %s", err)
writeError(w, http.StatusBadRequest)
return
}
var rdr io.Reader
name := r.URL.Path[len(path):]
text := r.PostForm.Get("text")
if text != "" {
if name == "" {
name = r.PostForm.Get("name")
}
// This causes scripts to act randomly. awk fails not understanding a \r
text = strings.ReplaceAll(text, "\r", "")
rdr = strings.NewReader(text)
} else {
file, meta, err := r.FormFile("file")
if err != nil {
log.Printf("Error Retrieving the File from form: %s", err)
writeError(w, http.StatusBadRequest)
return
}
defer file.Close()
if name == "" {
name = meta.Filename
}
rdr = file
}
if name == "" {
http.Error(w, "File not found", http.StatusNotFound)
return
}
if err := s.Write(name, rdr); err != nil {
log.Printf("creating file: %s", err)
writeError(w, http.StatusBadRequest)
return
}
http.Redirect(w, r, "/"+name, http.StatusSeeOther)
}
}
func ListFilesHandler(s *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
files, err := s.List()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.NewEncoder(w).Encode(&files); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
return
}
}
func ShellHandler(s *Store, tmpls *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed)
}
var input struct {
Cmd string `json:"cmd"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
out := run(s.root, "", input.Cmd)
if err := json.NewEncoder(w).Encode(map[string]interface{}{"output": out}); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
}
func basicAuth(next http.Handler, username string, password string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqUsername, reqPassword, ok := r.BasicAuth()
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
usernameHash := sha256.Sum256([]byte(reqUsername))
passwordHash := sha256.Sum256([]byte(reqPassword))
expectedUsernameHash := sha256.Sum256([]byte(username))
expectedPasswordHash := sha256.Sum256([]byte(password))
// ConstantTimeCompare is use to avoid leaking information using timing attacks
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
})
}
func shouldReject(w http.ResponseWriter, r *http.Request, method string) bool {
if r.Method == method {
return false
}
writeError(w, http.StatusMethodNotAllowed)
return true
}
func writeError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
// ResponseWriter is a wrapper for http.ResponseWriter to get the written http status code
type ResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (r *ResponseWriter) WriteHeader(statusCode int) {
r.ResponseWriter.WriteHeader(statusCode)
r.statusCode = statusCode
}
func (r *ResponseWriter) StatusCode() int {
if r.statusCode == 0 {
return http.StatusOK
}
return r.statusCode
}