diff --git a/config.go b/config.go new file mode 100644 index 0000000..1edf516 --- /dev/null +++ b/config.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "os" + "strconv" + "strings" +) + +type Config struct { + UploadDir string + MaxPasteBytes int64 + MaxFileBytes int64 + + DatabasePath string +} + +func loadConfig() (Config, error) { + uploadDir := envOrDefault("MINIBIN_UPLOAD_DIR", "uploads") + pasteSizeSetting := envOrDefault("MINIBIN_MAX_PASTE_KIB", "1024") + maxPasteKiB, err := strconv.ParseInt(pasteSizeSetting, 10, 64) + if err != nil { + return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_PASTE_KIB: %w", err) + } + if maxPasteKiB <= 0 { + return Config{}, fmt.Errorf("MINIBIN_MAX_PASTE_KIB must be greater than 0") + } + + fileSizeSetting := envOrDefault("MINIBIN_MAX_FILE_KIB", "1024") + maxFileKiB, err := strconv.ParseInt(fileSizeSetting, 10, 64) + if err != nil { + return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_FILE_KIB: %w", err) + } + if maxFileKiB <= 0 { + return Config{}, fmt.Errorf("MINIBIN_MAX_FILE_KIB must be greater than 0") + } + + databasePath := envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite") + + return Config{ + UploadDir: uploadDir, + MaxPasteBytes: maxPasteKiB * 1024, + MaxFileBytes: maxFileKiB * 1024, + + DatabasePath: databasePath, + }, nil +} + +func envOrDefault(key, fallback string) string { + value := strings.TrimSpace(os.Getenv(key)) + if value == "" { + return fallback + } + return value +} diff --git a/database.go b/database.go new file mode 100644 index 0000000..62f61db --- /dev/null +++ b/database.go @@ -0,0 +1,58 @@ +package main + +import ( + "errors" + "fmt" + + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +type ContentType uint8 + +const ( + ContentFile ContentType = iota + ContentPaste +) + +type Upload struct { + ID string `gorm:"column:id;primaryKey" json:"id"` + Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"` + Filename string `gorm:"column:filename;not null" json:"-"` + MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"` + Size int64 `gorm:"column:size;not null" json:"size"` + SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"` + CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"` + ExpiresAt *int64 `gorm:"column:expires_at;index" json:"expires_at"` // null means no expiration + LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"` +} + +func initDatabase(path string) (*gorm.DB, error) { + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{}) + if err != nil { + return nil, fmt.Errorf("open database: %w", err) + } + + sqlDB, err := db.DB() + if err != nil { + return nil, fmt.Errorf("get database handle: %w", err) + } + + sqlDB.SetMaxOpenConns(1) + sqlDB.SetMaxIdleConns(1) + if err := db.Exec("PRAGMA journal_mode = WAL").Error; err != nil { + walModeErr := fmt.Errorf("enable database WAL: %w", err) + return nil, errors.Join(walModeErr, sqlDB.Close()) + } + + if err := db.AutoMigrate(&Upload{}); err != nil { + migrationErr := fmt.Errorf("migrate database: %w", err) + return nil, errors.Join(migrationErr, sqlDB.Close()) + } + + return db, nil +} + +func insertUpload(db *gorm.DB, upload *Upload) error { + return db.Create(upload).Error +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..d361e71 --- /dev/null +++ b/go.mod @@ -0,0 +1,24 @@ +module git.whoswhip.dev/whoswhip/minibin + +go 1.27.1 + +require ( + github.com/glebarez/sqlite v1.11.0 + gorm.io/gorm v1.31.2 +) + +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/glebarez/go-sqlite v1.21.2 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/mattn/go-isatty v0.0.17 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.41.0 // indirect + modernc.org/libc v1.22.5 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/sqlite v1.23.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..25423d8 --- /dev/null +++ b/go.sum @@ -0,0 +1,38 @@ +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo= +github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k= +github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw= +github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= +gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= +modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM= +modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= diff --git a/handlers.go b/handlers.go new file mode 100644 index 0000000..22b2286 --- /dev/null +++ b/handlers.go @@ -0,0 +1,98 @@ +package main + +import ( + "fmt" + "io" + "log" + "mime" + "net/http" + + "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 upload(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 { + // not sure whether this should be a bad request or server error + http.Error(w, "failed to find or parse Content-Type", http.StatusInternalServerError) + return + } + + var input uploadInput + switch mediaType { + case "multipart/form-data": // file uploads + 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) + 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 { + log.Printf("detect file mime type: %v", 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 + input = uploadInput{ + Reader: r.Body, + Filename: "paste.txt", + MimeType: "text/plain; charset=utf-8", + Type: ContentPaste, + } + default: + http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType) + return + } + // todo: generate id -> derive storage path -> hash + save to disk -> insert to database + } +} + +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 +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..35bf8c6 --- /dev/null +++ b/main.go @@ -0,0 +1,56 @@ +package main + +import ( + "html/template" + "log" + "net/http" + "os" +) + +func main() { + config, err := loadConfig() + if err != nil { + log.Fatal(err) + } + + log.Println("config loaded") + + _, err = initDatabase(config.DatabasePath) + + if err != nil { + log.Fatal(err) + } + + log.Println("database initialized") + + if err := os.MkdirAll(config.UploadDir, 0700); err != nil { + log.Fatal(err) + } + + pages, err := template.ParseFiles("templates/home.html", "templates/paste.html") + if err != nil { + log.Fatal(err) + } + + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { + data := HomePageData{ + Title: "minibin", + Description: "simple file and paste hosting", + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + + if err := pages.ExecuteTemplate(w, "home.html", data); err != nil { + log.Println("render home page:", err) + } + }) + mux.HandleFunc("GET /health", health) + + log.Println("listening on http://localhost:8080") + + err = http.ListenAndServe("localhost:8080", mux) + if err != nil { + log.Fatal(err) + } +} diff --git a/storage.go b/storage.go new file mode 100644 index 0000000..ea0a2c4 --- /dev/null +++ b/storage.go @@ -0,0 +1,49 @@ +package main + +import ( + "crypto/rand" + "math/big" + "path/filepath" + "strings" +) + +const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + +// generates a secure random id, +// length must be either 10 or 16 +func generateId(length int) string { + if length != 10 && length != 16 { + panic("length must be 10 or 16") + } + bytes := make([]byte, length) + max := big.NewInt(int64(len(alphabet))) + + for i := range bytes { + rr, err := rand.Int(rand.Reader, max) + if err != nil { + panic(err) + } + bytes[i] = alphabet[rr.Int64()] + } + + return string(bytes) +} + +func validPasteId(id string) bool { + if len(id) != 10 && len(id) != 16 { + return false + } + + // check if it uses our alphabet + for _, r := range id { + if !strings.ContainsRune(alphabet, r) { + return false + } + } + + return true +} + +func getStoragePath(uploadDir, id string) string { + return filepath.Join(uploadDir, id[:2], id[2:4], id) +} diff --git a/templates/home.html b/templates/home.html new file mode 100644 index 0000000..2502d36 --- /dev/null +++ b/templates/home.html @@ -0,0 +1,22 @@ + + + + + + {{.Title}} + + +

{{.Title}}

+

{{.Description}}

+
+ + + +
+ +
+ + +
+ +