proxyRequestHandler.go 7.6 KB

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