Server.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package dynamicproxy
  2. import (
  3. "log"
  4. "net/http"
  5. "net/url"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "imuslab.com/zoraxy/mod/netutils"
  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. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  22. /*
  23. Special Routing Rules, bypass most of the limitations
  24. */
  25. //Check if there are external routing rule matches.
  26. //If yes, route them via external rr
  27. matchedRoutingRule := h.Parent.GetMatchingRoutingRule(r)
  28. if matchedRoutingRule != nil {
  29. //Matching routing rule found. Let the sub-router handle it
  30. matchedRoutingRule.Route(w, r)
  31. return
  32. }
  33. //Inject headers
  34. w.Header().Set("x-proxy-by", "zoraxy/"+h.Parent.Option.HostVersion)
  35. /*
  36. Redirection Routing
  37. */
  38. //Check if this is a redirection url
  39. if h.Parent.Option.RedirectRuleTable.IsRedirectable(r) {
  40. statusCode := h.Parent.Option.RedirectRuleTable.HandleRedirect(w, r)
  41. h.logRequest(r, statusCode != 500, statusCode, "redirect", "")
  42. return
  43. }
  44. /*
  45. Host Routing
  46. */
  47. //Extract request host to see if any proxy rule is matched
  48. domainOnly := r.Host
  49. if strings.Contains(r.Host, ":") {
  50. hostPath := strings.Split(r.Host, ":")
  51. domainOnly = hostPath[0]
  52. }
  53. sep := h.Parent.getProxyEndpointFromHostname(domainOnly)
  54. if sep != nil && !sep.Disabled {
  55. //Matching proxy rule found
  56. //Access Check (blacklist / whitelist)
  57. ruleID := sep.AccessFilterUUID
  58. if sep.AccessFilterUUID == "" {
  59. //Use default rule
  60. ruleID = "default"
  61. }
  62. if h.handleAccessRouting(ruleID, w, r) {
  63. //Request handled by subroute
  64. return
  65. }
  66. //Validate basic auth
  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. //Serve the not found page, use template if exists
  170. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  171. w.WriteHeader(http.StatusNotFound)
  172. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/notfound.html"))
  173. if err != nil {
  174. w.Write(page_hosterror)
  175. } else {
  176. w.Write(template)
  177. }
  178. }
  179. }
  180. // Handle access check (blacklist / whitelist), return true if request is handled (aka blocked)
  181. // if the return value is false, you can continue process the response writer
  182. func (h *ProxyHandler) handleAccessRouting(ruleID string, w http.ResponseWriter, r *http.Request) bool {
  183. accessRule, err := h.Parent.Option.AccessController.GetAccessRuleByID(ruleID)
  184. if err != nil {
  185. //Unable to load access rule. Target rule not found?
  186. log.Println("[Proxy] Unable to load access rule: " + ruleID)
  187. w.WriteHeader(http.StatusInternalServerError)
  188. w.Write([]byte("500 - Internal Server Error"))
  189. return true
  190. }
  191. //Check if this ip is in blacklist
  192. clientIpAddr := netutils.GetRequesterIP(r)
  193. if accessRule.IsBlacklisted(clientIpAddr) {
  194. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  195. w.WriteHeader(http.StatusForbidden)
  196. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/blacklist.html"))
  197. if err != nil {
  198. w.Write(page_forbidden)
  199. } else {
  200. w.Write(template)
  201. }
  202. h.logRequest(r, false, 403, "blacklist", "")
  203. return true
  204. }
  205. //Check if this ip is in whitelist
  206. if !accessRule.IsWhitelisted(clientIpAddr) {
  207. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  208. w.WriteHeader(http.StatusForbidden)
  209. template, err := os.ReadFile(filepath.Join(h.Parent.Option.WebDirectory, "templates/whitelist.html"))
  210. if err != nil {
  211. w.Write(page_forbidden)
  212. } else {
  213. w.Write(template)
  214. }
  215. h.logRequest(r, false, 403, "whitelist", "")
  216. return true
  217. }
  218. return false
  219. }