1
0

proxyRequestHandler.go 9.4 KB

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