proxyRequestHandler.go 8.1 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. 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. if len(target.UserDefinedHeaders) > 0 {
  132. for _, customHeader := range target.UserDefinedHeaders {
  133. r.Header.Set(customHeader.Key, customHeader.Value)
  134. }
  135. }
  136. err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  137. ProxyDomain: target.Domain,
  138. OriginalHost: originalHostHeader,
  139. UseTLS: target.RequireTLS,
  140. NoCache: h.Parent.Option.NoCache,
  141. PathPrefix: "",
  142. })
  143. var dnsError *net.DNSError
  144. if err != nil {
  145. if errors.As(err, &dnsError) {
  146. http.ServeFile(w, r, "./web/hosterror.html")
  147. log.Println(err.Error())
  148. h.logRequest(r, false, 404, "subdomain-http", target.Domain)
  149. } else {
  150. http.ServeFile(w, r, "./web/rperror.html")
  151. log.Println(err.Error())
  152. h.logRequest(r, false, 521, "subdomain-http", target.Domain)
  153. }
  154. }
  155. h.logRequest(r, true, 200, "subdomain-http", target.Domain)
  156. }
  157. // Handle vdir type request
  158. func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, target *VirtualDirectoryEndpoint) {
  159. rewriteURL := h.Parent.rewriteURL(target.MatchingPath, r.RequestURI)
  160. r.URL, _ = url.Parse(rewriteURL)
  161. r.Header.Set("X-Forwarded-Host", r.Host)
  162. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  163. //Inject custom headers
  164. if len(target.parent.UserDefinedHeaders) > 0 {
  165. for _, customHeader := range target.parent.UserDefinedHeaders {
  166. r.Header.Set(customHeader.Key, customHeader.Value)
  167. }
  168. }
  169. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  170. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  171. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  172. wsRedirectionEndpoint := target.Domain
  173. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  174. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  175. }
  176. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  177. if target.RequireTLS {
  178. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  179. }
  180. h.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  181. wspHandler := websocketproxy.NewProxy(u, websocketproxy.Options{
  182. SkipTLSValidation: target.SkipCertValidations,
  183. SkipOriginCheck: target.parent.SkipWebSocketOriginCheck,
  184. })
  185. wspHandler.ServeHTTP(w, r)
  186. return
  187. }
  188. originalHostHeader := r.Host
  189. if r.URL != nil {
  190. r.Host = r.URL.Host
  191. } else {
  192. //Fallback when the upstream proxy screw something up in the header
  193. r.URL, _ = url.Parse(originalHostHeader)
  194. }
  195. err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  196. ProxyDomain: target.Domain,
  197. OriginalHost: originalHostHeader,
  198. UseTLS: target.RequireTLS,
  199. PathPrefix: target.MatchingPath,
  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. }