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.

379 lines
12 KiB

  1. /*
  2. Package purell offers URL normalization as described on the wikipedia page:
  3. http://en.wikipedia.org/wiki/URL_normalization
  4. */
  5. package purell
  6. import (
  7. "bytes"
  8. "fmt"
  9. "net/url"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "github.com/PuerkitoBio/urlesc"
  15. "golang.org/x/net/idna"
  16. "golang.org/x/text/unicode/norm"
  17. "golang.org/x/text/width"
  18. )
  19. // A set of normalization flags determines how a URL will
  20. // be normalized.
  21. type NormalizationFlags uint
  22. const (
  23. // Safe normalizations
  24. FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1
  25. FlagLowercaseHost // http://HOST -> http://host
  26. FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF
  27. FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA
  28. FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$
  29. FlagRemoveDefaultPort // http://host:80 -> http://host
  30. FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path
  31. // Usually safe normalizations
  32. FlagRemoveTrailingSlash // http://host/path/ -> http://host/path
  33. FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags)
  34. FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c
  35. // Unsafe normalizations
  36. FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/
  37. FlagRemoveFragment // http://host/path#fragment -> http://host/path
  38. FlagForceHTTP // https://host -> http://host
  39. FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b
  40. FlagRemoveWWW // http://www.host/ -> http://host/
  41. FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags)
  42. FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3
  43. // Normalizations not in the wikipedia article, required to cover tests cases
  44. // submitted by jehiah
  45. FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147
  46. FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147
  47. FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147
  48. FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path
  49. FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path
  50. // Convenience set of safe normalizations
  51. FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator
  52. // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags,
  53. // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix".
  54. // Convenience set of usually safe normalizations (includes FlagsSafe)
  55. FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments
  56. FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments
  57. // Convenience set of unsafe normalizations (includes FlagsUsuallySafe)
  58. FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery
  59. FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery
  60. // Convenience set of all available flags
  61. FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator
  62. FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator
  63. )
  64. const (
  65. defaultHttpPort = ":80"
  66. defaultHttpsPort = ":443"
  67. )
  68. // Regular expressions used by the normalizations
  69. var rxPort = regexp.MustCompile(`(:\d+)/?$`)
  70. var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`)
  71. var rxDupSlashes = regexp.MustCompile(`/{2,}`)
  72. var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`)
  73. var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`)
  74. var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`)
  75. var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`)
  76. var rxEmptyPort = regexp.MustCompile(`:+$`)
  77. // Map of flags to implementation function.
  78. // FlagDecodeUnnecessaryEscapes has no action, since it is done automatically
  79. // by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator.
  80. // Since maps have undefined traversing order, make a slice of ordered keys
  81. var flagsOrder = []NormalizationFlags{
  82. FlagLowercaseScheme,
  83. FlagLowercaseHost,
  84. FlagRemoveDefaultPort,
  85. FlagRemoveDirectoryIndex,
  86. FlagRemoveDotSegments,
  87. FlagRemoveFragment,
  88. FlagForceHTTP, // Must be after remove default port (because https=443/http=80)
  89. FlagRemoveDuplicateSlashes,
  90. FlagRemoveWWW,
  91. FlagAddWWW,
  92. FlagSortQuery,
  93. FlagDecodeDWORDHost,
  94. FlagDecodeOctalHost,
  95. FlagDecodeHexHost,
  96. FlagRemoveUnnecessaryHostDots,
  97. FlagRemoveEmptyPortSeparator,
  98. FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last
  99. FlagAddTrailingSlash,
  100. }
  101. // ... and then the map, where order is unimportant
  102. var flags = map[NormalizationFlags]func(*url.URL){
  103. FlagLowercaseScheme: lowercaseScheme,
  104. FlagLowercaseHost: lowercaseHost,
  105. FlagRemoveDefaultPort: removeDefaultPort,
  106. FlagRemoveDirectoryIndex: removeDirectoryIndex,
  107. FlagRemoveDotSegments: removeDotSegments,
  108. FlagRemoveFragment: removeFragment,
  109. FlagForceHTTP: forceHTTP,
  110. FlagRemoveDuplicateSlashes: removeDuplicateSlashes,
  111. FlagRemoveWWW: removeWWW,
  112. FlagAddWWW: addWWW,
  113. FlagSortQuery: sortQuery,
  114. FlagDecodeDWORDHost: decodeDWORDHost,
  115. FlagDecodeOctalHost: decodeOctalHost,
  116. FlagDecodeHexHost: decodeHexHost,
  117. FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots,
  118. FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator,
  119. FlagRemoveTrailingSlash: removeTrailingSlash,
  120. FlagAddTrailingSlash: addTrailingSlash,
  121. }
  122. // MustNormalizeURLString returns the normalized string, and panics if an error occurs.
  123. // It takes an URL string as input, as well as the normalization flags.
  124. func MustNormalizeURLString(u string, f NormalizationFlags) string {
  125. result, e := NormalizeURLString(u, f)
  126. if e != nil {
  127. panic(e)
  128. }
  129. return result
  130. }
  131. // NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object.
  132. // It takes an URL string as input, as well as the normalization flags.
  133. func NormalizeURLString(u string, f NormalizationFlags) (string, error) {
  134. parsed, err := url.Parse(u)
  135. if err != nil {
  136. return "", err
  137. }
  138. if f&FlagLowercaseHost == FlagLowercaseHost {
  139. parsed.Host = strings.ToLower(parsed.Host)
  140. }
  141. // The idna package doesn't fully conform to RFC 5895
  142. // (https://tools.ietf.org/html/rfc5895), so we do it here.
  143. // Taken from Go 1.8 cycle source, courtesy of bradfitz.
  144. // TODO: Remove when (if?) idna package conforms to RFC 5895.
  145. parsed.Host = width.Fold.String(parsed.Host)
  146. parsed.Host = norm.NFC.String(parsed.Host)
  147. if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil {
  148. return "", err
  149. }
  150. return NormalizeURL(parsed, f), nil
  151. }
  152. // NormalizeURL returns the normalized string.
  153. // It takes a parsed URL object as input, as well as the normalization flags.
  154. func NormalizeURL(u *url.URL, f NormalizationFlags) string {
  155. for _, k := range flagsOrder {
  156. if f&k == k {
  157. flags[k](u)
  158. }
  159. }
  160. return urlesc.Escape(u)
  161. }
  162. func lowercaseScheme(u *url.URL) {
  163. if len(u.Scheme) > 0 {
  164. u.Scheme = strings.ToLower(u.Scheme)
  165. }
  166. }
  167. func lowercaseHost(u *url.URL) {
  168. if len(u.Host) > 0 {
  169. u.Host = strings.ToLower(u.Host)
  170. }
  171. }
  172. func removeDefaultPort(u *url.URL) {
  173. if len(u.Host) > 0 {
  174. scheme := strings.ToLower(u.Scheme)
  175. u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string {
  176. if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) {
  177. return ""
  178. }
  179. return val
  180. })
  181. }
  182. }
  183. func removeTrailingSlash(u *url.URL) {
  184. if l := len(u.Path); l > 0 {
  185. if strings.HasSuffix(u.Path, "/") {
  186. u.Path = u.Path[:l-1]
  187. }
  188. } else if l = len(u.Host); l > 0 {
  189. if strings.HasSuffix(u.Host, "/") {
  190. u.Host = u.Host[:l-1]
  191. }
  192. }
  193. }
  194. func addTrailingSlash(u *url.URL) {
  195. if l := len(u.Path); l > 0 {
  196. if !strings.HasSuffix(u.Path, "/") {
  197. u.Path += "/"
  198. }
  199. } else if l = len(u.Host); l > 0 {
  200. if !strings.HasSuffix(u.Host, "/") {
  201. u.Host += "/"
  202. }
  203. }
  204. }
  205. func removeDotSegments(u *url.URL) {
  206. if len(u.Path) > 0 {
  207. var dotFree []string
  208. var lastIsDot bool
  209. sections := strings.Split(u.Path, "/")
  210. for _, s := range sections {
  211. if s == ".." {
  212. if len(dotFree) > 0 {
  213. dotFree = dotFree[:len(dotFree)-1]
  214. }
  215. } else if s != "." {
  216. dotFree = append(dotFree, s)
  217. }
  218. lastIsDot = (s == "." || s == "..")
  219. }
  220. // Special case if host does not end with / and new path does not begin with /
  221. u.Path = strings.Join(dotFree, "/")
  222. if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") {
  223. u.Path = "/" + u.Path
  224. }
  225. // Special case if the last segment was a dot, make sure the path ends with a slash
  226. if lastIsDot && !strings.HasSuffix(u.Path, "/") {
  227. u.Path += "/"
  228. }
  229. }
  230. }
  231. func removeDirectoryIndex(u *url.URL) {
  232. if len(u.Path) > 0 {
  233. u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1")
  234. }
  235. }
  236. func removeFragment(u *url.URL) {
  237. u.Fragment = ""
  238. }
  239. func forceHTTP(u *url.URL) {
  240. if strings.ToLower(u.Scheme) == "https" {
  241. u.Scheme = "http"
  242. }
  243. }
  244. func removeDuplicateSlashes(u *url.URL) {
  245. if len(u.Path) > 0 {
  246. u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/")
  247. }
  248. }
  249. func removeWWW(u *url.URL) {
  250. if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") {
  251. u.Host = u.Host[4:]
  252. }
  253. }
  254. func addWWW(u *url.URL) {
  255. if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") {
  256. u.Host = "www." + u.Host
  257. }
  258. }
  259. func sortQuery(u *url.URL) {
  260. q := u.Query()
  261. if len(q) > 0 {
  262. arKeys := make([]string, len(q))
  263. i := 0
  264. for k := range q {
  265. arKeys[i] = k
  266. i++
  267. }
  268. sort.Strings(arKeys)
  269. buf := new(bytes.Buffer)
  270. for _, k := range arKeys {
  271. sort.Strings(q[k])
  272. for _, v := range q[k] {
  273. if buf.Len() > 0 {
  274. buf.WriteRune('&')
  275. }
  276. buf.WriteString(fmt.Sprintf("%s=%s", k, urlesc.QueryEscape(v)))
  277. }
  278. }
  279. // Rebuild the raw query string
  280. u.RawQuery = buf.String()
  281. }
  282. }
  283. func decodeDWORDHost(u *url.URL) {
  284. if len(u.Host) > 0 {
  285. if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 {
  286. var parts [4]int64
  287. dword, _ := strconv.ParseInt(matches[1], 10, 0)
  288. for i, shift := range []uint{24, 16, 8, 0} {
  289. parts[i] = dword >> shift & 0xFF
  290. }
  291. u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2])
  292. }
  293. }
  294. }
  295. func decodeOctalHost(u *url.URL) {
  296. if len(u.Host) > 0 {
  297. if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 {
  298. var parts [4]int64
  299. for i := 1; i <= 4; i++ {
  300. parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0)
  301. }
  302. u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5])
  303. }
  304. }
  305. }
  306. func decodeHexHost(u *url.URL) {
  307. if len(u.Host) > 0 {
  308. if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 {
  309. // Conversion is safe because of regex validation
  310. parsed, _ := strconv.ParseInt(matches[1], 16, 0)
  311. // Set host as DWORD (base 10) encoded host
  312. u.Host = fmt.Sprintf("%d%s", parsed, matches[2])
  313. // The rest is the same as decoding a DWORD host
  314. decodeDWORDHost(u)
  315. }
  316. }
  317. }
  318. func removeUnncessaryHostDots(u *url.URL) {
  319. if len(u.Host) > 0 {
  320. if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 {
  321. // Trim the leading and trailing dots
  322. u.Host = strings.Trim(matches[1], ".")
  323. if len(matches) > 2 {
  324. u.Host += matches[2]
  325. }
  326. }
  327. }
  328. }
  329. func removeEmptyPortSeparator(u *url.URL) {
  330. if len(u.Host) > 0 {
  331. u.Host = rxEmptyPort.ReplaceAllString(u.Host, "")
  332. }
  333. }