proxyRequestHandler.go 9.0 KB

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