proxyRequestHandler.go 7.0 KB

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