Server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package dynamicproxy
  2. import (
  3. _ "embed"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "os"
  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.proxyRequest(w, r, h.Parent.Root)
  108. }
  109. } else {
  110. //No routing rules found.
  111. if h.Parent.RootOptions.EnableRedirectForUnsetRules {
  112. //Route to custom domain
  113. if h.Parent.RootOptions.UnsetRuleRedirectTarget == "" {
  114. //Not set. Redirect to first level of domain redirectable
  115. fld, err := h.getTopLevelRedirectableDomain(r.RequestURI)
  116. if err != nil {
  117. //Redirect to proxy root
  118. log.Println("[Router] Unable to resolve top level redirectable domain: " + err.Error())
  119. h.proxyRequest(w, r, h.Parent.Root)
  120. } else {
  121. http.Redirect(w, r, fld, http.StatusTemporaryRedirect)
  122. }
  123. return
  124. } else {
  125. //Redirect to target
  126. http.Redirect(w, r, h.Parent.RootOptions.UnsetRuleRedirectTarget, http.StatusTemporaryRedirect)
  127. return
  128. }
  129. } else {
  130. //Route to root
  131. h.proxyRequest(w, r, h.Parent.Root)
  132. }
  133. }
  134. }
  135. // Handle access routing logic. Return true if the request is handled or blocked by the access control logic
  136. // if the return value is false, you can continue process the response writer
  137. func (h *ProxyHandler) handleAccessRouting(w http.ResponseWriter, r *http.Request) bool {
  138. //Check if this ip is in blacklist
  139. clientIpAddr := geodb.GetRequesterIP(r)
  140. if h.Parent.Option.GeodbStore.IsBlacklisted(clientIpAddr) {
  141. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  142. w.WriteHeader(http.StatusForbidden)
  143. template, err := os.ReadFile("./web/forbidden.html")
  144. if err != nil {
  145. w.Write([]byte("403 - Forbidden"))
  146. } else {
  147. w.Write(template)
  148. }
  149. h.logRequest(r, false, 403, "blacklist", "")
  150. return true
  151. }
  152. //Check if this ip is in whitelist
  153. if !h.Parent.Option.GeodbStore.IsWhitelisted(clientIpAddr) {
  154. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  155. w.WriteHeader(http.StatusForbidden)
  156. template, err := os.ReadFile("./web/forbidden.html")
  157. if err != nil {
  158. w.Write([]byte("403 - Forbidden"))
  159. } else {
  160. w.Write(template)
  161. }
  162. h.logRequest(r, false, 403, "whitelist", "")
  163. return true
  164. }
  165. return false
  166. }
  167. // GetTopLevelRedirectableDomain returns the toppest level of domain
  168. // that is redirectable. E.g. a.b.c.example.co.uk will return example.co.uk
  169. func (h *ProxyHandler) getTopLevelRedirectableDomain(unsetSubdomainUri string) (string, error) {
  170. //Extract hostname from URI
  171. parsedURL, err := url.Parse(unsetSubdomainUri)
  172. if err != nil {
  173. return "", err
  174. }
  175. hostname := parsedURL.Hostname()
  176. //Generate all levels of domains
  177. //leveledDomains := []string{}
  178. chunks := strings.Split(hostname, ".")
  179. for i := len(chunks); i > 0; i-- {
  180. thisChunk := chunks[i]
  181. fmt.Println(thisChunk)
  182. }
  183. return "", errors.New("wip")
  184. }