Server.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 && !targetProxyEndpoint.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. //Clean up the request URI
  94. proxyingPath := strings.TrimSpace(r.RequestURI)
  95. if !strings.HasSuffix(proxyingPath, "/") {
  96. potentialProxtEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath + "/")
  97. if potentialProxtEndpoint != nil {
  98. //Missing tailing slash. Redirect to target proxy endpoint
  99. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  100. } else {
  101. //Passthrough the request to root
  102. h.handleRootRouting(w, r)
  103. }
  104. } else {
  105. //No routing rules found.
  106. h.handleRootRouting(w, r)
  107. }
  108. }
  109. /*
  110. handleRootRouting
  111. This function handle root routing situations where there are no subdomain
  112. , vdir or special routing rule matches the requested URI.
  113. Once entered this routing segment, the root routing options will take over
  114. for the routing logic.
  115. */
  116. func (h *ProxyHandler) handleRootRouting(w http.ResponseWriter, r *http.Request) {
  117. domainOnly := r.Host
  118. if strings.Contains(r.Host, ":") {
  119. hostPath := strings.Split(r.Host, ":")
  120. domainOnly = hostPath[0]
  121. }
  122. //Get the proxy root config
  123. proot := h.Parent.Root
  124. switch proot.DefaultSiteOption {
  125. case DefaultSite_InternalStaticWebServer:
  126. fallthrough
  127. case DefaultSite_ReverseProxy:
  128. //They both share the same behavior
  129. //Check if any virtual directory rules matches
  130. proxyingPath := strings.TrimSpace(r.RequestURI)
  131. targetProxyEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath)
  132. if targetProxyEndpoint != nil && !targetProxyEndpoint.Disabled {
  133. //Virtual directory routing rule found. Route via vdir mode
  134. h.vdirRequest(w, r, targetProxyEndpoint)
  135. return
  136. } else if !strings.HasSuffix(proxyingPath, "/") && proot.ProxyType != ProxyType_Root {
  137. potentialProxtEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath + "/")
  138. if potentialProxtEndpoint != nil && !targetProxyEndpoint.Disabled {
  139. //Missing tailing slash. Redirect to target proxy endpoint
  140. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  141. return
  142. }
  143. }
  144. //No vdir match. Route via root router
  145. h.hostRequest(w, r, h.Parent.Root)
  146. case DefaultSite_Redirect:
  147. redirectTarget := strings.TrimSpace(proot.DefaultSiteValue)
  148. if redirectTarget == "" {
  149. redirectTarget = "about:blank"
  150. }
  151. //Check if it is an infinite loopback redirect
  152. parsedURL, err := url.Parse(proot.DefaultSiteValue)
  153. if err != nil {
  154. //Error when parsing target. Send to root
  155. h.hostRequest(w, r, h.Parent.Root)
  156. return
  157. }
  158. hostname := parsedURL.Hostname()
  159. if hostname == domainOnly {
  160. h.logRequest(r, false, 500, "root-redirect", domainOnly)
  161. http.Error(w, "Loopback redirects due to invalid settings", 500)
  162. return
  163. }
  164. h.logRequest(r, false, 307, "root-redirect", domainOnly)
  165. http.Redirect(w, r, redirectTarget, http.StatusTemporaryRedirect)
  166. case DefaultSite_NotFoundPage:
  167. //Serve the not found page, use template if exists
  168. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  169. w.WriteHeader(http.StatusNotFound)
  170. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
  171. if err != nil {
  172. w.Write(page_hosterror)
  173. } else {
  174. w.Write(template)
  175. }
  176. }
  177. }