Server.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package dynamicproxy
  2. import (
  3. "net/http"
  4. "net/url"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. )
  9. /*
  10. Server.go
  11. Main server for dynamic proxy core
  12. Routing Handler Priority (High to Low)
  13. - Blacklist
  14. - Whitelist
  15. - Redirectable
  16. - Subdomain Routing
  17. - Vitrual Directory Routing
  18. */
  19. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  20. /*
  21. Special Routing Rules, bypass most of the limitations
  22. */
  23. //Check if there are external routing rule matches.
  24. //If yes, route them via external rr
  25. matchedRoutingRule := h.Parent.GetMatchingRoutingRule(r)
  26. if matchedRoutingRule != nil {
  27. //Matching routing rule found. Let the sub-router handle it
  28. matchedRoutingRule.Route(w, r)
  29. return
  30. }
  31. //Inject headers
  32. w.Header().Set("x-proxy-by", "zoraxy/"+h.Parent.Option.HostVersion)
  33. /*
  34. Redirection Routing
  35. */
  36. //Check if this is a redirection url
  37. if h.Parent.Option.RedirectRuleTable.IsRedirectable(r) {
  38. statusCode := h.Parent.Option.RedirectRuleTable.HandleRedirect(w, r)
  39. h.logRequest(r, statusCode != 500, statusCode, "redirect", "")
  40. return
  41. }
  42. /*
  43. Host Routing
  44. */
  45. //Extract request host to see if any proxy rule is matched
  46. domainOnly := r.Host
  47. if strings.Contains(r.Host, ":") {
  48. hostPath := strings.Split(r.Host, ":")
  49. domainOnly = hostPath[0]
  50. }
  51. sep := h.Parent.getProxyEndpointFromHostname(domainOnly)
  52. if sep != nil && !sep.Disabled {
  53. //Matching proxy rule found
  54. //Access Check (blacklist / whitelist)
  55. ruleID := sep.AccessFilterUUID
  56. if sep.AccessFilterUUID == "" {
  57. //Use default rule
  58. ruleID = "default"
  59. }
  60. if h.handleAccessRouting(ruleID, w, r) {
  61. //Request handled by subroute
  62. return
  63. }
  64. //Validate basic auth
  65. if sep.RequireBasicAuth {
  66. err := h.handleBasicAuthRouting(w, r, sep)
  67. if err != nil {
  68. return
  69. }
  70. }
  71. //Check if any virtual directory rules matches
  72. proxyingPath := strings.TrimSpace(r.RequestURI)
  73. targetProxyEndpoint := sep.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath)
  74. if targetProxyEndpoint != nil && !targetProxyEndpoint.Disabled {
  75. //Virtual directory routing rule found. Route via vdir mode
  76. h.vdirRequest(w, r, targetProxyEndpoint)
  77. return
  78. } else if !strings.HasSuffix(proxyingPath, "/") && sep.ProxyType != ProxyType_Root {
  79. potentialProxtEndpoint := sep.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath + "/")
  80. if potentialProxtEndpoint != nil && !potentialProxtEndpoint.Disabled {
  81. //Missing tailing slash. Redirect to target proxy endpoint
  82. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  83. return
  84. }
  85. }
  86. //Fallback to handle by the host proxy forwarder
  87. h.hostRequest(w, r, sep)
  88. return
  89. }
  90. /*
  91. Root Router Handling
  92. */
  93. //Root access control based on default rule
  94. blocked := h.handleAccessRouting("default", w, r)
  95. if blocked {
  96. return
  97. }
  98. //Clean up the request URI
  99. proxyingPath := strings.TrimSpace(r.RequestURI)
  100. if !strings.HasSuffix(proxyingPath, "/") {
  101. potentialProxtEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath + "/")
  102. if potentialProxtEndpoint != nil {
  103. //Missing tailing slash. Redirect to target proxy endpoint
  104. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  105. } else {
  106. //Passthrough the request to root
  107. h.handleRootRouting(w, r)
  108. }
  109. } else {
  110. //No routing rules found.
  111. h.handleRootRouting(w, r)
  112. }
  113. }
  114. /*
  115. handleRootRouting
  116. This function handle root routing situations where there are no subdomain
  117. , vdir or special routing rule matches the requested URI.
  118. Once entered this routing segment, the root routing options will take over
  119. for the routing logic.
  120. */
  121. func (h *ProxyHandler) handleRootRouting(w http.ResponseWriter, r *http.Request) {
  122. domainOnly := r.Host
  123. if strings.Contains(r.Host, ":") {
  124. hostPath := strings.Split(r.Host, ":")
  125. domainOnly = hostPath[0]
  126. }
  127. //Get the proxy root config
  128. proot := h.Parent.Root
  129. switch proot.DefaultSiteOption {
  130. case DefaultSite_InternalStaticWebServer:
  131. fallthrough
  132. case DefaultSite_ReverseProxy:
  133. //They both share the same behavior
  134. //Check if any virtual directory rules matches
  135. proxyingPath := strings.TrimSpace(r.RequestURI)
  136. targetProxyEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath)
  137. if targetProxyEndpoint != nil && !targetProxyEndpoint.Disabled {
  138. //Virtual directory routing rule found. Route via vdir mode
  139. h.vdirRequest(w, r, targetProxyEndpoint)
  140. return
  141. } else if !strings.HasSuffix(proxyingPath, "/") && proot.ProxyType != ProxyType_Root {
  142. potentialProxtEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath + "/")
  143. if potentialProxtEndpoint != nil && !targetProxyEndpoint.Disabled {
  144. //Missing tailing slash. Redirect to target proxy endpoint
  145. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  146. return
  147. }
  148. }
  149. //No vdir match. Route via root router
  150. h.hostRequest(w, r, h.Parent.Root)
  151. case DefaultSite_Redirect:
  152. redirectTarget := strings.TrimSpace(proot.DefaultSiteValue)
  153. if redirectTarget == "" {
  154. redirectTarget = "about:blank"
  155. }
  156. //Check if it is an infinite loopback redirect
  157. parsedURL, err := url.Parse(proot.DefaultSiteValue)
  158. if err != nil {
  159. //Error when parsing target. Send to root
  160. h.hostRequest(w, r, h.Parent.Root)
  161. return
  162. }
  163. hostname := parsedURL.Hostname()
  164. if hostname == domainOnly {
  165. h.logRequest(r, false, 500, "root-redirect", domainOnly)
  166. http.Error(w, "Loopback redirects due to invalid settings", 500)
  167. return
  168. }
  169. h.logRequest(r, false, 307, "root-redirect", domainOnly)
  170. http.Redirect(w, r, redirectTarget, http.StatusTemporaryRedirect)
  171. case DefaultSite_NotFoundPage:
  172. //Serve the not found page, use template if exists
  173. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  174. w.WriteHeader(http.StatusNotFound)
  175. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
  176. if err != nil {
  177. w.Write(page_hosterror)
  178. } else {
  179. w.Write(template)
  180. }
  181. }
  182. }