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.

helpers.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package validation
  5. import (
  6. "net"
  7. "net/url"
  8. "regexp"
  9. "strings"
  10. "code.gitea.io/gitea/modules/setting"
  11. )
  12. var loopbackIPBlocks []*net.IPNet
  13. var externalTrackerRegex = regexp.MustCompile(`({?)(?:user|repo|index)+?(}?)`)
  14. func init() {
  15. for _, cidr := range []string{
  16. "127.0.0.0/8", // IPv4 loopback
  17. "::1/128", // IPv6 loopback
  18. } {
  19. if _, block, err := net.ParseCIDR(cidr); err == nil {
  20. loopbackIPBlocks = append(loopbackIPBlocks, block)
  21. }
  22. }
  23. }
  24. func isLoopbackIP(ip string) bool {
  25. pip := net.ParseIP(ip)
  26. if pip == nil {
  27. return false
  28. }
  29. for _, block := range loopbackIPBlocks {
  30. if block.Contains(pip) {
  31. return true
  32. }
  33. }
  34. return false
  35. }
  36. // IsValidURL checks if URL is valid
  37. func IsValidURL(uri string) bool {
  38. if u, err := url.ParseRequestURI(uri); err != nil ||
  39. (u.Scheme != "http" && u.Scheme != "https") ||
  40. !validPort(portOnly(u.Host)) {
  41. return false
  42. }
  43. return true
  44. }
  45. // IsAPIURL checks if URL is current Gitea instance API URL
  46. func IsAPIURL(uri string) bool {
  47. return strings.HasPrefix(strings.ToLower(uri), strings.ToLower(setting.AppURL+"api"))
  48. }
  49. // IsValidExternalURL checks if URL is valid external URL
  50. func IsValidExternalURL(uri string) bool {
  51. if !IsValidURL(uri) || IsAPIURL(uri) {
  52. return false
  53. }
  54. u, err := url.ParseRequestURI(uri)
  55. if err != nil {
  56. return false
  57. }
  58. // Currently check only if not loopback IP is provided to keep compatibility
  59. if isLoopbackIP(u.Hostname()) || strings.ToLower(u.Hostname()) == "localhost" {
  60. return false
  61. }
  62. // TODO: Later it should be added to allow local network IP addreses
  63. // only if allowed by special setting
  64. return true
  65. }
  66. // IsValidExternalTrackerURLFormat checks if URL matches required syntax for external trackers
  67. func IsValidExternalTrackerURLFormat(uri string) bool {
  68. if !IsValidExternalURL(uri) {
  69. return false
  70. }
  71. // check for typoed variables like /{index/ or /[repo}
  72. for _, match := range externalTrackerRegex.FindAllStringSubmatch(uri, -1) {
  73. if (match[1] == "{" || match[2] == "}") && (match[1] != "{" || match[2] != "}") {
  74. return false
  75. }
  76. }
  77. return true
  78. }