Server.go 6.9 KB

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