-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-root.go
More file actions
267 lines (235 loc) · 6.29 KB
/
http-root.go
File metadata and controls
267 lines (235 loc) · 6.29 KB
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
// Copyright 2020 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package main
import (
"fmt"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// Ensure file integrity
var fileLock sync.RWMutex
// Root handler
func inboundWebRootHandler(httpRsp http.ResponseWriter, httpReq *http.Request) {
// Process the request URI, looking for things that will indicate "dev"
method := httpReq.Method
if method == "" {
method = "GET"
}
// Get the body if supplied
reqJSON, err := io.ReadAll(httpReq.Body)
if err != nil {
reqJSON = []byte{}
}
// Get the target
rawTarget, args := HTTPArgs(httpReq, "")
rawTarget = strings.TrimSuffix(rawTarget, "/")
target := cleanTarget(rawTarget)
// Exit if just the favicon
if rawTarget == "favicon.ico" {
return
}
// Process args
count, _ := strconv.Atoi(args["count"])
if count == 0 {
count, _ = strconv.Atoi(args["tail"])
}
clean, _ := strconv.Atoi(args["clean"])
append := false
uploadFilename := args["append"]
if uploadFilename != "" {
append = true
} else {
uploadFilename = args["upload"]
}
deleteFilename := args["delete"]
// Map the delete verb
if method == "DELETE" && strings.Contains(rawTarget, "/") && !strings.Contains(rawTarget, ":") {
httpRsp.Write(deleteFile(rawTarget))
return
}
// Process appropriately
if (method == "POST" || method == "PUT") && uploadFilename != "" {
if len(reqJSON) == 0 {
httpRsp.Write([]byte("error: zero-length file"))
return
}
// Acknowledge the upload as quickly as possible and tear down the
// connection so the caller (e.g. a camera posting at ~1 fps) never
// waits on our local disk I/O. The request body has already been
// fully read into reqJSON, so we can safely hand the write off to
// a goroutine. Any write error is logged by uploadFile; the caller
// will not see it — that is the intentional trade-off.
body := []byte("ok\n")
httpRsp.Header().Set("Content-Type", "text/plain; charset=utf-8")
httpRsp.Header().Set("Content-Length", strconv.Itoa(len(body)))
httpRsp.Header().Set("Connection", "close")
httpRsp.WriteHeader(http.StatusOK)
httpRsp.Write(body)
if f, ok := httpRsp.(http.Flusher); ok {
f.Flush()
}
go uploadFile(target+"/"+uploadFilename, append, reqJSON)
return
}
if deleteFilename != "" {
httpRsp.Write(deleteFile(target + "/" + deleteFilename))
return
}
if method == "GET" && strings.Contains(rawTarget, "/") && !strings.Contains(rawTarget, ":") {
var ctype string
c := strings.Split(rawTarget, ".")
if len(c) > 1 {
ctype = mime.TypeByExtension("." + c[len(c)-1])
if ctype != "" {
httpRsp.Header().Set("Content-Type", ctype)
httpRsp.WriteHeader(http.StatusOK)
}
}
contents, _ := getFile(rawTarget, ctype)
httpRsp.Write(contents)
return
}
if method == "GET" {
path := rawTarget + "/index.html"
ctype := mime.TypeByExtension(".html")
_, exists := getFile(path, ctype)
if exists {
fmt.Printf("redirect to %s\n", path)
http.Redirect(httpRsp, httpReq, path, http.StatusTemporaryRedirect)
return
}
}
if method == "GET" && target == "" {
help(httpRsp)
return
}
if method == "GET" && count != 0 {
data := tail(target, count, false, &args)
httpRsp.Write(data)
return
}
if method == "GET" && clean != 0 {
data := tail(target, clean, true, nil)
httpRsp.Write(data)
return
}
// If the target is a directory containing image files, serve the
// auto-refreshing photo viewer (or, with ?latest=1, just the newest
// filename for the viewer's polling loop). Falls through to watch()
// below for non-image directories so JSON streams behave as before.
if method == "GET" && target != "" && !strings.Contains(rawTarget, "/") && isPhotoDirectory(target) {
if args["latest"] != "" {
photoLatest(httpRsp, target)
} else {
photoViewer(httpRsp, target)
}
return
}
if method == "GET" {
watch(httpRsp, httpReq, target)
return
}
if (method == "POST" || method == "PUT") && len(reqJSON) > 0 {
post(httpRsp, target, reqJSON)
return
}
httpRsp.Write([]byte(method + " " + target + " ???"))
}
// Clean a target so that it contains only the chars legal in a filename
func cleanTarget(in string) (out string) {
for _, r := range strings.ToLower(in) {
c := string(r)
if (c >= "a" && c <= "z") || (c >= "0" && c <= "9") || (c == "_" || c == "-") {
out = out + c
} else {
out = out + "-"
}
}
return
}
// Clean a filename
func cleanFilename(in string) (out string, bad bool) {
if strings.Contains(in, "..") {
return "", true
}
if strings.Contains(in, "./") {
return "", true
}
if strings.HasPrefix(in, "/") {
return "", true
}
out = filepath.Join(configDataDirectory, in)
return
}
// Upload a file. This runs on a background goroutine so the HTTP caller
// does not wait on local disk I/O; any error is logged here and not
// propagated back to the client.
func uploadFile(filename string, append bool, contents []byte) {
pathname, bad := cleanFilename(filename)
if bad {
return
}
fmt.Printf("upload %d bytes to '%s'\n", len(contents), filename)
c := strings.Split(pathname, "/")
if len(c) > 1 {
fileLock.Lock()
os.MkdirAll(strings.Join(c[0:len(c)-1], "/"), 0777)
fileLock.Unlock()
}
fileLock.Lock()
defer fileLock.Unlock()
flags := os.O_CREATE | os.O_WRONLY
if append {
flags = flags | os.O_APPEND
}
f, err := os.OpenFile(pathname, flags, 0644)
if err == nil {
_, err = f.Write(contents)
f.Close()
}
if err != nil {
fmt.Printf(" upload err %s: %s\n", filename, err)
}
}
// Delete a file
func deleteFile(filename string) (contents []byte) {
pathname, bad := cleanFilename(filename)
if bad {
return
}
fmt.Printf("FILE DELETE %s\n", filename)
var err error
fileLock.Lock()
err = os.Remove(pathname)
fileLock.Unlock()
if err != nil {
fmt.Printf(" err: %s\n", err)
contents = []byte(fmt.Sprintf("%s", err))
}
return
}
// Get a file
func getFile(filename string, ctype string) (contents []byte, exists bool) {
pathname, bad := cleanFilename(filename)
if bad {
return
}
var err error
fileLock.Lock()
contents, err = os.ReadFile(pathname)
fileLock.Unlock()
if err != nil {
contents = []byte(fmt.Sprintf("%s", err))
} else {
exists = true
fmt.Printf("FILE GET %s (%s)\n", filename, ctype)
}
return
}