本站源代码
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

97 linhas
2.2KB

  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. }
上海开阖软件有限公司 沪ICP备12045867号-1