1
0
mirror of https://github.com/imgproxy/imgproxy.git synced 2025-01-23 11:14:48 +02:00
imgproxy/server.go

249 lines
5.5 KiB
Go
Raw Normal View History

2017-06-27 12:00:33 +03:00
package main
import (
2018-04-26 18:17:08 +06:00
"bytes"
2017-06-27 12:00:33 +03:00
"compress/gzip"
"crypto/subtle"
2017-06-27 12:00:33 +03:00
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
2017-07-03 10:08:47 +06:00
"time"
2018-03-15 22:58:11 +06:00
nanoid "github.com/matoous/go-nanoid"
2017-06-27 12:00:33 +03:00
)
2017-09-27 14:42:49 +06:00
var mimes = map[imageType]string{
JPEG: "image/jpeg",
PNG: "image/png",
WEBP: "image/webp",
}
2017-07-04 20:05:53 +06:00
type httpHandler struct {
sem chan struct{}
}
2017-10-07 03:57:41 +06:00
func newHTTPHandler() *httpHandler {
return &httpHandler{make(chan struct{}, conf.Concurrency)}
2017-07-04 20:05:53 +06:00
}
2017-06-27 12:00:33 +03:00
func parsePath(r *http.Request) (string, processingOptions, error) {
var po processingOptions
var err error
path := r.URL.Path
parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
if len(parts) < 7 {
return "", po, errors.New("Invalid path")
}
token := parts[0]
if err = validatePath(token, strings.TrimPrefix(path, fmt.Sprintf("/%s", token))); err != nil {
return "", po, err
}
2017-09-27 14:42:49 +06:00
if r, ok := resizeTypes[parts[1]]; ok {
po.Resize = r
2017-09-27 14:42:49 +06:00
} else {
return "", po, fmt.Errorf("Invalid resize type: %s", parts[1])
}
2017-06-27 12:00:33 +03:00
if po.Width, err = strconv.Atoi(parts[2]); err != nil {
2017-06-27 12:00:33 +03:00
return "", po, fmt.Errorf("Invalid width: %s", parts[2])
}
if po.Height, err = strconv.Atoi(parts[3]); err != nil {
2017-06-27 12:00:33 +03:00
return "", po, fmt.Errorf("Invalid height: %s", parts[3])
}
if g, ok := gravityTypes[parts[4]]; ok {
po.Gravity = g
2017-06-27 12:00:33 +03:00
} else {
return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
}
po.Enlarge = parts[5] != "0"
2017-06-27 12:00:33 +03:00
filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
if len(filenameParts) < 2 {
po.Format = imageTypes["jpg"]
2017-06-27 12:00:33 +03:00
} else if f, ok := imageTypes[filenameParts[1]]; ok {
po.Format = f
2017-06-27 12:00:33 +03:00
} else {
return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
}
if !vipsTypeSupportSave[po.Format] {
2017-09-27 14:42:49 +06:00
return "", po, errors.New("Resulting image type not supported")
}
2017-06-27 12:00:33 +03:00
filename, err := base64.RawURLEncoding.DecodeString(filenameParts[0])
if err != nil {
return "", po, errors.New("Invalid filename encoding")
}
return string(filename), po, nil
}
func logResponse(status int, msg string) {
var color int
2017-10-05 01:44:58 +06:00
if status >= 500 {
2017-06-27 12:00:33 +03:00
color = 31
2017-10-05 01:44:58 +06:00
} else if status >= 400 {
2017-06-27 12:00:33 +03:00
color = 33
} else {
color = 32
}
log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
}
2018-04-26 17:22:31 +06:00
func writeCORS(rw http.ResponseWriter) {
if len(conf.AllowOrigin) > 0 {
rw.Header().Set("Access-Control-Allow-Origin", conf.AllowOrigin)
rw.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONs")
}
}
2018-03-15 22:58:11 +06:00
func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, duration time.Duration) {
2017-06-27 12:00:33 +03:00
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
2017-07-03 16:10:44 +06:00
rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
2017-10-30 10:53:51 +01:00
rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
rw.Header().Set("Content-Type", mimes[po.Format])
2018-04-26 18:17:08 +06:00
dataToRespond := data
2017-06-27 12:00:33 +03:00
if gzipped {
2018-04-26 18:17:08 +06:00
var buf bytes.Buffer
gz, _ := gzip.NewWriterLevel(&buf, conf.GZipCompression)
2017-06-27 12:00:33 +03:00
gz.Write(data)
gz.Close()
2018-04-26 18:17:08 +06:00
dataToRespond = buf.Bytes()
rw.Header().Set("Content-Encoding", "gzip")
2017-06-27 12:00:33 +03:00
}
2017-07-03 10:08:47 +06:00
2018-04-26 18:17:08 +06:00
rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
rw.WriteHeader(200)
rw.Write(dataToRespond)
2018-03-15 22:58:11 +06:00
logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, duration, imgURL, po))
2017-06-27 12:00:33 +03:00
}
2018-03-15 22:58:11 +06:00
func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
2017-06-27 12:00:33 +03:00
2017-10-05 01:44:58 +06:00
rw.WriteHeader(err.StatusCode)
rw.Write([]byte(err.PublicMessage))
}
2018-04-26 17:22:31 +06:00
func respondWithOptions(reqID string, rw http.ResponseWriter) {
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
rw.WriteHeader(200)
}
func checkSecret(s string) bool {
2017-07-03 15:36:37 +06:00
if len(conf.Secret) == 0 {
return true
}
return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
}
2018-03-15 20:53:39 +06:00
func (h *httpHandler) lock() {
2018-03-19 14:58:52 +06:00
h.sem <- struct{}{}
2017-07-04 20:05:53 +06:00
}
func (h *httpHandler) unlock() {
2017-10-05 01:44:58 +06:00
<-h.sem
2017-07-04 20:05:53 +06:00
}
2017-10-07 03:57:41 +06:00
func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
2018-03-15 22:58:11 +06:00
reqID, _ := nanoid.Nanoid()
2017-10-05 01:44:58 +06:00
defer func() {
if r := recover(); r != nil {
if err, ok := r.(imgproxyError); ok {
2018-03-15 22:58:11 +06:00
respondWithError(reqID, rw, err)
2017-10-05 01:44:58 +06:00
} else {
2018-03-15 22:58:11 +06:00
respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
2017-10-05 01:44:58 +06:00
}
}
}()
2017-07-04 20:05:53 +06:00
2018-04-26 17:22:31 +06:00
log.Printf("[%s] %s: %s\n", reqID, r.Method, r.URL.RequestURI())
writeCORS(rw)
if r.Method == http.MethodOptions {
respondWithOptions(reqID, rw)
return
}
if r.Method != http.MethodGet {
panic(invalidMethodErr)
}
2018-03-15 21:12:06 +06:00
if !checkSecret(r.Header.Get("Authorization")) {
panic(invalidSecretErr)
}
2018-03-15 20:53:39 +06:00
h.lock()
2017-10-05 01:44:58 +06:00
defer h.unlock()
2017-07-03 10:08:47 +06:00
if r.URL.Path == "/health" {
rw.WriteHeader(200)
rw.Write([]byte("imgproxy is running"))
return
}
2018-03-19 14:58:52 +06:00
t := startTimer(time.Duration(conf.WriteTimeout)*time.Second, "Processing")
2017-06-27 12:00:33 +03:00
imgURL, procOpt, err := parsePath(r)
if err != nil {
2017-10-05 01:44:58 +06:00
panic(newError(404, err.Error(), "Invalid image url"))
2017-06-27 12:00:33 +03:00
}
if _, err = url.ParseRequestURI(imgURL); err != nil {
2017-10-05 01:44:58 +06:00
panic(newError(404, err.Error(), "Invalid image url"))
2017-06-27 12:00:33 +03:00
}
2017-09-27 14:42:49 +06:00
b, imgtype, err := downloadImage(imgURL)
2017-06-27 12:00:33 +03:00
if err != nil {
2017-10-05 01:44:58 +06:00
panic(newError(404, err.Error(), "Image is unreachable"))
2017-06-27 12:00:33 +03:00
}
2017-10-05 01:44:58 +06:00
t.Check()
2018-02-26 15:41:37 +06:00
if conf.ETagEnabled {
eTag := calcETag(b, &procOpt)
rw.Header().Set("ETag", eTag)
if eTag == r.Header.Get("If-None-Match") {
panic(notModifiedErr)
}
}
2018-02-26 15:41:37 +06:00
t.Check()
2017-10-05 01:44:58 +06:00
b, err = processImage(b, imgtype, procOpt, t)
2017-06-27 12:00:33 +03:00
if err != nil {
2017-10-05 01:44:58 +06:00
panic(newError(500, err.Error(), "Error occurred while processing image"))
2017-06-27 12:00:33 +03:00
}
2017-10-05 01:44:58 +06:00
t.Check()
2018-03-15 22:58:11 +06:00
respondWithImage(reqID, r, rw, b, imgURL, procOpt, t.Since())
2017-06-27 12:00:33 +03:00
}