You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

camo.go 1.3KB

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