proxyRequestHandler.go 12 KB

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