Server.go 6.2 KB

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