proxyRequestHandler.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. /* Load balancing */
  101. selectedUpstream, err := h.Parent.loadBalancer.GetRequestUpstreamTarget(w, r, target.ActiveOrigins, target.UseStickySession)
  102. if err != nil {
  103. http.ServeFile(w, r, "./web/rperror.html")
  104. log.Println(err.Error())
  105. h.Parent.logRequest(r, false, 521, "subdomain-http", r.URL.Hostname())
  106. return
  107. }
  108. /* WebSocket automatic proxy */
  109. requestURL := r.URL.String()
  110. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  111. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  112. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  113. wsRedirectionEndpoint := selectedUpstream.OriginIpOrDomain
  114. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  115. //Append / to the end of the redirection endpoint if not exists
  116. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  117. }
  118. if len(requestURL) > 0 && requestURL[:1] == "/" {
  119. //Remove starting / from request URL if exists
  120. requestURL = requestURL[1:]
  121. }
  122. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  123. if selectedUpstream.RequireTLS {
  124. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  125. }
  126. h.Parent.logRequest(r, true, 101, "host-websocket", selectedUpstream.OriginIpOrDomain)
  127. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  128. SkipTLSValidation: selectedUpstream.SkipCertValidations,
  129. SkipOriginCheck: selectedUpstream.SkipWebSocketOriginCheck,
  130. Logger: h.Parent.Option.Logger,
  131. })
  132. wspHandler.ServeHTTP(w, r)
  133. return
  134. }
  135. originalHostHeader := r.Host
  136. if r.URL != nil {
  137. r.Host = r.URL.Host
  138. } else {
  139. //Fallback when the upstream proxy screw something up in the header
  140. r.URL, _ = url.Parse(originalHostHeader)
  141. }
  142. //Build downstream and upstream header rules
  143. upstreamHeaders, downstreamHeaders := target.SplitInboundOutboundHeaders()
  144. statusCode, err := selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  145. ProxyDomain: selectedUpstream.OriginIpOrDomain,
  146. OriginalHost: originalHostHeader,
  147. UseTLS: selectedUpstream.RequireTLS,
  148. NoCache: h.Parent.Option.NoCache,
  149. PathPrefix: "",
  150. UpstreamHeaders: upstreamHeaders,
  151. DownstreamHeaders: downstreamHeaders,
  152. HostHeaderOverwrite: target.RequestHostOverwrite,
  153. NoRemoveHopByHop: target.DisableHopByHopHeaderRemoval,
  154. Version: target.parent.Option.HostVersion,
  155. })
  156. var dnsError *net.DNSError
  157. if err != nil {
  158. if errors.As(err, &dnsError) {
  159. http.ServeFile(w, r, "./web/hosterror.html")
  160. log.Println(err.Error())
  161. h.Parent.logRequest(r, false, 404, "host-http", r.URL.Hostname())
  162. } else {
  163. http.ServeFile(w, r, "./web/rperror.html")
  164. log.Println(err.Error())
  165. h.Parent.logRequest(r, false, 521, "host-http", r.URL.Hostname())
  166. }
  167. }
  168. h.Parent.logRequest(r, true, statusCode, "host-http", r.URL.Hostname())
  169. }
  170. // Handle vdir type request
  171. func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, target *VirtualDirectoryEndpoint) {
  172. rewriteURL := h.Parent.rewriteURL(target.MatchingPath, r.RequestURI)
  173. r.URL, _ = url.Parse(rewriteURL)
  174. r.Header.Set("X-Forwarded-Host", r.Host)
  175. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  176. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  177. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  178. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  179. wsRedirectionEndpoint := target.Domain
  180. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  181. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  182. }
  183. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  184. if target.RequireTLS {
  185. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  186. }
  187. h.Parent.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  188. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  189. SkipTLSValidation: target.SkipCertValidations,
  190. SkipOriginCheck: true, //You should not use websocket via virtual directory. But keep this to true for compatibility
  191. Logger: h.Parent.Option.Logger,
  192. })
  193. wspHandler.ServeHTTP(w, r)
  194. return
  195. }
  196. originalHostHeader := r.Host
  197. if r.URL != nil {
  198. r.Host = r.URL.Host
  199. } else {
  200. //Fallback when the upstream proxy screw something up in the header
  201. r.URL, _ = url.Parse(originalHostHeader)
  202. }
  203. //Build downstream and upstream header rules
  204. upstreamHeaders, downstreamHeaders := target.parent.SplitInboundOutboundHeaders()
  205. statusCode, err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  206. ProxyDomain: target.Domain,
  207. OriginalHost: originalHostHeader,
  208. UseTLS: target.RequireTLS,
  209. PathPrefix: target.MatchingPath,
  210. UpstreamHeaders: upstreamHeaders,
  211. DownstreamHeaders: downstreamHeaders,
  212. HostHeaderOverwrite: target.parent.RequestHostOverwrite,
  213. Version: target.parent.parent.Option.HostVersion,
  214. })
  215. var dnsError *net.DNSError
  216. if err != nil {
  217. if errors.As(err, &dnsError) {
  218. http.ServeFile(w, r, "./web/hosterror.html")
  219. log.Println(err.Error())
  220. h.Parent.logRequest(r, false, 404, "vdir-http", target.Domain)
  221. } else {
  222. http.ServeFile(w, r, "./web/rperror.html")
  223. log.Println(err.Error())
  224. h.Parent.logRequest(r, false, 521, "vdir-http", target.Domain)
  225. }
  226. }
  227. h.Parent.logRequest(r, true, statusCode, "vdir-http", target.Domain)
  228. }
  229. // This logger collect data for the statistical analysis. For log to file logger, check the Logger and LogHTTPRequest handler
  230. func (router *Router) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  231. if router.Option.StatisticCollector != nil {
  232. go func() {
  233. requestInfo := statistic.RequestInfo{
  234. IpAddr: netutils.GetRequesterIP(r),
  235. RequestOriginalCountryISOCode: router.Option.GeodbStore.GetRequesterCountryISOCode(r),
  236. Succ: succ,
  237. StatusCode: statusCode,
  238. ForwardType: forwardType,
  239. Referer: r.Referer(),
  240. UserAgent: r.UserAgent(),
  241. RequestURL: r.Host + r.RequestURI,
  242. Target: target,
  243. }
  244. router.Option.StatisticCollector.RecordRequest(requestInfo)
  245. }()
  246. }
  247. router.Option.Logger.LogHTTPRequest(r, forwardType, statusCode)
  248. }