max total storage usage implemented!
code may be a bit messy but.... also implemented a storage usage stat (that can be toggled in .env) that shows on the home page, you can also enable the total limit to show as well eventually i need to implement clearing old unfinished uploads both on startup, admin actions, and cleaning up on upload failure
This commit is contained in:
+14
-2
@@ -8,6 +8,9 @@ MINIBIN_ADDR=localhost:8080
|
|||||||
# max size uploadable in KiB, 97657 is around 100 MB
|
# max size uploadable in KiB, 97657 is around 100 MB
|
||||||
MINIBIN_MAX_PASTE_KIB=97657
|
MINIBIN_MAX_PASTE_KIB=97657
|
||||||
MINIBIN_MAX_FILE_KIB=97657
|
MINIBIN_MAX_FILE_KIB=97657
|
||||||
|
# the max amount of storage minibin will use for uploads
|
||||||
|
# 0 means no limit
|
||||||
|
MINIBIN_MAX_STORAGE_USAGE_KIB=0
|
||||||
# allowed expiries, shown in the order they are written
|
# allowed expiries, shown in the order they are written
|
||||||
# syntax: h(our),d(ay),w(eek),mo(nth),y(ear), 0 = indefinite/no expiry
|
# syntax: h(our),d(ay),w(eek),mo(nth),y(ear), 0 = indefinite/no expiry
|
||||||
MINIBIN_EXPIRIES=1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0
|
MINIBIN_EXPIRIES=1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0
|
||||||
@@ -27,7 +30,7 @@ MINIBIN_POW_DIFFICULTY=10
|
|||||||
# options show in the order they are written
|
# options show in the order they are written
|
||||||
# leading spaces WILL be included, so make sure you dont include them
|
# leading spaces WILL be included, so make sure you dont include them
|
||||||
MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud"
|
MINIBIN_REPORT_OPTIONS="Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud"
|
||||||
# chose where minibin gets the client's ip from
|
# where minibin gets the client's ip from
|
||||||
# available options: remote, cloudflare, xff
|
# available options: remote, cloudflare, xff
|
||||||
# remote: the ip connecting to minibin
|
# remote: the ip connecting to minibin
|
||||||
# cloudflare: uses the CF-Connecting-IP header
|
# cloudflare: uses the CF-Connecting-IP header
|
||||||
@@ -37,5 +40,14 @@ MINIBIN_IP_ADDRESS_SOURCE=remote
|
|||||||
# cloudflares: https://cloudflare.com/ips/
|
# cloudflares: https://cloudflare.com/ips/
|
||||||
MINIBIN_TRUSTED_PROXIES=127.0.0.1/32
|
MINIBIN_TRUSTED_PROXIES=127.0.0.1/32
|
||||||
# comma separated list of asn numbers
|
# comma separated list of asn numbers
|
||||||
# any asn in this list will be completely banned from all routes
|
# any asn in this list will be completely banned from all routes (except for static assets and qts)
|
||||||
MINIBIN_BANNED_ASNS=""
|
MINIBIN_BANNED_ASNS=""
|
||||||
|
|
||||||
|
## Public Stats Related Environment Variables
|
||||||
|
# whether or not to display storage usage on the homepage
|
||||||
|
# will also return it on uploads if enabled
|
||||||
|
MINIBIN_STATS_DISPLAY_STORAGE_USAGE=false
|
||||||
|
# whether or not to display the max amount of storage minibin can use
|
||||||
|
# on the home and returning it on uploads
|
||||||
|
# this can NOT be enabled if MINIBIN_STATS_DISPLAY_STORAGE_USAGE isn't
|
||||||
|
MINIBIN_STATS_DISPLAY_STORAGE_LIMIT=flase
|
||||||
|
|||||||
+33
-1
@@ -5,6 +5,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.whoswhip.dev/whoswhip/minibin/internal/config"
|
"git.whoswhip.dev/whoswhip/minibin/internal/config"
|
||||||
@@ -42,11 +43,23 @@ func main() {
|
|||||||
|
|
||||||
log.Println("database initialized")
|
log.Println("database initialized")
|
||||||
|
|
||||||
|
err = database.EnsureQuotaUsage(db)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
initialUsage, err := database.GetQuotaUsage(db)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
usage := new(atomic.Int64)
|
||||||
|
usage.Store(initialUsage)
|
||||||
|
|
||||||
if err := os.MkdirAll(config.UploadDir, 0700); err != nil {
|
if err := os.MkdirAll(config.UploadDir, 0700); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pages, err := pages.LoadPages()
|
pages, err := pages.LoadPages(usage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -56,6 +69,25 @@ func main() {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
go tracker.Run(ctx, db)
|
go tracker.Run(ctx, db)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
usedBytes, err := database.GetQuotaUsage(db.WithContext(ctx))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("refresh quota usage: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
usage.Store(usedBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
challengeStore := reports.NewChallengeStore(3 * time.Minute)
|
challengeStore := reports.NewChallengeStore(3 * time.Minute)
|
||||||
|
|
||||||
log.Println("listening on", config.Addr)
|
log.Println("listening on", config.Addr)
|
||||||
|
|||||||
+42
-21
@@ -2,7 +2,6 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -16,12 +15,16 @@ type Config struct {
|
|||||||
UploadDir string
|
UploadDir string
|
||||||
MaxPasteBytes int64
|
MaxPasteBytes int64
|
||||||
MaxFileBytes int64
|
MaxFileBytes int64
|
||||||
|
MaxStorageUsage int64
|
||||||
Expiries []Expiry
|
Expiries []Expiry
|
||||||
NormalizeMIMETypes bool
|
NormalizeMIMETypes bool
|
||||||
BannedMIMETypes []string
|
BannedMIMETypes []string
|
||||||
PoWDifficulty int
|
PoWDifficulty int
|
||||||
ReportOptions []string
|
ReportOptions []string
|
||||||
|
|
||||||
|
DisplayStorageUsage bool
|
||||||
|
DisplayStorageLimit bool
|
||||||
|
|
||||||
DatabasePath string
|
DatabasePath string
|
||||||
// public host like "https://bin.zip", NOT the address minbin listens on
|
// public host like "https://bin.zip", NOT the address minbin listens on
|
||||||
Host string
|
Host string
|
||||||
@@ -34,25 +37,21 @@ type Config struct {
|
|||||||
func LoadConfig() (Config, error) {
|
func LoadConfig() (Config, error) {
|
||||||
err := godotenv.Load()
|
err := godotenv.Load()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error loading .env file")
|
return Config{}, fmt.Errorf("failed to load .env: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pasteSizeSetting := envOrDefault("MINIBIN_MAX_PASTE_KIB", "1024")
|
maxPasteKiB, err := envKibAsBytes("MINIBIN_MAX_PASTE_KIB", "1024", 1)
|
||||||
maxPasteKiB, err := strconv.ParseInt(pasteSizeSetting, 10, 64)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_PASTE_KIB: %w", err)
|
return Config{}, 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 := envKibAsBytes("MINIBIN_MAX_FILE_KIB", "1024", 1)
|
||||||
maxFileKiB, err := strconv.ParseInt(fileSizeSetting, 10, 64)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_FILE_KIB: %w", err)
|
return Config{}, err
|
||||||
}
|
}
|
||||||
if maxFileKiB <= 0 {
|
maxStorageUsageKiB, err := envKibAsBytes("MINIBIN_MAX_STORAGE_USAGE_KIB", "0", 0)
|
||||||
return Config{}, fmt.Errorf("MINIBIN_MAX_FILE_KIB must be greater than 0")
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
expiriesSetting := envOrDefault("MINIBIN_EXPIRIES", "1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0")
|
expiriesSetting := envOrDefault("MINIBIN_EXPIRIES", "1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0")
|
||||||
@@ -72,9 +71,6 @@ func LoadConfig() (Config, error) {
|
|||||||
}
|
}
|
||||||
reportOptionsSetting := envOrDefault("MINIBIN_REPORT_OPTIONS", "Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud")
|
reportOptionsSetting := envOrDefault("MINIBIN_REPORT_OPTIONS", "Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud")
|
||||||
reportOptions := strings.Split(reportOptionsSetting, ",")
|
reportOptions := strings.Split(reportOptionsSetting, ",")
|
||||||
if len(reportOptions) == 0 {
|
|
||||||
return Config{}, fmt.Errorf("no valid report options set")
|
|
||||||
}
|
|
||||||
ipAddressSource := envOrDefault("MINIBIN_IP_ADDRESS_SOURCE", "remote")
|
ipAddressSource := envOrDefault("MINIBIN_IP_ADDRESS_SOURCE", "remote")
|
||||||
if !slices.Contains([]string{"remote", "cloudflare", "xff"}, ipAddressSource) {
|
if !slices.Contains([]string{"remote", "cloudflare", "xff"}, ipAddressSource) {
|
||||||
return Config{}, fmt.Errorf("%s is not a valid MINIBIN_IP_ADDRESS_SOURCE option", ipAddressSource)
|
return Config{}, fmt.Errorf("%s is not a valid MINIBIN_IP_ADDRESS_SOURCE option", ipAddressSource)
|
||||||
@@ -105,23 +101,32 @@ func LoadConfig() (Config, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Config{
|
config := Config{
|
||||||
UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"),
|
UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"),
|
||||||
MaxPasteBytes: maxPasteKiB * 1024,
|
MaxPasteBytes: maxPasteKiB,
|
||||||
MaxFileBytes: maxFileKiB * 1024,
|
MaxFileBytes: maxFileKiB,
|
||||||
|
MaxStorageUsage: maxStorageUsageKiB,
|
||||||
Expiries: expiries,
|
Expiries: expiries,
|
||||||
NormalizeMIMETypes: envOrDefault("MINIBIN_NORMALIZE_MIME_TYPES", "true") == "true",
|
NormalizeMIMETypes: envAsBool("MINIBIN_NORMALIZE_MIME_TYPES", "true"),
|
||||||
BannedMIMETypes: strings.Split(envOrDefault("MINIBIN_BANNED_MIME_TYPES", ""), ","),
|
BannedMIMETypes: strings.Split(envOrDefault("MINIBIN_BANNED_MIME_TYPES", ""), ","),
|
||||||
PoWDifficulty: powDifficulty,
|
PoWDifficulty: powDifficulty,
|
||||||
ReportOptions: reportOptions,
|
ReportOptions: reportOptions,
|
||||||
|
|
||||||
|
DisplayStorageUsage: envAsBool("MINIBIN_STATS_DISPLAY_STORAGE_USAGE", "false"),
|
||||||
|
DisplayStorageLimit: envAsBool("MINIBIN_STATS_DISPLAY_STORAGE_LIMIT", "false"),
|
||||||
|
|
||||||
DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"),
|
DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"),
|
||||||
Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"),
|
Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"),
|
||||||
Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"),
|
Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"),
|
||||||
IPAdressSource: ipAddressSource,
|
IPAdressSource: ipAddressSource,
|
||||||
TrustedProxies: trustedProxies,
|
TrustedProxies: trustedProxies,
|
||||||
BannedClientASNs: bannedAsns,
|
BannedClientASNs: bannedAsns,
|
||||||
}, nil
|
}
|
||||||
|
if !config.DisplayStorageUsage && config.DisplayStorageLimit {
|
||||||
|
return Config{}, fmt.Errorf("MINIBIN_STATS_DISPLAY_STORAGE_LIMIT must be enabled when MINIBIN_STATS_DISPLAY_STORAGE_USAGE is enabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func envOrDefault(key, fallback string) string {
|
func envOrDefault(key, fallback string) string {
|
||||||
@@ -131,3 +136,19 @@ func envOrDefault(key, fallback string) string {
|
|||||||
}
|
}
|
||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func envKibAsBytes(key, fallback string, minKiB int64) (int64, error) {
|
||||||
|
setting := envOrDefault(key, fallback)
|
||||||
|
value, err := strconv.ParseInt(setting, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("parse %s: %w", key, err)
|
||||||
|
}
|
||||||
|
if value < minKiB {
|
||||||
|
return 0, fmt.Errorf("%s cannot be less than %v", key, minKiB)
|
||||||
|
}
|
||||||
|
return value * 1024, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func envAsBool(key, fallback string) bool {
|
||||||
|
return strings.ToLower(envOrDefault(key, fallback)) == "true"
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,17 +15,26 @@ const (
|
|||||||
ContentPaste
|
ContentPaste
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type UploadState uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Complete UploadState = iota
|
||||||
|
Pending
|
||||||
|
Deleting
|
||||||
|
)
|
||||||
|
|
||||||
type Upload struct {
|
type Upload struct {
|
||||||
ID string `gorm:"column:id;primaryKey" json:"id"`
|
ID string `gorm:"column:id;primaryKey" json:"id"`
|
||||||
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
|
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
|
||||||
Filename string `gorm:"column:filename;not null" json:"-"`
|
Filename string `gorm:"column:filename;not null" json:"-"`
|
||||||
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
|
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
|
||||||
Size int64 `gorm:"column:size;not null" json:"size"`
|
Size int64 `gorm:"column:size;not null" json:"size"`
|
||||||
SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"`
|
SHA256 []byte `gorm:"column:sha256;type:blob;index" json:"-"`
|
||||||
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"`
|
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
|
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"`
|
LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"`
|
||||||
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
|
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
|
||||||
|
State UploadState `gorm:"column:state;not null;default:0;type:integer;index" json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Report struct {
|
type Report struct {
|
||||||
@@ -36,6 +45,13 @@ type Report struct {
|
|||||||
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"`
|
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Stat struct {
|
||||||
|
Key string `gorm:"column:key;primaryKey"`
|
||||||
|
Value int64 `gorm:"column:value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var ErrStorageQuotaExceeded = errors.New("storage quota exceeded")
|
||||||
|
|
||||||
func InitDatabase(path string) (*gorm.DB, error) {
|
func InitDatabase(path string) (*gorm.DB, error) {
|
||||||
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true})
|
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -60,7 +76,7 @@ func InitDatabase(path string) (*gorm.DB, error) {
|
|||||||
return nil, fmt.Errorf("set synchronous normal: %w", err)
|
return nil, fmt.Errorf("set synchronous normal: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := db.AutoMigrate(&Upload{}, &Report{}); err != nil {
|
if err := db.AutoMigrate(&Upload{}, &Report{}, &Stat{}); err != nil {
|
||||||
migrationErr := fmt.Errorf("migrate database: %w", err)
|
migrationErr := fmt.Errorf("migrate database: %w", err)
|
||||||
return nil, errors.Join(migrationErr, sqlDB.Close())
|
return nil, errors.Join(migrationErr, sqlDB.Close())
|
||||||
}
|
}
|
||||||
@@ -68,8 +84,44 @@ func InitDatabase(path string) (*gorm.DB, error) {
|
|||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func InsertUpload(db *gorm.DB, upload *Upload) error {
|
func ReserveUpload(db *gorm.DB, upload *Upload, maxStorageUsage int64) (int64, error) {
|
||||||
return db.Create(upload).Error
|
var usedBytes int64
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
query := tx.Model(&Stat{}).Where(`"Key" = ?`, "quota_usage")
|
||||||
|
if maxStorageUsage > 0 {
|
||||||
|
query = query.Where("value <= ?", maxStorageUsage-upload.Size)
|
||||||
|
}
|
||||||
|
result := query.UpdateColumn("value", gorm.Expr("value + ?", upload.Size))
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
var stat Stat
|
||||||
|
if err := tx.Where(`"key" =?`, "quota_usage").Take(&stat).Error; err != nil {
|
||||||
|
return fmt.Errorf("read quota usage: %w", err)
|
||||||
|
}
|
||||||
|
usedBytes = stat.Value
|
||||||
|
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
return fmt.Errorf("reserve upload: %w", ErrStorageQuotaExceeded)
|
||||||
|
}
|
||||||
|
upload.State = Pending
|
||||||
|
return tx.Create(upload).Error
|
||||||
|
})
|
||||||
|
if err != nil && !errors.Is(err, ErrStorageQuotaExceeded) {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return usedBytes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func CompleteUpload(db *gorm.DB, upload *Upload) error {
|
||||||
|
if upload.SHA256 == nil {
|
||||||
|
return fmt.Errorf("sha256 hash required")
|
||||||
|
}
|
||||||
|
return db.Model(&Upload{}).Where("id = ? AND state = ?", upload.ID, Pending).
|
||||||
|
Updates(map[string]any{
|
||||||
|
"sha256": upload.SHA256,
|
||||||
|
"state": Complete,
|
||||||
|
}).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
func InsertReport(db *gorm.DB, report *Report) error {
|
func InsertReport(db *gorm.DB, report *Report) error {
|
||||||
@@ -78,8 +130,40 @@ func InsertReport(db *gorm.DB, report *Report) error {
|
|||||||
|
|
||||||
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
|
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
|
||||||
var upload Upload
|
var upload Upload
|
||||||
if err := db.First(&upload, "id = ?", id).Error; err != nil {
|
// will only find uploads whose upload state is complete
|
||||||
|
if err := db.First(&upload, "id = ? AND state = ?", id, Complete).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &upload, nil
|
return &upload, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func EnsureQuotaUsage(db *gorm.DB) error {
|
||||||
|
var stat Stat
|
||||||
|
result := db.Where(`"key" = ?`, "quota_usage").Limit(1).Find(&stat)
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
} else if result.RowsAffected == 0 {
|
||||||
|
return rebuildQuotaUsage(db)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetQuotaUsage(db *gorm.DB) (int64, error) {
|
||||||
|
var stat Stat
|
||||||
|
if err := db.First(&stat, `"key" = ?`, "quota_usage").Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return stat.Value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func rebuildQuotaUsage(db *gorm.DB) error {
|
||||||
|
return db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
var total int64
|
||||||
|
if err := tx.Model(&Upload{}).Select("COALESCE(SUM(size),0)").Scan(&total).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Exec(`
|
||||||
|
INSERT INTO stats ("key", value) values (?,?)
|
||||||
|
ON CONFLICT ("key") DO UPDATE SET value = excluded.value`, "quota_usage", total).Error
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
+19
-19
@@ -11,6 +11,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
"git.whoswhip.dev/whoswhip/minibin/internal/config"
|
"git.whoswhip.dev/whoswhip/minibin/internal/config"
|
||||||
"github.com/dustin/go-humanize"
|
"github.com/dustin/go-humanize"
|
||||||
@@ -20,16 +21,7 @@ type Pages struct {
|
|||||||
Templates *template.Template
|
Templates *template.Template
|
||||||
Qts []string
|
Qts []string
|
||||||
Placeholders []string
|
Placeholders []string
|
||||||
}
|
QuotaUsage *atomic.Int64
|
||||||
|
|
||||||
type HomePageData struct {
|
|
||||||
Expiries []config.Expiry
|
|
||||||
Qt string
|
|
||||||
PastePlaceholder string
|
|
||||||
FileMaxSize string
|
|
||||||
FileMaxSizeBytes int64
|
|
||||||
PasteMaxSize string
|
|
||||||
PasteMaxSizeBytes int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pages *Pages) Render(w http.ResponseWriter, name string, data any) {
|
func (pages *Pages) Render(w http.ResponseWriter, name string, data any) {
|
||||||
@@ -68,7 +60,7 @@ func GetRandomQt(qts []string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadPages() (*Pages, error) {
|
func LoadPages(usage *atomic.Int64) (*Pages, error) {
|
||||||
templates, err := template.New("").Funcs(template.FuncMap{
|
templates, err := template.New("").Funcs(template.FuncMap{
|
||||||
"hasPrefix": strings.HasPrefix,
|
"hasPrefix": strings.HasPrefix,
|
||||||
}).ParseGlob("web/templates/*.html")
|
}).ParseGlob("web/templates/*.html")
|
||||||
@@ -79,6 +71,7 @@ func LoadPages() (*Pages, error) {
|
|||||||
pages := &Pages{
|
pages := &Pages{
|
||||||
Templates: templates,
|
Templates: templates,
|
||||||
Placeholders: []string{"cmon, paste something already!"},
|
Placeholders: []string{"cmon, paste something already!"},
|
||||||
|
QuotaUsage: usage,
|
||||||
}
|
}
|
||||||
|
|
||||||
qtFiles, err := os.ReadDir("qts")
|
qtFiles, err := os.ReadDir("qts")
|
||||||
@@ -110,17 +103,24 @@ func LoadPages() (*Pages, error) {
|
|||||||
|
|
||||||
func HomeHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
|
func HomeHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
data := HomePageData{
|
data := map[string]any{
|
||||||
Expiries: cfg.Expiries,
|
"Expiries": cfg.Expiries,
|
||||||
FileMaxSize: humanize.Bytes(uint64(cfg.MaxFileBytes)),
|
"FileMaxSize": humanize.Bytes(uint64(cfg.MaxFileBytes)),
|
||||||
FileMaxSizeBytes: cfg.MaxFileBytes,
|
"FileMaxSizeBytes": cfg.MaxFileBytes,
|
||||||
PasteMaxSize: humanize.Bytes(uint64(cfg.MaxPasteBytes)),
|
"PasteMaxSize": humanize.Bytes(uint64(cfg.MaxPasteBytes)),
|
||||||
PasteMaxSizeBytes: cfg.MaxPasteBytes,
|
"PasteMaxSizeBytes": cfg.MaxPasteBytes,
|
||||||
Qt: GetRandomQt(pages.Qts),
|
"Qt": GetRandomQt(pages.Qts),
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(pages.Placeholders) > 0 {
|
if len(pages.Placeholders) > 0 {
|
||||||
data.PastePlaceholder = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
|
data["PastePlaceholder"] = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.DisplayStorageLimit {
|
||||||
|
data["StorageLimit"] = humanize.Bytes(uint64(cfg.MaxStorageUsage))
|
||||||
|
}
|
||||||
|
if cfg.DisplayStorageUsage {
|
||||||
|
data["StorageUsage"] = humanize.Bytes(uint64(pages.QuotaUsage.Load()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pages.Render(w, "home.html", data)
|
pages.Render(w, "home.html", data)
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
@@ -31,6 +32,7 @@ type UploadInput struct {
|
|||||||
Filename string
|
Filename string
|
||||||
MIMEType string
|
MIMEType string
|
||||||
Type database.ContentType
|
Type database.ContentType
|
||||||
|
Size int64
|
||||||
}
|
}
|
||||||
type UploadResponse struct {
|
type UploadResponse struct {
|
||||||
database.Upload
|
database.Upload
|
||||||
@@ -109,6 +111,7 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
|
|||||||
input.Reader = file
|
input.Reader = file
|
||||||
input.Filename = header.Filename
|
input.Filename = header.Filename
|
||||||
input.Type = database.ContentFile
|
input.Type = database.ContentFile
|
||||||
|
input.Size = header.Size
|
||||||
case "text/plain", "application/x-www-form-urlencoded": // paste uploads
|
case "text/plain", "application/x-www-form-urlencoded": // paste uploads
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes)
|
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes)
|
||||||
var content string
|
var content string
|
||||||
@@ -145,6 +148,7 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
|
|||||||
Filename: "paste.txt",
|
Filename: "paste.txt",
|
||||||
MIMEType: "text/plain; charset=utf-8",
|
MIMEType: "text/plain; charset=utf-8",
|
||||||
Type: database.ContentPaste,
|
Type: database.ContentPaste,
|
||||||
|
Size: int64(len(content)),
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
p.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType)
|
p.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType)
|
||||||
@@ -181,39 +185,6 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("create file:", err)
|
|
||||||
p.HTTPError(w, r, "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 {
|
|
||||||
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Println("write file:", err)
|
|
||||||
p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := dest.Close(); err != nil {
|
|
||||||
log.Println("close file:", err)
|
|
||||||
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
createdAt := time.Now().UTC().Unix()
|
createdAt := time.Now().UTC().Unix()
|
||||||
expires, err := selected.ExpiresFrom(time.Now().UTC())
|
expires, err := selected.ExpiresFrom(time.Now().UTC())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -243,14 +214,59 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
|
|||||||
Type: input.Type,
|
Type: input.Type,
|
||||||
Filename: input.Filename,
|
Filename: input.Filename,
|
||||||
MIMEType: input.MIMEType,
|
MIMEType: input.MIMEType,
|
||||||
Size: size,
|
Size: input.Size,
|
||||||
SHA256: hasher.Sum(nil),
|
|
||||||
CreatedAt: createdAt,
|
CreatedAt: createdAt,
|
||||||
ExpiresAt: expiresAt,
|
ExpiresAt: expiresAt,
|
||||||
LastAccessedAt: createdAt,
|
LastAccessedAt: createdAt,
|
||||||
DeleteToken: rand.Text(),
|
DeleteToken: rand.Text(),
|
||||||
}
|
}
|
||||||
err = database.InsertUpload(db, &upload)
|
usedBytes, err := database.ReserveUpload(db, &upload, cfg.MaxStorageUsage)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, database.ErrStorageQuotaExceeded) {
|
||||||
|
p.HTTPError(w, r, "storage capacity reached", http.StatusInsufficientStorage)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("reserve upload:", err)
|
||||||
|
p.HTTPError(w, r, "failed to reserve 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)
|
||||||
|
p.HTTPError(w, r, "failed 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()
|
||||||
|
_, err = io.Copy(io.MultiWriter(dest, hasher), input.Reader)
|
||||||
|
if err != nil {
|
||||||
|
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
|
||||||
|
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("write file:", err)
|
||||||
|
p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := dest.Close(); err != nil {
|
||||||
|
log.Println("close file:", err)
|
||||||
|
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
upload.SHA256 = hasher.Sum(nil)
|
||||||
|
err = database.CompleteUpload(db, &upload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("save upload:", err)
|
log.Println("save upload:", err)
|
||||||
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
|
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
|
||||||
@@ -266,6 +282,13 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
|
|||||||
Qt: pages.GetRandomQt(p.Qts),
|
Qt: pages.GetRandomQt(p.Qts),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.DisplayStorageUsage {
|
||||||
|
w.Header().Set("X-Storage-Usage", strconv.FormatInt(usedBytes, 10))
|
||||||
|
}
|
||||||
|
if cfg.DisplayStorageLimit {
|
||||||
|
w.Header().Set("X-Storage-Limit", strconv.FormatInt(cfg.MaxStorageUsage, 10))
|
||||||
|
}
|
||||||
|
|
||||||
switch returnType {
|
switch returnType {
|
||||||
// html & maybe xml? cant think of other return types
|
// html & maybe xml? cant think of other return types
|
||||||
case "html":
|
case "html":
|
||||||
|
|||||||
@@ -18,7 +18,11 @@ goals:
|
|||||||
|
|
||||||
# roadmap/todo
|
# roadmap/todo
|
||||||
|
|
||||||
- [ ] max total storage usage
|
- [x] max total storage usage
|
||||||
|
- [ ] clean up unfinished uploads
|
||||||
|
- [ ] on startup
|
||||||
|
- [ ] on upload failure
|
||||||
|
- [ ] on admin action
|
||||||
- [ ] size based expiry
|
- [ ] size based expiry
|
||||||
- exclusions if below a certain size (like 5mb)
|
- exclusions if below a certain size (like 5mb)
|
||||||
- [ ] prometheus metrics
|
- [ ] prometheus metrics
|
||||||
@@ -33,6 +37,7 @@ goals:
|
|||||||
- update expiry of uploads
|
- update expiry of uploads
|
||||||
- prune uploads that haven't been accessed for a specific amount of time
|
- prune uploads that haven't been accessed for a specific amount of time
|
||||||
- delete (duh!)
|
- delete (duh!)
|
||||||
|
- prune unfinished uploads
|
||||||
- local access from a specifc ip or range only
|
- local access from a specifc ip or range only
|
||||||
- [x] ASN blocking via geolite2
|
- [x] ASN blocking via geolite2
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,11 @@
|
|||||||
<label for="type-file">file</label>
|
<label for="type-file">file</label>
|
||||||
<input type="radio" name="upload-type" id="type-paste" />
|
<input type="radio" name="upload-type" id="type-paste" />
|
||||||
<label for="type-paste">paste</label>
|
<label for="type-paste">paste</label>
|
||||||
|
{{if or .StorageUsage .StorageLimit}}
|
||||||
|
<span class="muted" style="margin-left: auto; width: fit-content;">
|
||||||
|
{{.StorageUsage}}{{if .StorageLimit}} / {{.StorageLimit}}{{end}} used
|
||||||
|
</span>
|
||||||
|
{{end}}
|
||||||
<div class="file-panel">
|
<div class="file-panel">
|
||||||
<form id="upload-file-form" action="/upload?return=html" method="post" enctype="multipart/form-data">
|
<form id="upload-file-form" action="/upload?return=html" method="post" enctype="multipart/form-data">
|
||||||
<label class="muted" for="file-expiry">expiry</label>
|
<label class="muted" for="file-expiry">expiry</label>
|
||||||
|
|||||||
Reference in New Issue
Block a user