1
0

Server.go 6.9 KB

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