Server.go 6.1 KB

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