forked from mattermost/mattermost
/
atmos_camo.go
88 lines (68 loc) · 2.45 KB
/
atmos_camo.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
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package imageproxy
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"io"
"net/http"
"strings"
)
type AtmosCamoBackend struct {
proxy *ImageProxy
}
func makeAtmosCamoBackend(proxy *ImageProxy) *AtmosCamoBackend {
return &AtmosCamoBackend{
proxy: proxy,
}
}
func (backend *AtmosCamoBackend) GetImage(w http.ResponseWriter, r *http.Request, imageURL string) {
http.Redirect(w, r, backend.GetProxiedImageURL(imageURL), http.StatusFound)
}
func (backend *AtmosCamoBackend) GetImageDirect(imageURL string) (io.ReadCloser, string, error) {
req, err := http.NewRequest("GET", backend.GetProxiedImageURL(imageURL), nil)
if err != nil {
return nil, "", Error{err}
}
client := backend.proxy.HTTPService.MakeClient(false)
resp, err := client.Do(req)
if err != nil {
return nil, "", Error{err}
}
// Note that we don't do any additional validation of the received data since we expect the image proxy to do that
return resp.Body, resp.Header.Get("Content-Type"), nil
}
func (backend *AtmosCamoBackend) GetProxiedImageURL(imageURL string) string {
cfg := *backend.proxy.ConfigService.Config()
siteURL := *cfg.ServiceSettings.SiteURL
proxyURL := *cfg.ImageProxySettings.RemoteImageProxyURL
options := *cfg.ImageProxySettings.RemoteImageProxyOptions
return getAtmosCamoImageURL(imageURL, siteURL, proxyURL, options)
}
func getAtmosCamoImageURL(imageURL, siteURL, proxyURL, options string) string {
// Don't proxy blank images, relative URLs, absolute URLs on this server, or URLs that are already going through the proxy
if imageURL == "" || imageURL[0] == '/' || (siteURL != "" && strings.HasPrefix(imageURL, siteURL)) || strings.HasPrefix(imageURL, proxyURL) {
return imageURL
}
mac := hmac.New(sha1.New, []byte(options))
mac.Write([]byte(imageURL))
digest := hex.EncodeToString(mac.Sum(nil))
return proxyURL + "/" + digest + "/" + hex.EncodeToString([]byte(imageURL))
}
func (backend *AtmosCamoBackend) GetUnproxiedImageURL(proxiedURL string) string {
proxyURL := *backend.proxy.ConfigService.Config().ImageProxySettings.RemoteImageProxyURL + "/"
if !strings.HasPrefix(proxiedURL, proxyURL) {
return proxiedURL
}
path := proxiedURL[len(proxyURL):]
slash := strings.IndexByte(path, '/')
if slash == -1 {
return proxiedURL
}
decoded, err := hex.DecodeString(path[slash+1:])
if err != nil {
return proxiedURL
}
return string(decoded)
}