1
0

proxyRequestHandler.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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, target.SkipCertValidations)
  104. wspHandler.ServeHTTP(w, r)
  105. return
  106. }
  107. originalHostHeader := r.Host
  108. if r.URL != nil {
  109. r.Host = r.URL.Host
  110. } else {
  111. //Fallback when the upstream proxy screw something up in the header
  112. r.URL, _ = url.Parse(originalHostHeader)
  113. }
  114. err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  115. ProxyDomain: target.Domain,
  116. OriginalHost: originalHostHeader,
  117. UseTLS: target.RequireTLS,
  118. NoCache: h.Parent.Option.NoCache,
  119. PathPrefix: "",
  120. })
  121. var dnsError *net.DNSError
  122. if err != nil {
  123. if errors.As(err, &dnsError) {
  124. http.ServeFile(w, r, "./web/hosterror.html")
  125. log.Println(err.Error())
  126. h.logRequest(r, false, 404, "subdomain-http", target.Domain)
  127. } else {
  128. http.ServeFile(w, r, "./web/rperror.html")
  129. log.Println(err.Error())
  130. h.logRequest(r, false, 521, "subdomain-http", target.Domain)
  131. }
  132. }
  133. h.logRequest(r, true, 200, "subdomain-http", target.Domain)
  134. }
  135. // Handle vdir type request
  136. func (h *ProxyHandler) vdirRequest(w http.ResponseWriter, r *http.Request, target *VirtualDirectoryEndpoint) {
  137. rewriteURL := h.Parent.rewriteURL(target.MatchingPath, r.RequestURI)
  138. r.URL, _ = url.Parse(rewriteURL)
  139. r.Header.Set("X-Forwarded-Host", r.Host)
  140. r.Header.Set("X-Forwarded-Server", "zoraxy-"+h.Parent.Option.HostUUID)
  141. //Inject custom headers
  142. if len(target.parent.UserDefinedHeaders) > 0 {
  143. for _, customHeader := range target.parent.UserDefinedHeaders {
  144. r.Header.Set(customHeader.Key, customHeader.Value)
  145. }
  146. }
  147. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  148. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  149. r.Header.Set("Zr-Origin-Upgrade", "websocket")
  150. wsRedirectionEndpoint := target.Domain
  151. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  152. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  153. }
  154. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  155. if target.RequireTLS {
  156. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  157. }
  158. h.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  159. wspHandler := websocketproxy.NewProxy(u, target.SkipCertValidations)
  160. wspHandler.ServeHTTP(w, r)
  161. return
  162. }
  163. originalHostHeader := r.Host
  164. if r.URL != nil {
  165. r.Host = r.URL.Host
  166. } else {
  167. //Fallback when the upstream proxy screw something up in the header
  168. r.URL, _ = url.Parse(originalHostHeader)
  169. }
  170. err := target.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  171. ProxyDomain: target.Domain,
  172. OriginalHost: originalHostHeader,
  173. UseTLS: target.RequireTLS,
  174. PathPrefix: target.MatchingPath,
  175. })
  176. var dnsError *net.DNSError
  177. if err != nil {
  178. if errors.As(err, &dnsError) {
  179. http.ServeFile(w, r, "./web/hosterror.html")
  180. log.Println(err.Error())
  181. h.logRequest(r, false, 404, "vdir-http", target.Domain)
  182. } else {
  183. http.ServeFile(w, r, "./web/rperror.html")
  184. log.Println(err.Error())
  185. h.logRequest(r, false, 521, "vdir-http", target.Domain)
  186. }
  187. }
  188. h.logRequest(r, true, 200, "vdir-http", target.Domain)
  189. }
  190. func (h *ProxyHandler) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  191. if h.Parent.Option.StatisticCollector != nil {
  192. go func() {
  193. requestInfo := statistic.RequestInfo{
  194. IpAddr: geodb.GetRequesterIP(r),
  195. RequestOriginalCountryISOCode: h.Parent.Option.GeodbStore.GetRequesterCountryISOCode(r),
  196. Succ: succ,
  197. StatusCode: statusCode,
  198. ForwardType: forwardType,
  199. Referer: r.Referer(),
  200. UserAgent: r.UserAgent(),
  201. RequestURL: r.Host + r.RequestURI,
  202. Target: target,
  203. }
  204. h.Parent.Option.StatisticCollector.RecordRequest(requestInfo)
  205. }()
  206. }
  207. }