Server.go 6.5 KB

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