proxyRequestHandler.go 12 KB

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