2013-12-06 20:40:35 -05:00
|
|
|
// Copyright 2013 Google Inc. All rights reserved.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2014-11-26 19:42:44 -05:00
|
|
|
// Package imageproxy provides an image proxy server. For typical use of
|
|
|
|
// creating and using a Proxy, see cmd/imageproxy/main.go.
|
2014-10-11 20:18:13 -05:00
|
|
|
package imageproxy // import "willnorris.com/go/imageproxy"
|
2013-11-27 14:02:21 -05:00
|
|
|
|
|
|
|
import (
|
2013-12-26 21:31:20 -05:00
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2015-05-11 21:36:42 -05:00
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
2013-11-27 14:02:21 -05:00
|
|
|
"fmt"
|
2013-12-26 21:31:20 -05:00
|
|
|
"io"
|
2013-12-04 05:55:56 -05:00
|
|
|
"io/ioutil"
|
2013-11-27 14:02:21 -05:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2013-12-26 22:36:18 -05:00
|
|
|
"strings"
|
2013-12-26 22:04:35 -05:00
|
|
|
"time"
|
2013-12-04 03:37:13 -05:00
|
|
|
|
2013-12-04 05:55:56 -05:00
|
|
|
"github.com/golang/glog"
|
2013-12-25 21:48:10 -05:00
|
|
|
"github.com/gregjones/httpcache"
|
2016-11-29 18:39:59 -05:00
|
|
|
tphttp "willnorris.com/go/imageproxy/third_party/http"
|
2013-11-27 14:02:21 -05:00
|
|
|
)
|
|
|
|
|
2013-11-27 15:10:29 -05:00
|
|
|
// Proxy serves image requests.
|
|
|
|
type Proxy struct {
|
|
|
|
Client *http.Client // client used to fetch remote URLs
|
2014-11-26 19:42:44 -05:00
|
|
|
Cache Cache // cache used to cache responses
|
2013-12-04 06:12:56 -05:00
|
|
|
|
2014-11-26 19:42:44 -05:00
|
|
|
// Whitelist specifies a list of remote hosts that images can be
|
|
|
|
// proxied from. An empty list means all hosts are allowed.
|
2013-12-04 06:12:56 -05:00
|
|
|
Whitelist []string
|
2015-02-20 00:34:22 -05:00
|
|
|
|
2015-06-14 03:26:40 -05:00
|
|
|
// Referrers, when given, requires that requests to the image
|
|
|
|
// proxy come from a referring host. An empty list means all
|
|
|
|
// hosts are allowed.
|
|
|
|
Referrers []string
|
|
|
|
|
2015-02-20 00:34:22 -05:00
|
|
|
// DefaultBaseURL is the URL that relative remote URLs are resolved in
|
|
|
|
// reference to. If nil, all remote URLs specified in requests must be
|
|
|
|
// absolute.
|
|
|
|
DefaultBaseURL *url.URL
|
2015-05-11 21:36:42 -05:00
|
|
|
|
|
|
|
// SignatureKey is the HMAC key used to verify signed requests.
|
|
|
|
SignatureKey []byte
|
2015-08-12 13:39:38 -05:00
|
|
|
|
|
|
|
// Allow images to scale beyond their original dimensions.
|
|
|
|
ScaleUp bool
|
2016-11-29 16:50:19 -05:00
|
|
|
|
|
|
|
// Timeout specifies a time limit for requests served by this Proxy.
|
|
|
|
// If a call runs for longer than its time limit, a 504 Gateway Timeout
|
|
|
|
// response is returned. A Timeout of zero means no timeout.
|
|
|
|
Timeout time.Duration
|
2013-11-27 15:10:29 -05:00
|
|
|
}
|
|
|
|
|
2014-11-26 19:42:44 -05:00
|
|
|
// NewProxy constructs a new proxy. The provided http RoundTripper will be
|
|
|
|
// used to fetch remote URLs. If nil is provided, http.DefaultTransport will
|
|
|
|
// be used.
|
2013-12-26 21:31:20 -05:00
|
|
|
func NewProxy(transport http.RoundTripper, cache Cache) *Proxy {
|
|
|
|
if transport == nil {
|
|
|
|
transport = http.DefaultTransport
|
2013-11-27 15:10:29 -05:00
|
|
|
}
|
2013-12-25 21:48:10 -05:00
|
|
|
if cache == nil {
|
|
|
|
cache = NopCache
|
|
|
|
}
|
|
|
|
|
2015-08-12 13:39:38 -05:00
|
|
|
proxy := Proxy{
|
|
|
|
Cache: cache,
|
|
|
|
}
|
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
client := new(http.Client)
|
|
|
|
client.Transport = &httpcache.Transport{
|
2015-12-08 02:06:02 -05:00
|
|
|
Transport: &TransformingTransport{transport, client},
|
2013-12-26 21:31:20 -05:00
|
|
|
Cache: cache,
|
|
|
|
MarkCachedResponses: true,
|
|
|
|
}
|
|
|
|
|
2015-08-12 13:39:38 -05:00
|
|
|
proxy.Client = client
|
|
|
|
|
|
|
|
return &proxy
|
2013-11-27 15:10:29 -05:00
|
|
|
}
|
|
|
|
|
2016-11-29 16:50:19 -05:00
|
|
|
// ServeHTTP handles incoming requests.
|
2013-11-27 15:10:29 -05:00
|
|
|
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2014-11-23 19:04:53 -05:00
|
|
|
if r.URL.Path == "/favicon.ico" {
|
|
|
|
return // ignore favicon requests
|
|
|
|
}
|
|
|
|
|
2016-01-12 12:19:27 -05:00
|
|
|
if r.URL.Path == "/health-check" {
|
|
|
|
fmt.Fprint(w, "OK")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-29 16:50:19 -05:00
|
|
|
var h http.Handler = http.HandlerFunc(p.serveImage)
|
|
|
|
if p.Timeout > 0 {
|
2016-11-29 18:39:59 -05:00
|
|
|
h = tphttp.TimeoutHandler(h, p.Timeout, "Gateway timeout waiting for remote resource.")
|
2016-11-29 16:50:19 -05:00
|
|
|
}
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
// serveImage handles incoming requests for proxied images.
|
|
|
|
func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
|
2015-02-20 00:34:22 -05:00
|
|
|
req, err := NewRequest(r, p.DefaultBaseURL)
|
2013-11-27 15:10:29 -05:00
|
|
|
if err != nil {
|
2014-11-21 20:56:59 -05:00
|
|
|
msg := fmt.Sprintf("invalid request URL: %v", err)
|
|
|
|
glog.Error(msg)
|
|
|
|
http.Error(w, msg, http.StatusBadRequest)
|
2013-11-27 15:10:29 -05:00
|
|
|
return
|
|
|
|
}
|
2013-12-04 05:55:56 -05:00
|
|
|
|
2015-12-08 02:06:02 -05:00
|
|
|
// assign static settings from proxy to req.Options
|
|
|
|
req.Options.ScaleUp = p.ScaleUp
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
if err := p.allowed(req); err != nil {
|
|
|
|
glog.Error(err)
|
|
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
2013-12-04 06:12:56 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-05-11 19:12:03 -05:00
|
|
|
resp, err := p.Client.Get(req.String())
|
2013-12-25 21:48:10 -05:00
|
|
|
if err != nil {
|
2014-11-21 20:56:59 -05:00
|
|
|
msg := fmt.Sprintf("error fetching remote image: %v", err)
|
|
|
|
glog.Error(msg)
|
|
|
|
http.Error(w, msg, http.StatusInternalServerError)
|
2013-12-25 21:48:10 -05:00
|
|
|
return
|
2013-12-04 05:55:56 -05:00
|
|
|
}
|
2015-02-24 12:34:49 -05:00
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
cached := resp.Header.Get(httpcache.XFromCache)
|
|
|
|
glog.Infof("request: %v (served from cache: %v)", *req, cached == "1")
|
2013-12-04 05:55:56 -05:00
|
|
|
|
2017-06-14 16:19:57 -05:00
|
|
|
copyHeader(w.Header(), resp.Header, "Cache-Control", "Last-Modified", "Expires", "Etag", "Link")
|
2013-12-04 05:55:56 -05:00
|
|
|
|
2017-06-14 15:34:31 -05:00
|
|
|
if should304(r, resp) {
|
2013-12-26 22:04:35 -05:00
|
|
|
w.WriteHeader(http.StatusNotModified)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-06-14 16:19:57 -05:00
|
|
|
copyHeader(w.Header(), resp.Header, "Content-Length", "Content-Type")
|
2015-05-16 00:27:44 -05:00
|
|
|
w.WriteHeader(resp.StatusCode)
|
2013-12-26 21:31:20 -05:00
|
|
|
io.Copy(w, resp.Body)
|
2013-12-04 05:55:56 -05:00
|
|
|
}
|
|
|
|
|
2017-06-14 16:19:57 -05:00
|
|
|
// copyHeader copies header values from src to dst, adding to any existing
|
|
|
|
// values with the same header name. If keys is not empty, only those header
|
|
|
|
// keys will be copied.
|
|
|
|
func copyHeader(dst, src http.Header, keys ...string) {
|
|
|
|
if len(keys) == 0 {
|
|
|
|
for k, _ := range src {
|
|
|
|
keys = append(keys, k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, key := range keys {
|
|
|
|
k := http.CanonicalHeaderKey(key)
|
|
|
|
for _, v := range src[k] {
|
|
|
|
dst.Add(k, v)
|
|
|
|
}
|
2015-02-21 02:51:07 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
// allowed determines whether the specified request contains an allowed
|
|
|
|
// referrer, host, and signature. It returns an error if the request is not
|
|
|
|
// allowed.
|
|
|
|
func (p *Proxy) allowed(r *Request) error {
|
2015-06-14 03:26:40 -05:00
|
|
|
if len(p.Referrers) > 0 && !validReferrer(p.Referrers, r.Original) {
|
2015-12-13 19:59:56 -05:00
|
|
|
return fmt.Errorf("request does not contain an allowed referrer: %v", r)
|
2015-06-14 03:26:40 -05:00
|
|
|
}
|
|
|
|
|
2015-05-11 21:36:42 -05:00
|
|
|
if len(p.Whitelist) == 0 && len(p.SignatureKey) == 0 {
|
2015-12-13 19:59:56 -05:00
|
|
|
return nil // no whitelist or signature key, all requests accepted
|
2015-05-11 23:35:07 -05:00
|
|
|
}
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
if len(p.Whitelist) > 0 && validHost(p.Whitelist, r.URL) {
|
|
|
|
return nil
|
2015-05-11 21:36:42 -05:00
|
|
|
}
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
if len(p.SignatureKey) > 0 && validSignature(p.SignatureKey, r) {
|
|
|
|
return nil
|
2013-12-04 06:12:56 -05:00
|
|
|
}
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
return fmt.Errorf("request does not contain an allowed host or valid signature: %v", r)
|
2015-05-11 23:35:07 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// validHost returns whether the host in u matches one of hosts.
|
|
|
|
func validHost(hosts []string, u *url.URL) bool {
|
|
|
|
for _, host := range hosts {
|
2013-12-04 06:12:56 -05:00
|
|
|
if u.Host == host {
|
|
|
|
return true
|
|
|
|
}
|
2013-12-26 22:36:18 -05:00
|
|
|
if strings.HasPrefix(host, "*.") && strings.HasSuffix(u.Host, host[2:]) {
|
|
|
|
return true
|
|
|
|
}
|
2013-12-04 06:12:56 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-06-14 03:26:40 -05:00
|
|
|
// returns whether the referrer from the request is in the host list.
|
|
|
|
func validReferrer(hosts []string, r *http.Request) bool {
|
2015-12-13 19:59:56 -05:00
|
|
|
u, err := url.Parse(r.Header.Get("Referer"))
|
2015-06-14 03:26:40 -05:00
|
|
|
if err != nil { // malformed or blank header, just deny
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-12-13 19:59:56 -05:00
|
|
|
return validHost(hosts, u)
|
2015-06-14 03:26:40 -05:00
|
|
|
}
|
|
|
|
|
2015-05-11 21:36:42 -05:00
|
|
|
// validSignature returns whether the request signature is valid.
|
|
|
|
func validSignature(key []byte, r *Request) bool {
|
|
|
|
sig := r.Options.Signature
|
|
|
|
if m := len(sig) % 4; m != 0 { // add padding if missing
|
|
|
|
sig += strings.Repeat("=", 4-m)
|
|
|
|
}
|
|
|
|
|
|
|
|
got, err := base64.URLEncoding.DecodeString(sig)
|
|
|
|
if err != nil {
|
|
|
|
glog.Errorf("error base64 decoding signature %q", r.Options.Signature)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
mac := hmac.New(sha256.New, key)
|
|
|
|
mac.Write([]byte(r.URL.String()))
|
|
|
|
want := mac.Sum(nil)
|
|
|
|
|
|
|
|
return hmac.Equal(got, want)
|
|
|
|
}
|
|
|
|
|
2017-06-14 15:34:31 -05:00
|
|
|
// should304 returns whether we should send a 304 Not Modified in response to
|
2014-11-21 10:51:19 -05:00
|
|
|
// req, based on the response resp. This is determined using the last modified
|
|
|
|
// time and the entity tag of resp.
|
2017-06-14 15:34:31 -05:00
|
|
|
func should304(req *http.Request, resp *http.Response) bool {
|
2014-11-21 10:51:19 -05:00
|
|
|
// TODO(willnorris): if-none-match header can be a comma separated list
|
|
|
|
// of multiple tags to be matched, or the special value "*" which
|
|
|
|
// matches all etags
|
2013-12-26 22:04:35 -05:00
|
|
|
etag := resp.Header.Get("Etag")
|
|
|
|
if etag != "" && etag == req.Header.Get("If-None-Match") {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
lastModified, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ifModSince, err := time.Parse(time.RFC1123, req.Header.Get("If-Modified-Since"))
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if lastModified.Before(ifModSince) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
// TransformingTransport is an implementation of http.RoundTripper that
|
|
|
|
// optionally transforms images using the options specified in the request URL
|
|
|
|
// fragment.
|
|
|
|
type TransformingTransport struct {
|
2014-11-26 19:42:44 -05:00
|
|
|
// Transport is the underlying http.RoundTripper used to satisfy
|
|
|
|
// non-transform requests (those that do not include a URL fragment).
|
2013-12-26 21:31:20 -05:00
|
|
|
Transport http.RoundTripper
|
|
|
|
|
2014-11-26 19:42:44 -05:00
|
|
|
// CachingClient is used to fetch images to be resized. This client is
|
|
|
|
// used rather than Transport directly in order to ensure that
|
|
|
|
// responses are properly cached.
|
|
|
|
CachingClient *http.Client
|
2013-12-26 21:31:20 -05:00
|
|
|
}
|
|
|
|
|
2014-11-26 19:42:44 -05:00
|
|
|
// RoundTrip implements the http.RoundTripper interface.
|
2013-12-26 21:31:20 -05:00
|
|
|
func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
if req.URL.Fragment == "" {
|
|
|
|
// normal requests pass through
|
|
|
|
glog.Infof("fetching remote URL: %v", req.URL)
|
|
|
|
return t.Transport.RoundTrip(req)
|
2013-12-04 05:55:56 -05:00
|
|
|
}
|
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
u := *req.URL
|
|
|
|
u.Fragment = ""
|
2014-11-26 19:42:44 -05:00
|
|
|
resp, err := t.CachingClient.Get(u.String())
|
2014-11-20 01:22:21 -05:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-12-26 21:31:20 -05:00
|
|
|
|
2017-06-14 19:04:41 -05:00
|
|
|
if should304(req, resp) {
|
|
|
|
// bare 304 response, full response will be used from cache
|
|
|
|
return &http.Response{StatusCode: http.StatusNotModified}, nil
|
|
|
|
}
|
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
defer resp.Body.Close()
|
|
|
|
b, err := ioutil.ReadAll(resp.Body)
|
2013-12-04 05:55:56 -05:00
|
|
|
if err != nil {
|
2013-12-26 21:31:20 -05:00
|
|
|
return nil, err
|
2013-12-04 05:55:56 -05:00
|
|
|
}
|
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
opt := ParseOptions(req.URL.Fragment)
|
2015-08-12 13:39:38 -05:00
|
|
|
|
2013-12-26 21:31:20 -05:00
|
|
|
img, err := Transform(b, opt)
|
|
|
|
if err != nil {
|
2015-03-18 01:47:43 -05:00
|
|
|
glog.Errorf("error transforming image: %v", err)
|
2013-12-26 21:31:20 -05:00
|
|
|
img = b
|
|
|
|
}
|
|
|
|
|
|
|
|
// replay response with transformed image and updated content length
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
fmt.Fprintf(buf, "%s %s\n", resp.Proto, resp.Status)
|
2017-06-01 09:51:14 -05:00
|
|
|
resp.Header.WriteSubset(buf, map[string]bool{
|
|
|
|
"Content-Length": true,
|
2017-06-01 10:10:34 -05:00
|
|
|
// exclude Content-Type header if the format may have changed during transformation
|
|
|
|
"Content-Type": opt.Format != "" || resp.Header.Get("Content-Type") == "image/webp",
|
2017-06-01 09:51:14 -05:00
|
|
|
})
|
2013-12-26 21:31:20 -05:00
|
|
|
fmt.Fprintf(buf, "Content-Length: %d\n\n", len(img))
|
|
|
|
buf.Write(img)
|
|
|
|
|
|
|
|
return http.ReadResponse(bufio.NewReader(buf), req)
|
2013-11-27 15:10:29 -05:00
|
|
|
}
|