proxyRequestHandler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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/dynamicproxy/rewrite"
  13. "imuslab.com/zoraxy/mod/netutils"
  14. "imuslab.com/zoraxy/mod/statistic"
  15. "imuslab.com/zoraxy/mod/websocketproxy"
  16. )
  17. // Check if the request URI matches any of the proxy endpoint
  18. func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
  19. var targetProxyEndpoint *ProxyEndpoint = nil
  20. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  21. rootname := key.(string)
  22. if strings.HasPrefix(requestURI, rootname) {
  23. thisProxyEndpoint := value.(*ProxyEndpoint)
  24. targetProxyEndpoint = thisProxyEndpoint
  25. }
  26. return true
  27. })
  28. return targetProxyEndpoint
  29. }
  30. // Get the proxy endpoint from hostname, which might includes checking of wildcard certificates
  31. func (router *Router) getProxyEndpointFromHostname(hostname string) *ProxyEndpoint {
  32. var targetSubdomainEndpoint *ProxyEndpoint = nil
  33. ep, ok := router.ProxyEndpoints.Load(hostname)
  34. if ok {
  35. //Exact hit
  36. targetSubdomainEndpoint = ep.(*ProxyEndpoint)
  37. if !targetSubdomainEndpoint.Disabled {
  38. return targetSubdomainEndpoint
  39. }
  40. }
  41. //No hit. Try with wildcard and alias
  42. matchProxyEndpoints := []*ProxyEndpoint{}
  43. router.ProxyEndpoints.Range(func(k, v interface{}) bool {
  44. ep := v.(*ProxyEndpoint)
  45. match, err := filepath.Match(ep.RootOrMatchingDomain, hostname)
  46. if err != nil {
  47. //Bad pattern. Skip this rule
  48. return true
  49. }
  50. if match {
  51. //Wildcard matches. Skip checking alias
  52. matchProxyEndpoints = append(matchProxyEndpoints, ep)
  53. return true
  54. }
  55. //Wildcard not match. Check for alias
  56. if ep.MatchingDomainAlias != nil && len(ep.MatchingDomainAlias) > 0 {
  57. for _, aliasDomain := range ep.MatchingDomainAlias {
  58. match, err := filepath.Match(aliasDomain, hostname)
  59. if err != nil {
  60. //Bad pattern. Skip this alias
  61. continue
  62. }
  63. if match {
  64. //This alias match
  65. matchProxyEndpoints = append(matchProxyEndpoints, ep)
  66. return true
  67. }
  68. }
  69. }
  70. return true
  71. })
  72. if len(matchProxyEndpoints) == 1 {
  73. //Only 1 match
  74. return matchProxyEndpoints[0]
  75. } else if len(matchProxyEndpoints) > 1 {
  76. //More than one match. Get the best match one
  77. sort.Slice(matchProxyEndpoints, func(i, j int) bool {
  78. return matchProxyEndpoints[i].RootOrMatchingDomain < matchProxyEndpoints[j].RootOrMatchingDomain
  79. })
  80. return matchProxyEndpoints[0]
  81. }
  82. return targetSubdomainEndpoint
  83. }
  84. // Clearn URL Path (without the http:// part) replaces // in a URL to /
  85. func (router *Router) clearnURL(targetUrlOPath string) string {
  86. return strings.ReplaceAll(targetUrlOPath, "//", "/")
  87. }
  88. // Rewrite URL rewrite the prefix part of a virtual directory URL with /
  89. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  90. rewrittenURL := requestURL
  91. rewrittenURL = strings.TrimPrefix(rewrittenURL, strings.TrimSuffix(rooturl, "/"))
  92. if strings.Contains(rewrittenURL, "//") {
  93. rewrittenURL = router.clearnURL(rewrittenURL)
  94. }
  95. return rewrittenURL
  96. }
  97. // Handle host request
  98. func (h *ProxyHandler) hostRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  99. r.Header.Set("X-Forwarded-Host", r.Host)
  100. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  101. /* Load balancing */
  102. selectedUpstream, err := h.Parent.loadBalancer.GetRequestUpstreamTarget(w, r, target.ActiveOrigins, target.UseStickySession)
  103. if err != nil {
  104. http.ServeFile(w, r, "./web/rperror.html")
  105. h.Parent.Option.Logger.PrintAndLog("proxy", "Failed to assign an upstream for this request", err)
  106. h.Parent.logRequest(r, false, 521, "subdomain-http", r.URL.Hostname())
  107. return
  108. }
  109. /* WebSocket automatic proxy */
  110. requestURL := r.URL.String()
  111. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  112. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  113. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  114. wsRedirectionEndpoint := selectedUpstream.OriginIpOrDomain
  115. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  116. //Append / to the end of the redirection endpoint if not exists
  117. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  118. }
  119. if len(requestURL) > 0 && requestURL[:1] == "/" {
  120. //Remove starting / from request URL if exists
  121. requestURL = requestURL[1:]
  122. }
  123. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  124. if selectedUpstream.RequireTLS {
  125. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  126. }
  127. h.Parent.logRequest(r, true, 101, "host-websocket", selectedUpstream.OriginIpOrDomain)
  128. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  129. SkipTLSValidation: selectedUpstream.SkipCertValidations,
  130. SkipOriginCheck: selectedUpstream.SkipWebSocketOriginCheck,
  131. Logger: h.Parent.Option.Logger,
  132. })
  133. wspHandler.ServeHTTP(w, r)
  134. return
  135. }
  136. originalHostHeader := r.Host
  137. if r.URL != nil {
  138. r.Host = r.URL.Host
  139. } else {
  140. //Fallback when the upstream proxy screw something up in the header
  141. r.URL, _ = url.Parse(originalHostHeader)
  142. }
  143. //Populate the user-defined headers with the values from the request
  144. rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, target.HeaderRewriteRules.UserDefinedHeaders)
  145. //Build downstream and upstream header rules
  146. upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
  147. UserDefinedHeaders: rewrittenUserDefinedHeaders,
  148. HSTSMaxAge: target.HeaderRewriteRules.HSTSMaxAge,
  149. HSTSIncludeSubdomains: target.ContainsWildcardName(true),
  150. EnablePermissionPolicyHeader: target.HeaderRewriteRules.EnablePermissionPolicyHeader,
  151. PermissionPolicy: target.HeaderRewriteRules.PermissionPolicy,
  152. })
  153. //Handle the request reverse proxy
  154. statusCode, err := selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  155. ProxyDomain: selectedUpstream.OriginIpOrDomain,
  156. OriginalHost: originalHostHeader,
  157. UseTLS: selectedUpstream.RequireTLS,
  158. NoCache: h.Parent.Option.NoCache,
  159. PathPrefix: "",
  160. UpstreamHeaders: upstreamHeaders,
  161. DownstreamHeaders: downstreamHeaders,
  162. HostHeaderOverwrite: target.HeaderRewriteRules.RequestHostOverwrite,
  163. NoRemoveHopByHop: target.HeaderRewriteRules.DisableHopByHopHeaderRemoval,
  164. Version: target.parent.Option.HostVersion,
  165. })
  166. var dnsError *net.DNSError
  167. if err != nil {
  168. if errors.As(err, &dnsError) {
  169. http.ServeFile(w, r, "./web/hosterror.html")
  170. h.Parent.logRequest(r, false, 404, "host-http", r.URL.Hostname())
  171. } else {
  172. http.ServeFile(w, r, "./web/rperror.html")
  173. //TODO: Take this upstream offline automatically
  174. h.Parent.logRequest(r, false, 521, "host-http", r.URL.Hostname())
  175. }
  176. }
  177. h.Parent.logRequest(r, true, statusCode, "host-http", r.URL.Hostname())
  178. }
  179. // Handle vdir type request
  180. func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, target *VirtualDirectoryEndpoint) {
  181. rewriteURL := h.Parent.rewriteURL(target.MatchingPath, r.RequestURI)
  182. r.URL, _ = url.Parse(rewriteURL)
  183. r.Header.Set("X-Forwarded-Host", r.Host)
  184. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  185. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  186. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  187. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  188. wsRedirectionEndpoint := target.Domain
  189. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  190. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  191. }
  192. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  193. if target.RequireTLS {
  194. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  195. }
  196. h.Parent.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  197. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  198. SkipTLSValidation: target.SkipCertValidations,
  199. SkipOriginCheck: true, //You should not use websocket via virtual directory. But keep this to true for compatibility
  200. Logger: h.Parent.Option.Logger,
  201. })
  202. wspHandler.ServeHTTP(w, r)
  203. return
  204. }
  205. originalHostHeader := r.Host
  206. if r.URL != nil {
  207. r.Host = r.URL.Host
  208. } else {
  209. //Fallback when the upstream proxy screw something up in the header
  210. r.URL, _ = url.Parse(originalHostHeader)
  211. }
  212. //Populate the user-defined headers with the values from the request
  213. rewrittenUserDefinedHeaders := rewrite.PopulateRequestHeaderVariables(r, target.parent.HeaderRewriteRules.UserDefinedHeaders)
  214. //Build downstream and upstream header rules, use the parent (subdomain) endpoint's headers
  215. upstreamHeaders, downstreamHeaders := rewrite.SplitUpDownStreamHeaders(&rewrite.HeaderRewriteOptions{
  216. UserDefinedHeaders: rewrittenUserDefinedHeaders,
  217. HSTSMaxAge: target.parent.HeaderRewriteRules.HSTSMaxAge,
  218. HSTSIncludeSubdomains: target.parent.ContainsWildcardName(true),
  219. EnablePermissionPolicyHeader: target.parent.HeaderRewriteRules.EnablePermissionPolicyHeader,
  220. PermissionPolicy: target.parent.HeaderRewriteRules.PermissionPolicy,
  221. })
  222. //Handle the virtual directory reverse proxy request
  223. statusCode, err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  224. ProxyDomain: target.Domain,
  225. OriginalHost: originalHostHeader,
  226. UseTLS: target.RequireTLS,
  227. PathPrefix: target.MatchingPath,
  228. UpstreamHeaders: upstreamHeaders,
  229. DownstreamHeaders: downstreamHeaders,
  230. HostHeaderOverwrite: target.parent.HeaderRewriteRules.RequestHostOverwrite,
  231. Version: target.parent.parent.Option.HostVersion,
  232. })
  233. var dnsError *net.DNSError
  234. if err != nil {
  235. if errors.As(err, &dnsError) {
  236. http.ServeFile(w, r, "./web/hosterror.html")
  237. log.Println(err.Error())
  238. h.Parent.logRequest(r, false, 404, "vdir-http", target.Domain)
  239. } else {
  240. http.ServeFile(w, r, "./web/rperror.html")
  241. log.Println(err.Error())
  242. h.Parent.logRequest(r, false, 521, "vdir-http", target.Domain)
  243. }
  244. }
  245. h.Parent.logRequest(r, true, statusCode, "vdir-http", target.Domain)
  246. }
  247. // This logger collect data for the statistical analysis. For log to file logger, check the Logger and LogHTTPRequest handler
  248. func (router *Router) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  249. if router.Option.StatisticCollector != nil {
  250. go func() {
  251. requestInfo := statistic.RequestInfo{
  252. IpAddr: netutils.GetRequesterIP(r),
  253. RequestOriginalCountryISOCode: router.Option.GeodbStore.GetRequesterCountryISOCode(r),
  254. Succ: succ,
  255. StatusCode: statusCode,
  256. ForwardType: forwardType,
  257. Referer: r.Referer(),
  258. UserAgent: r.UserAgent(),
  259. RequestURL: r.Host + r.RequestURI,
  260. Target: target,
  261. }
  262. router.Option.StatisticCollector.RecordRequest(requestInfo)
  263. }()
  264. }
  265. router.Option.Logger.LogHTTPRequest(r, forwardType, statusCode)
  266. }