proxyRequestHandler.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "log"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  10. "imuslab.com/zoraxy/mod/geodb"
  11. "imuslab.com/zoraxy/mod/statistic"
  12. "imuslab.com/zoraxy/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. return true
  23. })
  24. return targetProxyEndpoint
  25. }
  26. func (router *Router) getSubdomainProxyEndpointFromHostname(hostname string) *ProxyEndpoint {
  27. var targetSubdomainEndpoint *ProxyEndpoint = nil
  28. ep, ok := router.SubdomainEndpoint.Load(hostname)
  29. if ok {
  30. targetSubdomainEndpoint = ep.(*ProxyEndpoint)
  31. }
  32. return targetSubdomainEndpoint
  33. }
  34. // Clearn URL Path (without the http:// part) replaces // in a URL to /
  35. func (router *Router) clearnURL(targetUrlOPath string) string {
  36. return strings.ReplaceAll(targetUrlOPath, "//", "/")
  37. }
  38. // Rewrite URL rewrite the prefix part of a virtual directory URL with /
  39. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  40. rewrittenURL := requestURL
  41. rewrittenURL = strings.TrimPrefix(rewrittenURL, strings.TrimSuffix(rooturl, "/"))
  42. if strings.Contains(rewrittenURL, "//") {
  43. rewrittenURL = router.clearnURL(rewrittenURL)
  44. }
  45. return rewrittenURL
  46. }
  47. // Handle subdomain request
  48. func (h *ProxyHandler) subdomainRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  49. r.Header.Set("X-Forwarded-Host", r.Host)
  50. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  51. requestURL := r.URL.String()
  52. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  53. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  54. r.Header.Set("A-Upgrade", "websocket")
  55. wsRedirectionEndpoint := target.Domain
  56. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  57. //Append / to the end of the redirection endpoint if not exists
  58. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  59. }
  60. if len(requestURL) > 0 && requestURL[:1] == "/" {
  61. //Remove starting / from request URL if exists
  62. requestURL = requestURL[1:]
  63. }
  64. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  65. if target.RequireTLS {
  66. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  67. }
  68. h.logRequest(r, true, 101, "subdomain-websocket", target.Domain)
  69. wspHandler := websocketproxy.NewProxy(u, target.SkipCertValidations)
  70. wspHandler.ServeHTTP(w, r)
  71. return
  72. }
  73. originalHostHeader := r.Host
  74. if r.URL != nil {
  75. r.Host = r.URL.Host
  76. } else {
  77. //Fallback when the upstream proxy screw something up in the header
  78. r.URL, _ = url.Parse(originalHostHeader)
  79. }
  80. err := target.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  81. ProxyDomain: target.Domain,
  82. OriginalHost: originalHostHeader,
  83. UseTLS: target.RequireTLS,
  84. PathPrefix: "",
  85. })
  86. var dnsError *net.DNSError
  87. if err != nil {
  88. if errors.As(err, &dnsError) {
  89. http.ServeFile(w, r, "./web/hosterror.html")
  90. log.Println(err.Error())
  91. h.logRequest(r, false, 404, "subdomain-http", target.Domain)
  92. } else {
  93. http.ServeFile(w, r, "./web/rperror.html")
  94. log.Println(err.Error())
  95. h.logRequest(r, false, 521, "subdomain-http", target.Domain)
  96. }
  97. }
  98. h.logRequest(r, true, 200, "subdomain-http", target.Domain)
  99. }
  100. // Handle vdir type request
  101. func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  102. rewriteURL := h.Parent.rewriteURL(target.RootOrMatchingDomain, r.RequestURI)
  103. r.URL, _ = url.Parse(rewriteURL)
  104. r.Header.Set("X-Forwarded-Host", r.Host)
  105. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  106. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  107. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  108. r.Header.Set("A-Upgrade", "websocket")
  109. wsRedirectionEndpoint := target.Domain
  110. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  111. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  112. }
  113. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  114. if target.RequireTLS {
  115. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  116. }
  117. h.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  118. wspHandler := websocketproxy.NewProxy(u, target.SkipCertValidations)
  119. wspHandler.ServeHTTP(w, r)
  120. return
  121. }
  122. originalHostHeader := r.Host
  123. if r.URL != nil {
  124. r.Host = r.URL.Host
  125. } else {
  126. //Fallback when the upstream proxy screw something up in the header
  127. r.URL, _ = url.Parse(originalHostHeader)
  128. }
  129. err := target.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  130. ProxyDomain: target.Domain,
  131. OriginalHost: originalHostHeader,
  132. UseTLS: target.RequireTLS,
  133. PathPrefix: target.RootOrMatchingDomain,
  134. })
  135. var dnsError *net.DNSError
  136. if err != nil {
  137. if errors.As(err, &dnsError) {
  138. http.ServeFile(w, r, "./web/hosterror.html")
  139. log.Println(err.Error())
  140. h.logRequest(r, false, 404, "vdir-http", target.Domain)
  141. } else {
  142. http.ServeFile(w, r, "./web/rperror.html")
  143. log.Println(err.Error())
  144. h.logRequest(r, false, 521, "vdir-http", target.Domain)
  145. }
  146. }
  147. h.logRequest(r, true, 200, "vdir-http", target.Domain)
  148. }
  149. func (h *ProxyHandler) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  150. if h.Parent.Option.StatisticCollector != nil {
  151. go func() {
  152. requestInfo := statistic.RequestInfo{
  153. IpAddr: geodb.GetRequesterIP(r),
  154. RequestOriginalCountryISOCode: h.Parent.Option.GeodbStore.GetRequesterCountryISOCode(r),
  155. Succ: succ,
  156. StatusCode: statusCode,
  157. ForwardType: forwardType,
  158. Referer: r.Referer(),
  159. UserAgent: r.UserAgent(),
  160. RequestURL: r.Host + r.RequestURI,
  161. Target: target,
  162. }
  163. h.Parent.Option.StatisticCollector.RecordRequest(requestInfo)
  164. }()
  165. }
  166. }