proxyRequestHandler.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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, "host-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. HostHeaderOverwrite: target.RequestHostOverwrite,
  150. NoRemoveHopByHop: target.DisableHopByHopHeaderRemoval,
  151. Version: target.parent.Option.HostVersion,
  152. })
  153. var dnsError *net.DNSError
  154. if err != nil {
  155. if errors.As(err, &dnsError) {
  156. http.ServeFile(w, r, "./web/hosterror.html")
  157. log.Println(err.Error())
  158. h.Parent.logRequest(r, false, 404, "host-http", r.URL.Hostname())
  159. } else {
  160. http.ServeFile(w, r, "./web/rperror.html")
  161. log.Println(err.Error())
  162. h.Parent.logRequest(r, false, 521, "host-http", r.URL.Hostname())
  163. }
  164. }
  165. h.Parent.logRequest(r, true, 200, "host-http", r.URL.Hostname())
  166. }
  167. // Handle vdir type request
  168. func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, target *VirtualDirectoryEndpoint) {
  169. rewriteURL := h.Parent.rewriteURL(target.MatchingPath, r.RequestURI)
  170. r.URL, _ = url.Parse(rewriteURL)
  171. r.Header.Set("X-Forwarded-Host", r.Host)
  172. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  173. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  174. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  175. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  176. wsRedirectionEndpoint := target.Domain
  177. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  178. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  179. }
  180. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  181. if target.RequireTLS {
  182. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  183. }
  184. h.Parent.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  185. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  186. SkipTLSValidation: target.SkipCertValidations,
  187. SkipOriginCheck: true, //You should not use websocket via virtual directory. But keep this to true for compatibility
  188. })
  189. wspHandler.ServeHTTP(w, r)
  190. return
  191. }
  192. originalHostHeader := r.Host
  193. if r.URL != nil {
  194. r.Host = r.URL.Host
  195. } else {
  196. //Fallback when the upstream proxy screw something up in the header
  197. r.URL, _ = url.Parse(originalHostHeader)
  198. }
  199. //Build downstream and upstream header rules
  200. upstreamHeaders, downstreamHeaders := target.parent.SplitInboundOutboundHeaders()
  201. err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  202. ProxyDomain: target.Domain,
  203. OriginalHost: originalHostHeader,
  204. UseTLS: target.RequireTLS,
  205. PathPrefix: target.MatchingPath,
  206. UpstreamHeaders: upstreamHeaders,
  207. DownstreamHeaders: downstreamHeaders,
  208. HostHeaderOverwrite: target.parent.RequestHostOverwrite,
  209. Version: target.parent.parent.Option.HostVersion,
  210. })
  211. var dnsError *net.DNSError
  212. if err != nil {
  213. if errors.As(err, &dnsError) {
  214. http.ServeFile(w, r, "./web/hosterror.html")
  215. log.Println(err.Error())
  216. h.Parent.logRequest(r, false, 404, "vdir-http", target.Domain)
  217. } else {
  218. http.ServeFile(w, r, "./web/rperror.html")
  219. log.Println(err.Error())
  220. h.Parent.logRequest(r, false, 521, "vdir-http", target.Domain)
  221. }
  222. }
  223. h.Parent.logRequest(r, true, 200, "vdir-http", target.Domain)
  224. }
  225. // This logger collect data for the statistical analysis. For log to file logger, check the Logger and LogHTTPRequest handler
  226. func (router *Router) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  227. if router.Option.StatisticCollector != nil {
  228. go func() {
  229. requestInfo := statistic.RequestInfo{
  230. IpAddr: netutils.GetRequesterIP(r),
  231. RequestOriginalCountryISOCode: router.Option.GeodbStore.GetRequesterCountryISOCode(r),
  232. Succ: succ,
  233. StatusCode: statusCode,
  234. ForwardType: forwardType,
  235. Referer: r.Referer(),
  236. UserAgent: r.UserAgent(),
  237. RequestURL: r.Host + r.RequestURI,
  238. Target: target,
  239. }
  240. router.Option.StatisticCollector.RecordRequest(requestInfo)
  241. }()
  242. }
  243. router.Option.Logger.LogHTTPRequest(r, forwardType, statusCode)
  244. }