-
Notifications
You must be signed in to change notification settings - Fork 191
/
upload.go
413 lines (351 loc) · 10.9 KB
/
upload.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/andreimarcu/linx-server/auth/apikeys"
"github.com/andreimarcu/linx-server/backends"
"github.com/andreimarcu/linx-server/expiry"
"github.com/dchest/uniuri"
"github.com/gabriel-vasile/mimetype"
"github.com/zenazn/goji/web"
)
var FileTooLargeError = errors.New("File too large.")
var fileBlacklist = map[string]bool{
"favicon.ico": true,
"index.htm": true,
"index.html": true,
"index.php": true,
"robots.txt": true,
"crossdomain.xml": true,
}
// Describes metadata directly from the user request
type UploadRequest struct {
src io.Reader
size int64
filename string
expiry time.Duration // Seconds until expiry, 0 = never
deleteKey string // Empty string if not defined
randomBarename bool
accessKey string // Empty string if not defined
}
// Metadata associated with a file as it would actually be stored
type Upload struct {
Filename string // Final filename on disk
Metadata backends.Metadata
}
func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
if !strictReferrerCheck(r, getSiteURL(r), []string{"Linx-Delete-Key", "Linx-Expiry", "Linx-Randomize", "X-Requested-With"}) {
badRequestHandler(c, w, r, RespAUTO, "")
return
}
upReq := UploadRequest{}
uploadHeaderProcess(r, &upReq)
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data") {
file, headers, err := r.FormFile("file")
if err != nil {
oopsHandler(c, w, r, RespHTML, "Could not upload file.")
return
}
defer file.Close()
upReq.src = file
upReq.size = headers.Size
upReq.filename = headers.Filename
} else {
if r.PostFormValue("content") == "" {
badRequestHandler(c, w, r, RespAUTO, "Empty file")
return
}
extension := r.PostFormValue("extension")
if extension == "" {
extension = "txt"
}
content := r.PostFormValue("content")
upReq.src = strings.NewReader(content)
upReq.size = int64(len(content))
upReq.filename = r.PostFormValue("filename") + "." + extension
}
upReq.expiry = parseExpiry(r.PostFormValue("expires"))
upReq.accessKey = r.PostFormValue(accessKeyParamName)
if r.PostFormValue("randomize") == "true" {
upReq.randomBarename = true
}
upload, err := processUpload(upReq)
if strings.EqualFold("application/json", r.Header.Get("Accept")) {
if err == FileTooLargeError || err == backends.FileEmptyError {
badRequestHandler(c, w, r, RespJSON, err.Error())
return
} else if err != nil {
oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
return
}
js := generateJSONresponse(upload, r)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(js)
} else {
if err == FileTooLargeError || err == backends.FileEmptyError {
badRequestHandler(c, w, r, RespHTML, err.Error())
return
} else if err != nil {
oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
return
}
http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
}
}
func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
upReq := UploadRequest{}
uploadHeaderProcess(r, &upReq)
defer r.Body.Close()
upReq.filename = c.URLParams["name"]
upReq.src = http.MaxBytesReader(w, r.Body, Config.maxSize)
upload, err := processUpload(upReq)
if strings.EqualFold("application/json", r.Header.Get("Accept")) {
if err == FileTooLargeError || err == backends.FileEmptyError {
badRequestHandler(c, w, r, RespJSON, err.Error())
return
} else if err != nil {
oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
return
}
js := generateJSONresponse(upload, r)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(js)
} else {
if err == FileTooLargeError || err == backends.FileEmptyError {
badRequestHandler(c, w, r, RespPLAIN, err.Error())
return
} else if err != nil {
oopsHandler(c, w, r, RespPLAIN, "Could not upload file: "+err.Error())
return
}
fmt.Fprintf(w, "%s\n", getSiteURL(r)+upload.Filename)
}
}
func uploadRemote(c web.C, w http.ResponseWriter, r *http.Request) {
if Config.remoteAuthFile != "" {
key := r.FormValue("key")
if key == "" && Config.basicAuth {
_, password, ok := r.BasicAuth()
if ok {
key = password
}
}
result, err := apikeys.CheckAuth(remoteAuthKeys, key)
if err != nil || !result {
if Config.basicAuth {
rs := ""
if Config.siteName != "" {
rs = fmt.Sprintf(` realm="%s"`, Config.siteName)
}
w.Header().Set("WWW-Authenticate", `Basic`+rs)
}
unauthorizedHandler(c, w, r)
return
}
}
if r.FormValue("url") == "" {
http.Redirect(w, r, Config.sitePath, 303)
return
}
upReq := UploadRequest{}
grabUrl, _ := url.Parse(r.FormValue("url"))
directURL := r.FormValue("direct_url") == "yes"
resp, err := http.Get(grabUrl.String())
if err != nil {
oopsHandler(c, w, r, RespAUTO, "Could not retrieve URL")
return
}
upReq.filename = filepath.Base(grabUrl.Path)
upReq.src = http.MaxBytesReader(w, resp.Body, Config.maxSize)
upReq.deleteKey = r.FormValue("deletekey")
upReq.accessKey = r.FormValue(accessKeyParamName)
upReq.randomBarename = r.FormValue("randomize") == "yes"
upReq.expiry = parseExpiry(r.FormValue("expiry"))
upload, err := processUpload(upReq)
if strings.EqualFold("application/json", r.Header.Get("Accept")) {
if err != nil {
oopsHandler(c, w, r, RespJSON, "Could not upload file: "+err.Error())
return
}
js := generateJSONresponse(upload, r)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write(js)
} else {
if err != nil {
oopsHandler(c, w, r, RespHTML, "Could not upload file: "+err.Error())
return
}
if directURL {
http.Redirect(w, r, Config.sitePath+Config.selifPath+upload.Filename, 303)
} else {
http.Redirect(w, r, Config.sitePath+upload.Filename, 303)
}
}
}
func uploadHeaderProcess(r *http.Request, upReq *UploadRequest) {
if r.Header.Get("Linx-Randomize") == "yes" {
upReq.randomBarename = true
}
upReq.deleteKey = r.Header.Get("Linx-Delete-Key")
upReq.accessKey = r.Header.Get(accessKeyHeaderName)
// Get seconds until expiry. Non-integer responses never expire.
expStr := r.Header.Get("Linx-Expiry")
upReq.expiry = parseExpiry(expStr)
}
func processUpload(upReq UploadRequest) (upload Upload, err error) {
if upReq.size > Config.maxSize {
return upload, FileTooLargeError
}
// Determine the appropriate filename
barename, extension := barePlusExt(upReq.filename)
randomize := false
// Randomize the "barename" (filename without extension) if needed
if upReq.randomBarename || len(barename) == 0 {
barename = generateBarename()
randomize = true
}
var header []byte
if len(extension) == 0 {
// Pull the first 512 bytes off for use in MIME detection
header = make([]byte, 512)
n, _ := upReq.src.Read(header)
if n == 0 {
return upload, backends.FileEmptyError
}
header = header[:n]
// Determine the type of file from header
kind := mimetype.Detect(header)
if len(kind.Extension()) < 2 {
extension = "file"
} else {
extension = kind.Extension()[1:] // remove leading "."
}
}
upload.Filename = strings.Join([]string{barename, extension}, ".")
upload.Filename = strings.Replace(upload.Filename, " ", "", -1)
fileexists, _ := storageBackend.Exists(upload.Filename)
// Check if the delete key matches, in which case overwrite
if fileexists {
metad, merr := storageBackend.Head(upload.Filename)
if merr == nil {
if upReq.deleteKey == metad.DeleteKey {
fileexists = false
} else if Config.forceRandomFilename == true {
// the file exists
// the delete key doesn't match
// force random filenames is enabled
randomize = true
}
}
} else if Config.forceRandomFilename == true {
// the file doesn't exist
// force random filenames is enabled
randomize = true
// set fileexists to true to generate a new barename
fileexists = true
}
for fileexists {
if randomize {
barename = generateBarename()
} else {
counter, err := strconv.Atoi(string(barename[len(barename)-1]))
if err != nil {
barename = barename + "1"
} else {
barename = barename[:len(barename)-1] + strconv.Itoa(counter+1)
}
}
upload.Filename = strings.Join([]string{barename, extension}, ".")
fileexists, err = storageBackend.Exists(upload.Filename)
}
if fileBlacklist[strings.ToLower(upload.Filename)] {
return upload, errors.New("Prohibited filename")
}
// Get the rest of the metadata needed for storage
var fileExpiry time.Time
if upReq.expiry == 0 {
fileExpiry = expiry.NeverExpire
} else {
fileExpiry = time.Now().Add(upReq.expiry)
}
if upReq.deleteKey == "" {
upReq.deleteKey = uniuri.NewLen(30)
}
upload.Metadata, err = storageBackend.Put(upload.Filename, io.MultiReader(bytes.NewReader(header), upReq.src), fileExpiry, upReq.deleteKey, upReq.accessKey)
if err != nil {
return upload, err
}
return
}
func generateBarename() string {
return uniuri.NewLenChars(8, []byte("abcdefghijklmnopqrstuvwxyz0123456789"))
}
func generateJSONresponse(upload Upload, r *http.Request) []byte {
js, _ := json.Marshal(map[string]string{
"url": getSiteURL(r) + upload.Filename,
"direct_url": getSiteURL(r) + Config.selifPath + upload.Filename,
"filename": upload.Filename,
"delete_key": upload.Metadata.DeleteKey,
"access_key": upload.Metadata.AccessKey,
"expiry": strconv.FormatInt(upload.Metadata.Expiry.Unix(), 10),
"size": strconv.FormatInt(upload.Metadata.Size, 10),
"mimetype": upload.Metadata.Mimetype,
"sha256sum": upload.Metadata.Sha256sum,
})
return js
}
var bareRe = regexp.MustCompile(`[^A-Za-z0-9\-]`)
var extRe = regexp.MustCompile(`[^A-Za-z0-9\-\.]`)
var compressedExts = map[string]bool{
".bz2": true,
".gz": true,
".xz": true,
}
var archiveExts = map[string]bool{
".tar": true,
}
func barePlusExt(filename string) (barename, extension string) {
filename = strings.TrimSpace(filename)
filename = strings.ToLower(filename)
extension = path.Ext(filename)
barename = filename[:len(filename)-len(extension)]
if compressedExts[extension] {
ext2 := path.Ext(barename)
if archiveExts[ext2] {
barename = barename[:len(barename)-len(ext2)]
extension = ext2 + extension
}
}
extension = extRe.ReplaceAllString(extension, "")
barename = bareRe.ReplaceAllString(barename, "")
extension = strings.Trim(extension, "-.")
barename = strings.Trim(barename, "-")
return
}
func parseExpiry(expStr string) time.Duration {
if expStr == "" {
return time.Duration(Config.maxExpiry) * time.Second
} else {
fileExpiry, err := strconv.ParseUint(expStr, 10, 64)
if err != nil {
return time.Duration(Config.maxExpiry) * time.Second
} else {
if Config.maxExpiry > 0 && (fileExpiry > Config.maxExpiry || fileExpiry == 0) {
fileExpiry = Config.maxExpiry
}
return time.Duration(fileExpiry) * time.Second
}
}
}