-
-
Notifications
You must be signed in to change notification settings - Fork 630
/
server.go
248 lines (188 loc) · 5.53 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package main
import (
"bytes"
"compress/gzip"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
nanoid "github.com/matoous/go-nanoid"
)
var mimes = map[imageType]string{
JPEG: "image/jpeg",
PNG: "image/png",
WEBP: "image/webp",
}
type httpHandler struct {
sem chan struct{}
}
func newHTTPHandler() *httpHandler {
return &httpHandler{make(chan struct{}, conf.Concurrency)}
}
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
}
if r, ok := resizeTypes[parts[1]]; ok {
po.Resize = r
} else {
return "", po, fmt.Errorf("Invalid resize type: %s", parts[1])
}
if po.Width, err = strconv.Atoi(parts[2]); err != nil {
return "", po, fmt.Errorf("Invalid width: %s", parts[2])
}
if po.Height, err = strconv.Atoi(parts[3]); err != nil {
return "", po, fmt.Errorf("Invalid height: %s", parts[3])
}
if g, ok := gravityTypes[parts[4]]; ok {
po.Gravity = g
} else {
return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
}
po.Enlarge = parts[5] != "0"
filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
if len(filenameParts) < 2 {
po.Format = imageTypes["jpg"]
} else if f, ok := imageTypes[filenameParts[1]]; ok {
po.Format = f
} else {
return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
}
if !vipsTypeSupportSave[po.Format] {
return "", po, errors.New("Resulting image type not supported")
}
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
if status >= 500 {
color = 31
} else if status >= 400 {
color = 33
} else {
color = 32
}
log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
}
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")
}
}
func respondWithImage(reqID string, r *http.Request, rw http.ResponseWriter, data []byte, imgURL string, po processingOptions, duration time.Duration) {
gzipped := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") && conf.GZipCompression > 0
rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
rw.Header().Set("Content-Type", mimes[po.Format])
dataToRespond := data
if gzipped {
var buf bytes.Buffer
gz, _ := gzip.NewWriterLevel(&buf, conf.GZipCompression)
gz.Write(data)
gz.Close()
dataToRespond = buf.Bytes()
rw.Header().Set("Content-Encoding", "gzip")
}
rw.Header().Set("Content-Length", strconv.Itoa(len(dataToRespond)))
rw.WriteHeader(200)
rw.Write(dataToRespond)
logResponse(200, fmt.Sprintf("[%s] Processed in %s: %s; %+v", reqID, duration, imgURL, po))
}
func respondWithError(reqID string, rw http.ResponseWriter, err imgproxyError) {
logResponse(err.StatusCode, fmt.Sprintf("[%s] %s", reqID, err.Message))
rw.WriteHeader(err.StatusCode)
rw.Write([]byte(err.PublicMessage))
}
func respondWithOptions(reqID string, rw http.ResponseWriter) {
logResponse(200, fmt.Sprintf("[%s] Respond with options", reqID))
rw.WriteHeader(200)
}
func checkSecret(s string) bool {
if len(conf.Secret) == 0 {
return true
}
return strings.HasPrefix(s, "Bearer ") && subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(s, "Bearer ")), []byte(conf.Secret)) == 1
}
func (h *httpHandler) lock() {
h.sem <- struct{}{}
}
func (h *httpHandler) unlock() {
<-h.sem
}
func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
reqID, _ := nanoid.Nanoid()
defer func() {
if r := recover(); r != nil {
if err, ok := r.(imgproxyError); ok {
respondWithError(reqID, rw, err)
} else {
respondWithError(reqID, rw, newUnexpectedError(r.(error), 4))
}
}
}()
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)
}
if !checkSecret(r.Header.Get("Authorization")) {
panic(invalidSecretErr)
}
h.lock()
defer h.unlock()
if r.URL.Path == "/health" {
rw.WriteHeader(200)
rw.Write([]byte("imgproxy is running"))
return
}
t := startTimer(time.Duration(conf.WriteTimeout)*time.Second, "Processing")
imgURL, procOpt, err := parsePath(r)
if err != nil {
panic(newError(404, err.Error(), "Invalid image url"))
}
if _, err = url.ParseRequestURI(imgURL); err != nil {
panic(newError(404, err.Error(), "Invalid image url"))
}
b, imgtype, err := downloadImage(imgURL)
if err != nil {
panic(newError(404, err.Error(), "Image is unreachable"))
}
t.Check()
if conf.ETagEnabled {
eTag := calcETag(b, &procOpt)
rw.Header().Set("ETag", eTag)
if eTag == r.Header.Get("If-None-Match") {
panic(notModifiedErr)
}
}
t.Check()
b, err = processImage(b, imgtype, procOpt, t)
if err != nil {
panic(newError(500, err.Error(), "Error occurred while processing image"))
}
t.Check()
respondWithImage(reqID, r, rw, b, imgURL, procOpt, t.Since())
}