Server.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package dynamicproxy
  2. import (
  3. _ "embed"
  4. "errors"
  5. "log"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "imuslab.com/zoraxy/mod/geodb"
  12. )
  13. /*
  14. Server.go
  15. Main server for dynamic proxy core
  16. Routing Handler Priority (High to Low)
  17. - Blacklist
  18. - Whitelist
  19. - Redirectable
  20. - Subdomain Routing
  21. - Vitrual Directory Routing
  22. */
  23. var (
  24. //go:embed tld.json
  25. rawTldMap []byte
  26. )
  27. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. /*
  29. Special Routing Rules, bypass most of the limitations
  30. */
  31. //Check if there are external routing rule matches.
  32. //If yes, route them via external rr
  33. matchedRoutingRule := h.Parent.GetMatchingRoutingRule(r)
  34. if matchedRoutingRule != nil {
  35. //Matching routing rule found. Let the sub-router handle it
  36. if matchedRoutingRule.UseSystemAccessControl {
  37. //This matching rule request system access control.
  38. //check access logic
  39. respWritten := h.handleAccessRouting(w, r)
  40. if respWritten {
  41. return
  42. }
  43. }
  44. matchedRoutingRule.Route(w, r)
  45. return
  46. }
  47. /*
  48. General Access Check
  49. */
  50. respWritten := h.handleAccessRouting(w, r)
  51. if respWritten {
  52. return
  53. }
  54. /*
  55. Redirection Routing
  56. */
  57. //Check if this is a redirection url
  58. if h.Parent.Option.RedirectRuleTable.IsRedirectable(r) {
  59. statusCode := h.Parent.Option.RedirectRuleTable.HandleRedirect(w, r)
  60. h.logRequest(r, statusCode != 500, statusCode, "redirect", "")
  61. return
  62. }
  63. //Extract request host to see if it is virtual directory or subdomain
  64. domainOnly := r.Host
  65. if strings.Contains(r.Host, ":") {
  66. hostPath := strings.Split(r.Host, ":")
  67. domainOnly = hostPath[0]
  68. }
  69. /*
  70. Subdomain Routing
  71. */
  72. if strings.Contains(r.Host, ".") {
  73. //This might be a subdomain. See if there are any subdomain proxy router for this
  74. sep := h.Parent.getSubdomainProxyEndpointFromHostname(domainOnly)
  75. if sep != nil {
  76. if sep.RequireBasicAuth {
  77. err := h.handleBasicAuthRouting(w, r, sep)
  78. if err != nil {
  79. return
  80. }
  81. }
  82. h.subdomainRequest(w, r, sep)
  83. return
  84. }
  85. }
  86. /*
  87. Virtual Directory Routing
  88. */
  89. //Clean up the request URI
  90. proxyingPath := strings.TrimSpace(r.RequestURI)
  91. targetProxyEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath)
  92. if targetProxyEndpoint != nil {
  93. if targetProxyEndpoint.RequireBasicAuth {
  94. err := h.handleBasicAuthRouting(w, r, targetProxyEndpoint)
  95. if err != nil {
  96. return
  97. }
  98. }
  99. h.proxyRequest(w, r, targetProxyEndpoint)
  100. } else 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. if h.Parent.RootRoutingOptions.EnableRedirectForUnsetRules {
  128. //Route to custom domain
  129. if h.Parent.RootRoutingOptions.UnsetRuleRedirectTarget == "" {
  130. //Not set. Redirect to first level of domain redirectable
  131. fld, err := h.getTopLevelRedirectableDomain(domainOnly)
  132. if err != nil {
  133. //Redirect to proxy root
  134. h.proxyRequest(w, r, h.Parent.Root)
  135. } else {
  136. log.Println("[Router] Redirecting request from " + domainOnly + " to " + fld)
  137. h.logRequest(r, false, 307, "root-redirect", domainOnly)
  138. http.Redirect(w, r, fld, http.StatusTemporaryRedirect)
  139. }
  140. return
  141. } else if h.isTopLevelRedirectableDomain(domainOnly) {
  142. //This is requesting a top level private domain that should be serving root
  143. h.proxyRequest(w, r, h.Parent.Root)
  144. } else {
  145. //Validate the redirection target URL
  146. parsedURL, err := url.Parse(h.Parent.RootRoutingOptions.UnsetRuleRedirectTarget)
  147. if err != nil {
  148. //Error when parsing target. Send to root
  149. h.proxyRequest(w, r, h.Parent.Root)
  150. return
  151. }
  152. hostname := parsedURL.Hostname()
  153. if domainOnly != hostname {
  154. //Redirect to target
  155. h.logRequest(r, false, 307, "root-redirect", domainOnly)
  156. http.Redirect(w, r, h.Parent.RootRoutingOptions.UnsetRuleRedirectTarget, http.StatusTemporaryRedirect)
  157. return
  158. } else {
  159. //Loopback request due to bad settings (Shd leave it empty)
  160. //Forward it to root proxy
  161. h.proxyRequest(w, r, h.Parent.Root)
  162. }
  163. }
  164. } else {
  165. //Route to root
  166. h.proxyRequest(w, r, h.Parent.Root)
  167. }
  168. }
  169. // Handle access routing logic. Return true if the request is handled or blocked by the access control logic
  170. // if the return value is false, you can continue process the response writer
  171. func (h *ProxyHandler) handleAccessRouting(w http.ResponseWriter, r *http.Request) bool {
  172. //Check if this ip is in blacklist
  173. clientIpAddr := geodb.GetRequesterIP(r)
  174. if h.Parent.Option.GeodbStore.IsBlacklisted(clientIpAddr) {
  175. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  176. w.WriteHeader(http.StatusForbidden)
  177. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/blacklist.html"))
  178. if err != nil {
  179. w.Write(page_forbidden)
  180. } else {
  181. w.Write(template)
  182. }
  183. h.logRequest(r, false, 403, "blacklist", "")
  184. return true
  185. }
  186. //Check if this ip is in whitelist
  187. if !h.Parent.Option.GeodbStore.IsWhitelisted(clientIpAddr) {
  188. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  189. w.WriteHeader(http.StatusForbidden)
  190. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/whitelist.html"))
  191. if err != nil {
  192. w.Write(page_forbidden)
  193. } else {
  194. w.Write(template)
  195. }
  196. h.logRequest(r, false, 403, "whitelist", "")
  197. return true
  198. }
  199. return false
  200. }
  201. // Return if the given host is already topped (e.g. example.com or example.co.uk) instead of
  202. // a host with subdomain (e.g. test.example.com)
  203. func (h *ProxyHandler) isTopLevelRedirectableDomain(requestHost string) bool {
  204. parts := strings.Split(requestHost, ".")
  205. if len(parts) > 2 {
  206. //Cases where strange tld is used like .co.uk or .com.hk
  207. _, ok := h.Parent.tldMap[strings.Join(parts[1:], ".")]
  208. if ok {
  209. //Already topped
  210. return true
  211. }
  212. } else {
  213. //Already topped
  214. return true
  215. }
  216. return false
  217. }
  218. // GetTopLevelRedirectableDomain returns the toppest level of domain
  219. // that is redirectable. E.g. a.b.c.example.co.uk will return example.co.uk
  220. func (h *ProxyHandler) getTopLevelRedirectableDomain(unsetSubdomainHost string) (string, error) {
  221. parts := strings.Split(unsetSubdomainHost, ".")
  222. if h.isTopLevelRedirectableDomain(unsetSubdomainHost) {
  223. //Already topped
  224. return "", errors.New("already at top level domain")
  225. }
  226. for i := 0; i < len(parts); i++ {
  227. possibleTld := parts[i:]
  228. _, ok := h.Parent.tldMap[strings.Join(possibleTld, ".")]
  229. if ok {
  230. //This is tld length
  231. tld := strings.Join(parts[i-1:], ".")
  232. return "//" + tld, nil
  233. }
  234. }
  235. return "", errors.New("unsupported top level domain given")
  236. }