code.gitea.io/gitea@v1.19.3/modules/markup/camo.go (about) 1 // Copyright 2022 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package markup 5 6 import ( 7 "crypto/hmac" 8 "crypto/sha1" 9 "encoding/base64" 10 "net/url" 11 "strings" 12 13 "code.gitea.io/gitea/modules/setting" 14 "code.gitea.io/gitea/modules/util" 15 ) 16 17 // CamoEncode encodes a lnk to fit with the go-camo and camo proxy links. The purposes of camo-proxy are: 18 // 1. Allow accessing "http://" images on a HTTPS site by using the "https://" URLs provided by camo-proxy. 19 // 2. Hide the visitor's real IP (protect privacy) when accessing external images. 20 func CamoEncode(link string) string { 21 if strings.HasPrefix(link, setting.Camo.ServerURL) { 22 return link 23 } 24 25 mac := hmac.New(sha1.New, []byte(setting.Camo.HMACKey)) 26 _, _ = mac.Write([]byte(link)) // hmac does not return errors 27 macSum := b64encode(mac.Sum(nil)) 28 encodedURL := b64encode([]byte(link)) 29 30 return util.URLJoin(setting.Camo.ServerURL, macSum, encodedURL) 31 } 32 33 func b64encode(data []byte) string { 34 return strings.TrimRight(base64.URLEncoding.EncodeToString(data), "=") 35 } 36 37 func camoHandleLink(link string) string { 38 if setting.Camo.Enabled { 39 lnkURL, err := url.Parse(link) 40 if err == nil && lnkURL.IsAbs() && !strings.HasPrefix(link, setting.AppURL) && 41 (setting.Camo.Allways || lnkURL.Scheme != "https") { 42 return CamoEncode(link) 43 } 44 } 45 return link 46 }