proxyRequestHandler.go 8.3 KB

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