diff --git a/handlers.go b/handlers.go index 9c1bd25..3dc4757 100644 --- a/handlers.go +++ b/handlers.go @@ -3,6 +3,7 @@ package main import ( "crypto/sha256" "encoding/json" + "errors" "fmt" "io" "log" @@ -10,6 +11,7 @@ import ( "net/http" "os" "path/filepath" + "strings" "time" "unicode/utf8" @@ -57,19 +59,21 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { var input uploadInput switch mediaType { case "multipart/form-data": // file uploads + r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxFileBytes) file, header, err := r.FormFile("file") if r.MultipartForm != nil { defer r.MultipartForm.RemoveAll() } if err != nil { - http.Error(w, "invalid file or upload too large", http.StatusBadRequest) + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + return + } + + http.Error(w, "invalid file", http.StatusBadRequest) return } defer file.Close() - if header.Size > cfg.MaxFileBytes { - http.Error(w, "invalid file size, file too large", http.StatusRequestEntityTooLarge) - return - } input.MIMEType, err = detectMimeType(file) if err != nil { @@ -81,8 +85,38 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { input.Filename = header.Filename input.Type = ContentFile case "text/plain", "application/x-www-form-urlencoded": // paste uploads + r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes) + var content string + if mediaType == "application/x-www-form-urlencoded" { + err = r.ParseForm() + if err == nil { + content = r.PostForm.Get("content") + } + } else { + var body []byte + body, err = io.ReadAll(r.Body) + if err == nil { + content = string(body) + } + } + + if err != nil { + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + return + } + + http.Error(w, "invalid paste upload", http.StatusBadRequest) + return + } + + if strings.TrimSpace(content) == "" { + http.Error(w, "paste cannot be empty", http.StatusBadRequest) + return + } + input = uploadInput{ - Reader: r.Body, + Reader: strings.NewReader(content), Filename: "paste.txt", MIMEType: "text/plain; charset=utf-8", Type: ContentPaste, @@ -120,6 +154,10 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc { hasher := sha256.New() size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) if err != nil { + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + return + } log.Println("write file:", err) http.Error(w, "faield to write upload", http.StatusInternalServerError) return