Server.go 6.9 KB

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