Server.go 7.5 KB

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