proxyRequestHandler.go 8.4 KB

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