gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package proxy
  4. import (
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "strings"
  9. "sync"
  10. "code.gitea.io/gitea/modules/glob"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. )
  14. var (
  15. once sync.Once
  16. hostMatchers []glob.Glob
  17. )
  18. // GetProxyURL returns proxy url
  19. func GetProxyURL() string {
  20. if !setting.Proxy.Enabled {
  21. return ""
  22. }
  23. if setting.Proxy.ProxyURL == "" {
  24. if os.Getenv("http_proxy") != "" {
  25. return os.Getenv("http_proxy")
  26. }
  27. return os.Getenv("https_proxy")
  28. }
  29. return setting.Proxy.ProxyURL
  30. }
  31. // Match return true if url needs to be proxied
  32. func Match(u string) bool {
  33. if !setting.Proxy.Enabled {
  34. return false
  35. }
  36. // enforce do once
  37. Proxy()
  38. for _, v := range hostMatchers {
  39. if v.Match(u) {
  40. return true
  41. }
  42. }
  43. return false
  44. }
  45. // Proxy returns the system proxy
  46. func Proxy() func(req *http.Request) (*url.URL, error) {
  47. if !setting.Proxy.Enabled {
  48. return func(req *http.Request) (*url.URL, error) {
  49. return nil, nil
  50. }
  51. }
  52. if setting.Proxy.ProxyURL == "" {
  53. return http.ProxyFromEnvironment
  54. }
  55. once.Do(func() {
  56. for _, h := range setting.Proxy.ProxyHosts {
  57. if g, err := glob.Compile(h); err == nil {
  58. hostMatchers = append(hostMatchers, g)
  59. } else {
  60. log.Error("glob.Compile %s failed: %v", h, err)
  61. }
  62. }
  63. })
  64. return func(req *http.Request) (*url.URL, error) {
  65. for _, v := range hostMatchers {
  66. if v.Match(req.URL.Host) {
  67. return http.ProxyURL(setting.Proxy.ProxyURLFixed)(req)
  68. }
  69. }
  70. return http.ProxyFromEnvironment(req)
  71. }
  72. }
  73. // EnvWithProxy returns os.Environ(), with a https_proxy env, if the given url
  74. // needs to be proxied.
  75. func EnvWithProxy(u *url.URL) []string {
  76. envs := os.Environ()
  77. if strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https") {
  78. if Match(u.Host) {
  79. envs = append(envs, "https_proxy="+GetProxyURL())
  80. }
  81. }
  82. return envs
  83. }