Server.go 6.2 KB

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