proxyRequestHandler.go 6.4 KB

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