proxyRequestHandler.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "log"
  5. "net"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  10. "imuslab.com/zoraxy/mod/geodb"
  11. "imuslab.com/zoraxy/mod/statistic"
  12. "imuslab.com/zoraxy/mod/websocketproxy"
  13. )
  14. func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
  15. var targetProxyEndpoint *ProxyEndpoint = nil
  16. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  17. rootname := key.(string)
  18. if strings.HasPrefix(requestURI, rootname) {
  19. thisProxyEndpoint := value.(*ProxyEndpoint)
  20. targetProxyEndpoint = thisProxyEndpoint
  21. }
  22. return true
  23. })
  24. return targetProxyEndpoint
  25. }
  26. func (router *Router) getSubdomainProxyEndpointFromHostname(hostname string) *ProxyEndpoint {
  27. var targetSubdomainEndpoint *ProxyEndpoint = nil
  28. ep, ok := router.SubdomainEndpoint.Load(hostname)
  29. if ok {
  30. targetSubdomainEndpoint = ep.(*ProxyEndpoint)
  31. }
  32. return targetSubdomainEndpoint
  33. }
  34. // Clearn URL Path (without the http:// part) replaces // in a URL to /
  35. func (router *Router) clearnURL(targetUrlOPath string) string {
  36. return strings.ReplaceAll(targetUrlOPath, "//", "/")
  37. }
  38. // Rewrite URL rewrite the prefix part of a virtual directory URL with /
  39. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  40. rewrittenURL := requestURL
  41. rewrittenURL = strings.TrimPrefix(rewrittenURL, strings.TrimSuffix(rooturl, "/"))
  42. if strings.Contains(rewrittenURL, "//") {
  43. rewrittenURL = router.clearnURL(rewrittenURL)
  44. }
  45. return rewrittenURL
  46. }
  47. // Handle subdomain request
  48. func (h *ProxyHandler) subdomainRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  49. r.Header.Set("X-Forwarded-Host", r.Host)
  50. requestURL := r.URL.String()
  51. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  52. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  53. r.Header.Set("A-Upgrade", "websocket")
  54. wsRedirectionEndpoint := target.Domain
  55. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  56. //Append / to the end of the redirection endpoint if not exists
  57. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  58. }
  59. if len(requestURL) > 0 && requestURL[:1] == "/" {
  60. //Remove starting / from request URL if exists
  61. requestURL = requestURL[1:]
  62. }
  63. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  64. if target.RequireTLS {
  65. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  66. }
  67. h.logRequest(r, true, 101, "subdomain-websocket", target.Domain)
  68. wspHandler := websocketproxy.NewProxy(u, target.SkipCertValidations)
  69. wspHandler.ServeHTTP(w, r)
  70. return
  71. }
  72. originalHostHeader := r.Host
  73. if r.URL != nil {
  74. r.Host = r.URL.Host
  75. } else {
  76. //Fallback when the upstream proxy screw something up in the header
  77. r.URL, _ = url.Parse(originalHostHeader)
  78. }
  79. err := target.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  80. ProxyDomain: target.Domain,
  81. OriginalHost: originalHostHeader,
  82. UseTLS: target.RequireTLS,
  83. PathPrefix: "",
  84. })
  85. var dnsError *net.DNSError
  86. if err != nil {
  87. if errors.As(err, &dnsError) {
  88. http.ServeFile(w, r, "./web/hosterror.html")
  89. log.Println(err.Error())
  90. h.logRequest(r, false, 404, "subdomain-http", target.Domain)
  91. } else {
  92. http.ServeFile(w, r, "./web/rperror.html")
  93. log.Println(err.Error())
  94. h.logRequest(r, false, 521, "subdomain-http", target.Domain)
  95. }
  96. }
  97. h.logRequest(r, true, 200, "subdomain-http", target.Domain)
  98. }
  99. // Handle vdir type request
  100. func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  101. rewriteURL := h.Parent.rewriteURL(target.RootOrMatchingDomain, r.RequestURI)
  102. r.URL, _ = url.Parse(rewriteURL)
  103. r.Header.Set("X-Forwarded-Host", r.Host)
  104. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  105. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  106. r.Header.Set("A-Upgrade", "websocket")
  107. wsRedirectionEndpoint := target.Domain
  108. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  109. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  110. }
  111. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  112. if target.RequireTLS {
  113. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  114. }
  115. h.logRequest(r, true, 101, "vdir-websocket", target.Domain)
  116. wspHandler := websocketproxy.NewProxy(u, target.SkipCertValidations)
  117. wspHandler.ServeHTTP(w, r)
  118. return
  119. }
  120. originalHostHeader := r.Host
  121. if r.URL != nil {
  122. r.Host = r.URL.Host
  123. } else {
  124. //Fallback when the upstream proxy screw something up in the header
  125. r.URL, _ = url.Parse(originalHostHeader)
  126. }
  127. err := target.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  128. ProxyDomain: target.Domain,
  129. OriginalHost: originalHostHeader,
  130. UseTLS: target.RequireTLS,
  131. PathPrefix: target.RootOrMatchingDomain,
  132. })
  133. var dnsError *net.DNSError
  134. if err != nil {
  135. if errors.As(err, &dnsError) {
  136. http.ServeFile(w, r, "./web/hosterror.html")
  137. log.Println(err.Error())
  138. h.logRequest(r, false, 404, "vdir-http", target.Domain)
  139. } else {
  140. http.ServeFile(w, r, "./web/rperror.html")
  141. log.Println(err.Error())
  142. h.logRequest(r, false, 521, "vdir-http", target.Domain)
  143. }
  144. }
  145. h.logRequest(r, true, 200, "vdir-http", target.Domain)
  146. }
  147. func (h *ProxyHandler) logRequest(r *http.Request, succ bool, statusCode int, forwardType string, target string) {
  148. if h.Parent.Option.StatisticCollector != nil {
  149. go func() {
  150. requestInfo := statistic.RequestInfo{
  151. IpAddr: geodb.GetRequesterIP(r),
  152. RequestOriginalCountryISOCode: h.Parent.Option.GeodbStore.GetRequesterCountryISOCode(r),
  153. Succ: succ,
  154. StatusCode: statusCode,
  155. ForwardType: forwardType,
  156. Referer: r.Referer(),
  157. UserAgent: r.UserAgent(),
  158. RequestURL: r.Host + r.RequestURI,
  159. Target: target,
  160. }
  161. h.Parent.Option.StatisticCollector.RecordRequest(requestInfo)
  162. }()
  163. }
  164. }