proxyRequestHandler.go 9.6 KB

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