216 lines
5.6 KiB
Go
216 lines
5.6 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type HomePageData struct {
|
|
Title string
|
|
Description string
|
|
}
|
|
|
|
func health(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
fmt.Fprintln(w, "OK")
|
|
}
|
|
|
|
type uploadInput struct {
|
|
Reader io.Reader
|
|
Filename string
|
|
MIMEType string
|
|
Type ContentType
|
|
}
|
|
|
|
func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "invalid method", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
// use the largest of the sizes, and then do another size check per type down the line
|
|
r.Body = http.MaxBytesReader(w, r.Body, max(cfg.MaxFileBytes, cfg.MaxPasteBytes))
|
|
|
|
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
if err != nil {
|
|
http.Error(w, "failed to find or parse Content-Type", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
idLength := 16
|
|
if r.URL.Query().Get("idlength") == "short" {
|
|
idLength = 10
|
|
}
|
|
|
|
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 {
|
|
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()
|
|
|
|
input.MIMEType, err = detectMimeType(file)
|
|
if err != nil {
|
|
log.Println("detect file mime type:", err)
|
|
http.Error(w, "failed to detect mime type", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
input.Reader = file
|
|
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: strings.NewReader(content),
|
|
Filename: "paste.txt",
|
|
MIMEType: "text/plain; charset=utf-8",
|
|
Type: ContentPaste,
|
|
}
|
|
default:
|
|
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType)
|
|
return
|
|
}
|
|
|
|
id := generateId(idLength)
|
|
path := getStoragePath(cfg.UploadDir, id)
|
|
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
|
log.Println("create directories:", err)
|
|
http.Error(w, "failed to save upload", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
|
if err != nil {
|
|
log.Println("create file:", err)
|
|
http.Error(w, "faield to save upload", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
saved := false
|
|
defer func() {
|
|
dest.Close()
|
|
if !saved {
|
|
if err := os.Remove(path); err != nil {
|
|
log.Printf("remove incomplete upload %s: %v", id, err)
|
|
}
|
|
}
|
|
}()
|
|
|
|
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
|
|
}
|
|
if err := dest.Close(); err != nil {
|
|
log.Println("close file:", err)
|
|
http.Error(w, "failed to save upload", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
createdAt := time.Now().UTC().Unix()
|
|
if utf8.RuneCountInString(input.Filename) > 255 {
|
|
name := []rune(input.Filename)
|
|
ext := []rune(filepath.Ext(input.Filename))
|
|
if len(ext) >= 255 {
|
|
ext = nil
|
|
}
|
|
input.Filename = string(name[:255-len(ext)]) + string(ext)
|
|
}
|
|
|
|
upload := Upload{
|
|
ID: id,
|
|
Type: input.Type,
|
|
Filename: input.Filename,
|
|
MIMEType: input.MIMEType,
|
|
Size: size,
|
|
SHA256: hasher.Sum(nil),
|
|
CreatedAt: createdAt,
|
|
LastAccessedAt: createdAt,
|
|
}
|
|
err = insertUpload(db, &upload)
|
|
if err != nil {
|
|
log.Println("save upload:", err)
|
|
http.Error(w, "failed to save upload", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
saved = true
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
if err := json.NewEncoder(w).Encode(upload); err != nil {
|
|
log.Println("failed to encode response:", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func detectMimeType(file io.ReadSeeker) (string, error) {
|
|
var buffer [512]byte
|
|
n, readErr := io.ReadFull(file, buffer[:])
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return "", fmt.Errorf("rewind file: %w", err)
|
|
}
|
|
if readErr != nil && readErr != io.EOF && readErr != io.ErrUnexpectedEOF {
|
|
return "", fmt.Errorf("read file header: %w", readErr)
|
|
}
|
|
return http.DetectContentType(buffer[:n]), nil
|
|
}
|