1
0

Server.go 6.2 KB

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