Server.go 6.4 KB

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