463 lines
12 KiB
Go
463 lines
12 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"log"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"github.com/gabriel-vasile/mimetype"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type HomePageData struct {
|
|
Expiries []Expiry
|
|
Qt string
|
|
PastePlaceholder 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
|
|
}
|
|
type UploadResponse struct {
|
|
Upload
|
|
SHA256 string `json:"sha256"`
|
|
DeleteToken string `json:"deleteToken"`
|
|
FileExtension string `json:"extension"` // useful for things like sharex to append the extension
|
|
}
|
|
|
|
func render(pages *template.Template, w http.ResponseWriter, name string, data any) {
|
|
w.Header().Set("Conten-Type", "text/html; charset=utf-8")
|
|
if err := pages.ExecuteTemplate(w, name, data); err != nil {
|
|
log.Printf("render %s: %v", name, err)
|
|
}
|
|
}
|
|
|
|
func staticPage(pages *template.Template, name string) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
render(pages, w, name, nil)
|
|
}
|
|
}
|
|
|
|
func uploadHandler(db *gorm.DB, cfg Config, pages *template.Template) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost && r.Method != http.MethodPut {
|
|
w.Header().Set("Allow", "POST,PUT")
|
|
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))
|
|
|
|
var err error
|
|
mediaType := "text/plain"
|
|
if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" {
|
|
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
|
|
}
|
|
}
|
|
|
|
returnType := strings.TrimSpace(r.URL.Query().Get("return"))
|
|
if returnType == "" {
|
|
returnType = "json"
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
expLabel := r.URL.Query().Get("expiry")
|
|
if expLabel == "" {
|
|
expLabel = r.PostForm.Get("expiry") // html form request
|
|
}
|
|
if expLabel == "" {
|
|
expLabel = cfg.Expiries[0].Label
|
|
}
|
|
|
|
selected, found := findExpiry(cfg.Expiries, expLabel)
|
|
if !found {
|
|
http.Error(w, "invalid expiry", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
idLength := 16
|
|
if r.URL.Query().Get("idlength") == "short" {
|
|
idLength = 10
|
|
}
|
|
if r.PostForm.Get("idlength") == "short" {
|
|
idLength = 10
|
|
}
|
|
|
|
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()
|
|
expires, err := selected.ExpiresFrom(time.Now().UTC())
|
|
if err != nil {
|
|
log.Println("calc expiry:", err) // im just using slang
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// the following code prevents a panic, trying to convert a null pointer to unix perhaps doesnt work
|
|
var expiresAt *int64
|
|
if expires != nil {
|
|
timestamp := expires.Unix()
|
|
expiresAt = ×tamp
|
|
}
|
|
|
|
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,
|
|
ExpiresAt: expiresAt,
|
|
LastAccessedAt: createdAt,
|
|
DeleteToken: rand.Text(),
|
|
}
|
|
err = insertUpload(db, &upload)
|
|
if err != nil {
|
|
log.Println("save upload:", err)
|
|
http.Error(w, "failed to save upload", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
saved = true
|
|
|
|
response := UploadResponse{
|
|
Upload: upload,
|
|
SHA256: hex.EncodeToString(upload.SHA256),
|
|
DeleteToken: upload.DeleteToken,
|
|
FileExtension: filepath.Ext(upload.Filename),
|
|
}
|
|
|
|
switch returnType {
|
|
// html & maybe xml? cant think of other return types
|
|
case "html":
|
|
render(pages, w, "upload.html", response)
|
|
case "redirect":
|
|
http.Redirect(w, r, "/"+id, http.StatusSeeOther)
|
|
default:
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
if err := json.NewEncoder(w).Encode(response); err != nil {
|
|
log.Println("failed to encode response:", err)
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut
|
|
|
|
if !validPasteId(id) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
path := getStoragePath(cfg.UploadDir, id)
|
|
upload, err := getUploadById(db.WithContext(r.Context()), id)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
log.Println("get upload:", err)
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
now := time.Now().UTC().Unix()
|
|
if upload.ExpiresAt != nil && now >= *upload.ExpiresAt {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
log.Println("get upload file:", err)
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
defer file.Close()
|
|
tracker.Record(id)
|
|
|
|
ttl := 600 // 10 minutes
|
|
if upload.ExpiresAt != nil {
|
|
ttl = int(*upload.ExpiresAt - now)
|
|
}
|
|
mimetype := upload.MIMEType
|
|
if cfg.NormalizeMIMETypes {
|
|
mimetype = normalizeMIMEType(mimetype)
|
|
}
|
|
|
|
if mimetype == "application/octet-stream" {
|
|
w.Header().Set(
|
|
"Content-Disposition",
|
|
fmt.Sprintf("attachment; filename=\"%s%s\"", upload.ID, filepath.Ext(upload.Filename)),
|
|
)
|
|
}
|
|
|
|
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d, must-revalidate", ttl))
|
|
w.Header().Set("ETag", "\""+hex.EncodeToString(upload.SHA256)+"\"")
|
|
w.Header().Set("Content-Security-Policy", "sandbox")
|
|
w.Header().Set("Content-Type", mimetype)
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
http.ServeContent(w, r, upload.Filename, time.Unix(upload.CreatedAt, 0), file)
|
|
}
|
|
}
|
|
|
|
func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
if !validPasteId(id) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
redirect := r.URL.Query().Get("redirect") == "true"
|
|
|
|
var token string
|
|
switch r.Method {
|
|
case http.MethodDelete:
|
|
bearer := r.Header.Get("Authorization")
|
|
var scheme string
|
|
var found bool
|
|
scheme, token, found = strings.Cut(bearer, " ")
|
|
if !found || scheme != "Bearer" {
|
|
http.Error(w, "invalid token", http.StatusBadRequest)
|
|
return
|
|
}
|
|
case http.MethodPost:
|
|
token = r.PostFormValue("delete_token")
|
|
}
|
|
|
|
path := getStoragePath(cfg.UploadDir, id)
|
|
upload, err := getUploadById(db.WithContext(r.Context()), id)
|
|
if err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
log.Println("get upload:", err)
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 {
|
|
http.Error(w, "invalid token", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// continue to delete from database IF the file doesnt exist on disk
|
|
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
|
|
log.Println("remove upload file:", err)
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
log.Println("remove upload file:", err)
|
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if redirect {
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
func detectMimeType(file io.ReadSeeker) (string, error) {
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return "", fmt.Errorf("rewind file: %w", err)
|
|
}
|
|
|
|
mtype, dtcErr := mimetype.DetectReader(file)
|
|
|
|
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
|
return "", fmt.Errorf("rewind file: %w", err)
|
|
}
|
|
|
|
if dtcErr != nil {
|
|
return "", fmt.Errorf("detect MIME type: %w", dtcErr)
|
|
}
|
|
|
|
return mtype.String(), nil
|
|
}
|
|
|
|
func normalizeMIMEType(contentType string) string {
|
|
const plaintext = "text/plain; charset=utf-8"
|
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
|
if err != nil {
|
|
return plaintext
|
|
}
|
|
if strings.HasSuffix(mediaType, "+xml") {
|
|
return plaintext
|
|
}
|
|
switch mediaType {
|
|
case "text/html", "text/javascript", "application/javascript",
|
|
"application/ecmascript", "text/ecmascript", "application/xml",
|
|
"text/xml", "text/xsl",
|
|
"text/css", "application/wasm":
|
|
return plaintext
|
|
case "application/pdf":
|
|
return "application/octet-stream"
|
|
default:
|
|
return contentType
|
|
}
|
|
}
|