proxyRequestHandler.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. /*
  23. if len(requestURI) >= len(rootname) && requestURI[:len(rootname)] == rootname {
  24. thisProxyEndpoint := value.(*ProxyEndpoint)
  25. targetProxyEndpoint = thisProxyEndpoint
  26. }
  27. */
  28. return true
  29. })
  30. return targetProxyEndpoint
  31. }
  32. func (router *Router) getSubdomainProxyEndpointFromHostname(hostname string) *SubdomainEndpoint {
  33. var targetSubdomainEndpoint *SubdomainEndpoint = nil
  34. ep, ok := router.SubdomainEndpoint.Load(hostname)
  35. if ok {
  36. targetSubdomainEndpoint = ep.(*SubdomainEndpoint)
  37. }
  38. return targetSubdomainEndpoint
  39. }
  40. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  41. rewrittenURL := requestURL
  42. rewrittenURL = strings.TrimPrefix(rewrittenURL, strings.TrimSuffix(rooturl, "/"))
  43. return rewrittenURL
  44. }
  45. func (h *ProxyHandler) subdomainRequest(w http.ResponseWriter, r *http.Request, target *SubdomainEndpoint) {
  46. r.Header.Set("X-Forwarded-Host", r.Host)
  47. requestURL := r.URL.String()
  48. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  49. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  50. r.Header.Set("A-Upgrade", "websocket")
  51. wsRedirectionEndpoint := target.Domain
  52. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  53. //Append / to the end of the redirection endpoint if not exists
  54. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  55. }
  56. if len(requestURL) > 0 && requestURL[:1] == "/" {
  57. //Remove starting / from request URL if exists
  58. requestURL = requestURL[1:]
  59. }
  60. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + requestURL)
  61. if target.RequireTLS {
  62. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + requestURL)
  63. }
  64. h.logRequest(r, true, 101, "subdomain-websocket")
  65. wspHandler := websocketproxy.NewProxy(u)
  66. wspHandler.ServeHTTP(w, r)
  67. return
  68. }
  69. r.Host = r.URL.Host
  70. err := target.Proxy.ServeHTTP(w, r)
  71. var dnsError *net.DNSError
  72. if err != nil {
  73. if errors.As(err, &dnsError) {
  74. http.ServeFile(w, r, "./web/hosterror.html")
  75. log.Println(err.Error())
  76. h.logRequest(r, false, 404, "subdomain-http")
  77. } else {
  78. http.ServeFile(w, r, "./web/rperror.html")
  79. log.Println(err.Error())
  80. h.logRequest(r, false, 521, "subdomain-http")
  81. }
  82. }
  83. h.logRequest(r, true, 200, "subdomain-http")
  84. }
  85. func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  86. rewriteURL := h.Parent.rewriteURL(target.Root, r.RequestURI)
  87. r.URL, _ = url.Parse(rewriteURL)
  88. r.Header.Set("X-Forwarded-Host", r.Host)
  89. if r.Header["Upgrade"] != nil && strings.ToLower(r.Header["Upgrade"][0]) == "websocket" {
  90. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  91. r.Header.Set("A-Upgrade", "websocket")
  92. wsRedirectionEndpoint := target.Domain
  93. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  94. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  95. }
  96. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  97. if target.RequireTLS {
  98. u, _ = url.Parse("wss://" + wsRedirectionEndpoint + r.URL.String())
  99. }
  100. h.logRequest(r, true, 101, "vdir-websocket")
  101. wspHandler := websocketproxy.NewProxy(u)
  102. wspHandler.ServeHTTP(w, r)
  103. return
  104. }
  105. originalHostHeader := r.Host
  106. r.Host = r.URL.Host
  107. err := target.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  108. ProxyDomain: target.Domain,
  109. OriginalHost: originalHostHeader,
  110. UseTLS: target.RequireTLS,
  111. PathPrefix: target.Root,
  112. })
  113. var dnsError *net.DNSError
  114. if err != nil {
  115. if errors.As(err, &dnsError) {
  116. http.ServeFile(w, r, "./web/hosterror.html")
  117. log.Println(err.Error())
  118. h.logRequest(r, false, 404, "vdir-http")
  119. } else {
  120. http.ServeFile(w, r, "./web/rperror.html")
  121. log.Println(err.Error())
  122. h.logRequest(r, false, 521, "vdir-http")
  123. }
  124. }
  125. h.logRequest(r, true, 200, "vdir-http")
  126. }
  127. func (h *ProxyHandler) logRequest(r *http.Request, succ bool, statusCode int, forwardType string) {
  128. if h.Parent.Option.StatisticCollector != nil {
  129. go func() {
  130. requestInfo := statistic.RequestInfo{
  131. IpAddr: geodb.GetRequesterIP(r),
  132. RequestOriginalCountryISOCode: h.Parent.Option.GeodbStore.GetRequesterCountryISOCode(r),
  133. Succ: succ,
  134. StatusCode: statusCode,
  135. ForwardType: forwardType,
  136. Referer: r.Referer(),
  137. UserAgent: r.UserAgent(),
  138. RequestURL: r.Host + r.RequestURI,
  139. }
  140. h.Parent.Option.StatisticCollector.RecordRequest(requestInfo)
  141. }()
  142. }
  143. }