url.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package options
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/url"
  6. "strings"
  7. "github.com/imgproxy/imgproxy/v3/config"
  8. )
  9. const urlTokenPlain = "plain"
  10. func preprocessURL(u string) string {
  11. for _, repl := range config.URLReplacements {
  12. u = repl.Regexp.ReplaceAllString(u, repl.Replacement)
  13. }
  14. if len(config.BaseURL) == 0 || strings.HasPrefix(u, config.BaseURL) {
  15. return u
  16. }
  17. return fmt.Sprintf("%s%s", config.BaseURL, u)
  18. }
  19. func decodeBase64URL(parts []string) (string, string, error) {
  20. var format string
  21. if len(parts) > 1 && config.Base64URLIncludesFilename {
  22. parts = parts[:len(parts)-1]
  23. }
  24. encoded := strings.Join(parts, "")
  25. urlParts := strings.Split(encoded, ".")
  26. if len(urlParts[0]) == 0 {
  27. return "", "", newInvalidURLError("Image URL is empty")
  28. }
  29. if len(urlParts) > 2 {
  30. return "", "", newInvalidURLError("Multiple formats are specified: %s", encoded)
  31. }
  32. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  33. format = urlParts[1]
  34. }
  35. imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
  36. if err != nil {
  37. return "", "", newInvalidURLError("Invalid url encoding: %s", encoded)
  38. }
  39. return preprocessURL(string(imageURL)), format, nil
  40. }
  41. func decodePlainURL(parts []string) (string, string, error) {
  42. var format string
  43. encoded := strings.Join(parts, "/")
  44. urlParts := strings.Split(encoded, "@")
  45. if len(urlParts[0]) == 0 {
  46. return "", "", newInvalidURLError("Image URL is empty")
  47. }
  48. if len(urlParts) > 2 {
  49. return "", "", newInvalidURLError("Multiple formats are specified: %s", encoded)
  50. }
  51. if len(urlParts) == 2 && len(urlParts[1]) > 0 {
  52. format = urlParts[1]
  53. }
  54. unescaped, err := url.PathUnescape(urlParts[0])
  55. if err != nil {
  56. return "", "", newInvalidURLError("Invalid url encoding: %s", encoded)
  57. }
  58. return preprocessURL(unescaped), format, nil
  59. }
  60. func DecodeURL(parts []string) (string, string, error) {
  61. if len(parts) == 0 {
  62. return "", "", newInvalidURLError("Image URL is empty")
  63. }
  64. if parts[0] == urlTokenPlain && len(parts) > 1 {
  65. return decodePlainURL(parts[1:])
  66. }
  67. return decodeBase64URL(parts)
  68. }