2017-06-27 11:00:33 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-04-26 14:17:08 +02:00
|
|
|
"bytes"
|
2017-06-27 11:00:33 +02:00
|
|
|
"compress/gzip"
|
2018-09-10 08:17:00 +02:00
|
|
|
"context"
|
2017-07-01 23:25:08 +02:00
|
|
|
"crypto/subtle"
|
2017-06-27 11:00:33 +02:00
|
|
|
"fmt"
|
|
|
|
"log"
|
2018-09-10 08:17:00 +02:00
|
|
|
"net"
|
2017-06-27 11:00:33 +02:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2017-07-03 06:08:47 +02:00
|
|
|
"time"
|
2018-03-15 18:58:11 +02:00
|
|
|
|
|
|
|
nanoid "github.com/matoous/go-nanoid"
|
2018-09-10 08:17:00 +02:00
|
|
|
"golang.org/x/net/netutil"
|
2017-06-27 11:00:33 +02:00
|
|
|
)
|
|
|
|
|
2017-09-27 10:42:49 +02:00
|
|
|
var mimes = map[imageType]string{
|
2018-09-07 16:45:57 +02:00
|
|
|
imageTypeJPEG: "image/jpeg",
|
|
|
|
imageTypePNG: "image/png",
|
|
|
|
imageTypeWEBP: "image/webp",
|
2017-07-05 23:09:41 +02:00
|
|
|
}
|
|
|
|
|
2017-07-04 16:05:53 +02:00
|
|
|
type httpHandler struct {
|
|
|
|
sem chan struct{}
|
|
|
|
}
|
|
|
|
|
2017-10-06 23:57:41 +02:00
|
|
|
func newHTTPHandler() *httpHandler {
|
|
|
|
return &httpHandler{make(chan struct{}, conf.Concurrency)}
|
2017-07-04 16:05:53 +02:00
|
|
|
}
|
2017-06-27 11:00:33 +02:00
|
|
|
|
2018-09-10 08:17:00 +02:00
|
|
|
func startServer() *http.Server {
|
|
|
|
l, err := net.Listen("tcp", conf.Bind)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
s := &http.Server{
|
|
|
|
Handler: newHTTPHandler(),
|
|
|
|
ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
|
|
|
|
MaxHeaderBytes: 1 << 20,
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
log.Printf("Starting server at %s\n", conf.Bind)
|
|
|
|
log.Fatal(s.Serve(netutil.LimitListener(l, conf.MaxClients)))
|
|
|
|
}()
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func shutdownServer(s *http.Server) {
|
|
|
|
log.Println("Shutting down the server...")
|
|
|
|
|
|
|
|
ctx, close := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer close()
|
|
|
|
|
|
|
|
s.Shutdown(ctx)
|
|
|
|
}
|
|
|
|
|
2017-06-27 11:00:33 +02:00
|
|
|
func logResponse(status int, msg string) {
|
|
|
|
var color int
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
if status >= 500 {
|
2017-06-27 11:00:33 +02:00
|
|
|
color = 31
|
2017-10-04 21:44:58 +02:00
|
|
|
} else if status >= 400 {
|
2017-06-27 11:00:33 +02:00
|
|
|
color = 33
|
|
|
|
} else {
|
|
|
|
color = 32
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
|
|
|
|
}
|
|
|
|
|
2018-04-26 13:22:31 +02: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 18:58:11 +02:00
|
|
|
func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, duration time.Duration) {
|
2017-06-27 11:00:33 +02:00
|
|
|
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
|
|
|
|
|
2017-07-03 12:10:44 +02:00
|
|
|
rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
|
2017-10-30 11:53:51 +02:00
|
|
|
rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
|
2018-02-26 10:45:52 +02:00
|
|
|
rw.Header().Set("Content-Type", mimes[po.Format])
|
|
|
|
|
2018-04-26 14:17:08 +02:00
|
|
|
dataToRespond := data
|
2017-06-27 11:00:33 +02:00
|
|
|
|
|
|
|
if gzipped {
|
2018-04-26 14:17:08 +02:00
|
|
|
var buf bytes.Buffer
|
|
|
|
|
|
|
|
gz, _ := gzip.NewWriterLevel(&buf, conf.GZipCompression)
|
2017-06-27 11:00:33 +02:00
|
|
|
gz.Write(data)
|
|
|
|
gz.Close()
|
2018-04-26 14:17:08 +02:00
|
|
|
|
|
|
|
dataToRespond = buf.Bytes()
|
|
|
|
|
|
|
|
rw.Header().Set("Content-Encoding", "gzip")
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
2017-07-03 06:08:47 +02:00
|
|
|
|
2018-04-26 14:17:08 +02:00
|
|
|
rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
|
|
|
|
|
|
|
|
rw.WriteHeader(200)
|
|
|
|
rw.Write(dataToRespond)
|
|
|
|
|
2018-03-15 18:58:11 +02:00
|
|
|
logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, duration, imgURL, po))
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
|
|
|
|
2018-03-15 18:58:11 +02:00
|
|
|
func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
|
|
|
|
logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
|
2017-06-27 11:00:33 +02:00
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
rw.WriteHeader(err.StatusCode)
|
|
|
|
rw.Write([]byte(err.PublicMessage))
|
2017-07-01 23:25:08 +02:00
|
|
|
}
|
|
|
|
|
2018-04-26 13:22:31 +02:00
|
|
|
func respondWithOptions(reqID string, rw http.ResponseWriter) {
|
|
|
|
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
|
|
|
|
rw.WriteHeader(200)
|
|
|
|
}
|
|
|
|
|
2017-07-01 23:25:08 +02:00
|
|
|
func checkSecret(s string) bool {
|
2017-07-03 11:36:37 +02:00
|
|
|
if len(conf.Secret) == 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
|
2017-07-01 23:25:08 +02:00
|
|
|
}
|
|
|
|
|
2018-03-15 16:53:39 +02:00
|
|
|
func (h *httpHandler) lock() {
|
2018-03-19 10:58:52 +02:00
|
|
|
h.sem <- struct{}{}
|
2017-07-04 16:05:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *httpHandler) unlock() {
|
2017-10-04 21:44:58 +02:00
|
|
|
<-h.sem
|
2017-07-04 16:05:53 +02:00
|
|
|
}
|
|
|
|
|
2017-10-06 23:57:41 +02:00
|
|
|
func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
|
2018-03-15 18:58:11 +02:00
|
|
|
reqID, _ := nanoid.Nanoid()
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
if err, ok := r.(imgproxyError); ok {
|
2018-03-15 18:58:11 +02:00
|
|
|
respondWithError(reqID, rw, err)
|
2017-10-04 21:44:58 +02:00
|
|
|
} else {
|
2018-03-15 18:58:11 +02:00
|
|
|
respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
|
2017-10-04 21:44:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2017-07-04 16:05:53 +02:00
|
|
|
|
2018-04-26 13:22:31 +02: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 17:12:06 +02:00
|
|
|
if !checkSecret(r.Header.Get("Authorization")) {
|
|
|
|
panic(invalidSecretErr)
|
|
|
|
}
|
|
|
|
|
2018-03-15 16:53:39 +02:00
|
|
|
h.lock()
|
2017-10-04 21:44:58 +02:00
|
|
|
defer h.unlock()
|
2017-07-03 06:08:47 +02:00
|
|
|
|
2017-10-25 11:57:19 +02:00
|
|
|
if r.URL.Path == "/health" {
|
2018-02-26 10:45:52 +02:00
|
|
|
rw.WriteHeader(200)
|
|
|
|
rw.Write([]byte("imgproxy is running"))
|
2017-10-25 11:57:19 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-03-19 10:58:52 +02:00
|
|
|
t := startTimer(time.Duration(conf.WriteTimeout)*time.Second, "Processing")
|
|
|
|
|
2017-06-27 11:00:33 +02:00
|
|
|
imgURL, procOpt, err := parsePath(r)
|
|
|
|
if err != nil {
|
2017-10-04 21:44:58 +02:00
|
|
|
panic(newError(404, err.Error(), "Invalid image url"))
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err = url.ParseRequestURI(imgURL); err != nil {
|
2017-10-04 21:44:58 +02:00
|
|
|
panic(newError(404, err.Error(), "Invalid image url"))
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
|
|
|
|
2017-09-27 10:42:49 +02:00
|
|
|
b, imgtype, err := downloadImage(imgURL)
|
2017-06-27 11:00:33 +02:00
|
|
|
if err != nil {
|
2017-10-04 21:44:58 +02:00
|
|
|
panic(newError(404, err.Error(), "Image is unreachable"))
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
t.Check()
|
|
|
|
|
2018-02-26 11:41:37 +02: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 10:45:52 +02:00
|
|
|
}
|
|
|
|
|
2018-02-26 11:41:37 +02:00
|
|
|
t.Check()
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
b, err = processImage(b, imgtype, procOpt, t)
|
2017-06-27 11:00:33 +02:00
|
|
|
if err != nil {
|
2017-10-04 21:44:58 +02:00
|
|
|
panic(newError(500, err.Error(), "Error occurred while processing image"))
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|
|
|
|
|
2017-10-04 21:44:58 +02:00
|
|
|
t.Check()
|
|
|
|
|
2018-03-15 18:58:11 +02:00
|
|
|
respondWithImage(reqID, r, rw, b, imgURL, procOpt, t.Since())
|
2017-06-27 11:00:33 +02:00
|
|
|
}
|