proxyRequestHandler.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "imuslab.com/Zoarxy/mod/geodb"
  11. "imuslab.com/Zoarxy/mod/statistic"
  12. "imuslab.com/Zoarxy/mod/websocketproxy"
  13. )
  14. func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
  15. var targetProxyEndpoint *ProxyEndpoint = nil
  16. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  17. rootname := key.(string)
  18. if strings.HasPrefix(requestURI, rootname) {
  19. thisProxyEndpoint := value.(*ProxyEndpoint)
  20. targetProxyEndpoint = thisProxyEndpoint
  21. }
  22. /*
  23. if len(requestURI) >= len(rootname) && requestURI[:len(rootname)] == rootname {
  24. thisProxyEndpoint := value.(*ProxyEndpoint)
  25. targetProxyEndpoint = thisProxyEndpoint
  26. }
  27. */
  28. return true
  29. })
  30. return targetProxyEndpoint
  31. }
  32. func (router *Router) getSubdomainProxyEndpointFromHostname(hostname string) *SubdomainEndpoint {
  33. var targetSubdomainEndpoint *SubdomainEndpoint = nil
  34. ep, ok := router.SubdomainEndpoint.Load(hostname)
  35. if ok {
  36. targetSubdomainEndpoint = ep.(*SubdomainEndpoint)
  37. }
  38. return targetSubdomainEndpoint
  39. }
  40. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  41. if len(requestURL) > len(rooturl) {
  42. return requestURL[len(rooturl):]
  43. }
  44. return ""
  45. }
  46. func (h *ProxyHandler) subdomainRequest(w http.ResponseWriter, r *http.Request, target *SubdomainEndpoint) {
  47. r.Header.Set("X-Forwarded-Host", r.Host)
  48. requestURL := r.URL.String()
  49. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  50. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  51. r.Header.Set("A-Upgrade", "websocket")
  52. wsRedirectionEndpoint := target.Domain
  53. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  54. //Append / to the end of the redirection endpoint if not exists
  55. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  56. }
  57. if len(requestURL) > 0 && requestURL[:1] == "/" {
  58. //Remove starting / from request URL if exists
  59. requestURL = requestURL[1:]
  60. }
  61. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  62. if target.RequireTLS {
  63. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  64. }
  65. h.logRequest(r, true, 101, "subdomain-websocket")
  66. wspHandler := websocketproxy.NewProxy(u)
  67. wspHandler.ServeHTTP(w, r)
  68. return
  69. }
  70. r.Host = r.URL.Host
  71. err := target.Proxy.ServeHTTP(w, r)
  72. var dnsError *net.DNSError
  73. if err != nil {
  74. if errors.As(err, &dnsError) {
  75. http.ServeFile(w, r, "./web/hosterror.html")
  76. log.Println(err.Error())
  77. h.logRequest(r, false, 404, "subdomain-http")
  78. } else {
  79. http.ServeFile(w, r, "./web/rperror.html")
  80. log.Println(err.Error())
  81. h.logRequest(r, false, 521, "subdomain-http")
  82. }
  83. }
  84. h.logRequest(r, true, 200, "subdomain-http")
  85. }
  86. func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  87. rewriteURL := h.Parent.rewriteURL(target.Root, r.RequestURI)
  88. r.URL, _ = url.Parse(rewriteURL)
  89. r.Header.Set("X-Forwarded-Host", r.Host)
  90. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  91. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  92. r.Header.Set("A-Upgrade", "websocket")
  93. wsRedirectionEndpoint := target.Domain
  94. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  95. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  96. }
  97. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  98. if target.RequireTLS {
  99. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  100. }
  101. h.logRequest(r, true, 101, "vdir-websocket")
  102. wspHandler := websocketproxy.NewProxy(u)
  103. wspHandler.ServeHTTP(w, r)
  104. return
  105. }
  106. r.Host = r.URL.Host
  107. err := target.Proxy.ServeHTTP(w, r)
  108. var dnsError *net.DNSError
  109. if err != nil {
  110. if errors.As(err, &dnsError) {
  111. http.ServeFile(w, r, "./web/hosterror.html")
  112. log.Println(err.Error())
  113. h.logRequest(r, false, 404, "vdir-http")
  114. } else {
  115. http.ServeFile(w, r, "./web/rperror.html")
  116. log.Println(err.Error())
  117. h.logRequest(r, false, 521, "vdir-http")
  118. }
  119. }
  120. h.logRequest(r, true, 200, "vdir-http")
  121. }
  122. func (h *ProxyHandler) logRequest(r *http.Request, succ bool, statusCode int, forwardType string) {
  123. if h.Parent.Option.StatisticCollector != nil {
  124. go func() {
  125. requestInfo := statistic.RequestInfo{
  126. IpAddr: geodb.GetRequesterIP(r),
  127. RequestOriginalCountryISOCode: h.Parent.Option.GeodbStore.GetRequesterCountryISOCode(r),
  128. Succ: succ,
  129. StatusCode: statusCode,
  130. ForwardType: forwardType,
  131. }
  132. fmt.Println(requestInfo)
  133. h.Parent.Option.StatisticCollector.RecordRequest(requestInfo)
  134. }()
  135. }
  136. }