proxyRequestHandler.go 5.1 KB

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