Server.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package dynamicproxy
  2. import (
  3. "net/http"
  4. "net/url"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "imuslab.com/zoraxy/mod/netutils"
  9. )
  10. /*
  11. Server.go
  12. Main server for dynamic proxy core
  13. Routing Handler Priority (High to Low)
  14. - Blacklist
  15. - Whitelist
  16. - Redirectable
  17. - Subdomain Routing
  18. - Vitrual Directory Routing
  19. */
  20. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  21. /*
  22. Special Routing Rules, bypass most of the limitations
  23. */
  24. //Check if there are external routing rule matches.
  25. //If yes, route them via external rr
  26. matchedRoutingRule := h.Parent.GetMatchingRoutingRule(r)
  27. if matchedRoutingRule != nil {
  28. //Matching routing rule found. Let the sub-router handle it
  29. if matchedRoutingRule.UseSystemAccessControl {
  30. //This matching rule request system access control.
  31. //check access logic
  32. //TODO: Change this to routing rule's acess check
  33. respWritten := h.handleAccessRouting(w, r)
  34. if respWritten {
  35. return
  36. }
  37. }
  38. matchedRoutingRule.Route(w, r)
  39. return
  40. }
  41. //Inject headers
  42. w.Header().Set("x-proxy-by", "zoraxy/"+h.Parent.Option.HostVersion)
  43. /*
  44. General Access Check
  45. */
  46. respWritten := h.handleAccessRouting(w, r)
  47. if respWritten {
  48. return
  49. }
  50. /*
  51. Redirection Routing
  52. */
  53. //Check if this is a redirection url
  54. if h.Parent.Option.RedirectRuleTable.IsRedirectable(r) {
  55. statusCode := h.Parent.Option.RedirectRuleTable.HandleRedirect(w, r)
  56. h.logRequest(r, statusCode != 500, statusCode, "redirect", "")
  57. return
  58. }
  59. //Extract request host to see if it is virtual directory or subdomain
  60. domainOnly := r.Host
  61. if strings.Contains(r.Host, ":") {
  62. hostPath := strings.Split(r.Host, ":")
  63. domainOnly = hostPath[0]
  64. }
  65. /*
  66. Host Routing
  67. */
  68. sep := h.Parent.getProxyEndpointFromHostname(domainOnly)
  69. if sep != nil && !sep.Disabled {
  70. if sep.RequireBasicAuth {
  71. err := h.handleBasicAuthRouting(w, r, sep)
  72. if err != nil {
  73. return
  74. }
  75. }
  76. //Check if any virtual directory rules matches
  77. proxyingPath := strings.TrimSpace(r.RequestURI)
  78. targetProxyEndpoint := sep.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath)
  79. if targetProxyEndpoint != nil && !targetProxyEndpoint.Disabled {
  80. //Virtual directory routing rule found. Route via vdir mode
  81. h.vdirRequest(w, r, targetProxyEndpoint)
  82. return
  83. } else if !strings.HasSuffix(proxyingPath, "/") && sep.ProxyType != ProxyType_Root {
  84. potentialProxtEndpoint := sep.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath + "/")
  85. if potentialProxtEndpoint != nil && !targetProxyEndpoint.Disabled {
  86. //Missing tailing slash. Redirect to target proxy endpoint
  87. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  88. return
  89. }
  90. }
  91. //Fallback to handle by the host proxy forwarder
  92. h.hostRequest(w, r, sep)
  93. return
  94. }
  95. /*
  96. Root Router Handling
  97. */
  98. //Clean up the request URI
  99. proxyingPath := strings.TrimSpace(r.RequestURI)
  100. if !strings.HasSuffix(proxyingPath, "/") {
  101. potentialProxtEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath + "/")
  102. if potentialProxtEndpoint != nil {
  103. //Missing tailing slash. Redirect to target proxy endpoint
  104. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  105. } else {
  106. //Passthrough the request to root
  107. h.handleRootRouting(w, r)
  108. }
  109. } else {
  110. //No routing rules found.
  111. h.handleRootRouting(w, r)
  112. }
  113. }
  114. /*
  115. handleRootRouting
  116. This function handle root routing situations where there are no subdomain
  117. , vdir or special routing rule matches the requested URI.
  118. Once entered this routing segment, the root routing options will take over
  119. for the routing logic.
  120. */
  121. func (h *ProxyHandler) handleRootRouting(w http.ResponseWriter, r *http.Request) {
  122. domainOnly := r.Host
  123. if strings.Contains(r.Host, ":") {
  124. hostPath := strings.Split(r.Host, ":")
  125. domainOnly = hostPath[0]
  126. }
  127. //Get the proxy root config
  128. proot := h.Parent.Root
  129. switch proot.DefaultSiteOption {
  130. case DefaultSite_InternalStaticWebServer:
  131. fallthrough
  132. case DefaultSite_ReverseProxy:
  133. //They both share the same behavior
  134. //Check if any virtual directory rules matches
  135. proxyingPath := strings.TrimSpace(r.RequestURI)
  136. targetProxyEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath)
  137. if targetProxyEndpoint != nil && !targetProxyEndpoint.Disabled {
  138. //Virtual directory routing rule found. Route via vdir mode
  139. h.vdirRequest(w, r, targetProxyEndpoint)
  140. return
  141. } else if !strings.HasSuffix(proxyingPath, "/") && proot.ProxyType != ProxyType_Root {
  142. potentialProxtEndpoint := proot.GetVirtualDirectoryHandlerFromRequestURI(proxyingPath + "/")
  143. if potentialProxtEndpoint != nil && !targetProxyEndpoint.Disabled {
  144. //Missing tailing slash. Redirect to target proxy endpoint
  145. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  146. return
  147. }
  148. }
  149. //No vdir match. Route via root router
  150. h.hostRequest(w, r, h.Parent.Root)
  151. case DefaultSite_Redirect:
  152. redirectTarget := strings.TrimSpace(proot.DefaultSiteValue)
  153. if redirectTarget == "" {
  154. redirectTarget = "about:blank"
  155. }
  156. //Check if it is an infinite loopback redirect
  157. parsedURL, err := url.Parse(proot.DefaultSiteValue)
  158. if err != nil {
  159. //Error when parsing target. Send to root
  160. h.hostRequest(w, r, h.Parent.Root)
  161. return
  162. }
  163. hostname := parsedURL.Hostname()
  164. if hostname == domainOnly {
  165. h.logRequest(r, false, 500, "root-redirect", domainOnly)
  166. http.Error(w, "Loopback redirects due to invalid settings", 500)
  167. return
  168. }
  169. h.logRequest(r, false, 307, "root-redirect", domainOnly)
  170. http.Redirect(w, r, redirectTarget, http.StatusTemporaryRedirect)
  171. case DefaultSite_NotFoundPage:
  172. //Serve the not found page, use template if exists
  173. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  174. w.WriteHeader(http.StatusNotFound)
  175. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
  176. if err != nil {
  177. w.Write(page_hosterror)
  178. } else {
  179. w.Write(template)
  180. }
  181. }
  182. }
  183. // Handle access routing logic. Return true if the request is handled or blocked by the access control logic
  184. // if the return value is false, you can continue process the response writer
  185. func (h *ProxyHandler) handleAccessRouting(w http.ResponseWriter, r *http.Request) bool {
  186. //Check if this ip is in blacklist
  187. clientIpAddr := netutils.GetRequesterIP(r)
  188. if h.Parent.Option.AccessController.GlobalAccessRule.IsBlacklisted(clientIpAddr) {
  189. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  190. w.WriteHeader(http.StatusForbidden)
  191. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/blacklist.html"))
  192. if err != nil {
  193. w.Write(page_forbidden)
  194. } else {
  195. w.Write(template)
  196. }
  197. h.logRequest(r, false, 403, "blacklist", "")
  198. return true
  199. }
  200. //Check if this ip is in whitelist
  201. if !h.Parent.Option.AccessController.GlobalAccessRule.IsWhitelisted(clientIpAddr) {
  202. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  203. w.WriteHeader(http.StatusForbidden)
  204. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/whitelist.html"))
  205. if err != nil {
  206. w.Write(page_forbidden)
  207. } else {
  208. w.Write(template)
  209. }
  210. h.logRequest(r, false, 403, "whitelist", "")
  211. return true
  212. }
  213. return false
  214. }