waifu_gallery/http.go

86 lines
2.3 KiB
Go

package main
import (
"errors"
"fmt"
"net/http"
"regexp"
"strings"
"sync"
"time"
"waifu_gallery/s3"
)
var generationQueue sync.Map
// Display a picture from S3, greatly benefits from being cached
func servePicture(w http.ResponseWriter, r *http.Request) {
// TODO no need to check for bad words here
// Validate user input
input, err := handleSubdomain(w, r)
if err != nil {
InfoLogger.Println(err)
return
}
// Fetch image from input in s3
obj, err := s3.Download(input)
if err != nil {
ErrorLogger.Println(err)
return
}
// reader will bitch if the object doesn't exist but.. whatever
http.ServeContent(w, r, input+".png", time.Now(), obj)
}
func serveBadSubdomainError(w http.ResponseWriter) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid subdomain provided"))
}
func serveInternalError(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Server encountered an error processing your request, sorry."))
}
func handleSubdomain(w http.ResponseWriter, r *http.Request) (input string, err error) {
// get Subdomain
domainInd := strings.LastIndex(r.Host, ".")
if domainInd <= 0 {
return "", errors.New("Error: Host '" + r.Host + "' doesn't have a tld")
}
domain := r.Host[:domainInd]
subdomainInd := strings.LastIndex(domain, ".")
if subdomainInd <= 0 {
return "", errors.New("Error: Host '" + r.Host + "' doesn't have a subdomain")
}
subdomain := r.Host[:subdomainInd]
// Subdomain sanitization
input = subdomain[strings.LastIndex(subdomain, ".")+1:] // only keep one level of subdomain
// add spaces
input = strings.ReplaceAll(input, "_", " ")
input = strings.ReplaceAll(input, "-", " ")
// remove non-ascii characters
input = regexp.MustCompile(`[^a-zA-Z0-9 ]+`).ReplaceAllString(input, " ")
input = strings.TrimSpace(input)
input = strings.ToLower(input)
if config.state.bannedWordsRegex.MatchString(input) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("This incident has been reported. Sick fuck."))
return "", fmt.Errorf("banned words in req '%s'", subdomain)
}
if len(input) <= 0 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid input, subdomain cannot be empty (Accepted characters are '_-[A-Za-z]')"))
return "", errors.New("invalid input")
}
return
}