Server.go 6.8 KB

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