Server.go 6.9 KB

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