typedef.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package dynamicproxy
  2. import (
  3. _ "embed"
  4. "net"
  5. "net/http"
  6. "sync"
  7. "imuslab.com/zoraxy/mod/access"
  8. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  9. "imuslab.com/zoraxy/mod/dynamicproxy/loadbalance"
  10. "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
  11. "imuslab.com/zoraxy/mod/dynamicproxy/redirection"
  12. "imuslab.com/zoraxy/mod/geodb"
  13. "imuslab.com/zoraxy/mod/info/logger"
  14. "imuslab.com/zoraxy/mod/statistic"
  15. "imuslab.com/zoraxy/mod/tlscert"
  16. )
  17. const (
  18. ProxyType_Root = 0
  19. ProxyType_Host = 1
  20. ProxyType_Vdir = 2
  21. )
  22. type ProxyHandler struct {
  23. Parent *Router
  24. }
  25. /* Router Object Options */
  26. type RouterOption struct {
  27. HostUUID string //The UUID of Zoraxy, use for heading mod
  28. HostVersion string //The version of Zoraxy, use for heading mod
  29. Port int //Incoming port
  30. UseTls bool //Use TLS to serve incoming requsts
  31. ForceTLSLatest bool //Force TLS1.2 or above
  32. NoCache bool //Force set Cache-Control: no-store
  33. ListenOnPort80 bool //Enable port 80 http listener
  34. ForceHttpsRedirect bool //Force redirection of http to https endpoint
  35. TlsManager *tlscert.Manager //TLS manager for serving SAN certificates
  36. RedirectRuleTable *redirection.RuleTable //Redirection rules handler and table
  37. GeodbStore *geodb.Store //GeoIP resolver
  38. AccessController *access.Controller //Blacklist / whitelist controller
  39. StatisticCollector *statistic.Collector //Statistic collector for storing stats on incoming visitors
  40. WebDirectory string //The static web server directory containing the templates folder
  41. LoadBalancer *loadbalance.RouteManager //Load balancer that handle load balancing of proxy target
  42. Logger *logger.Logger //Logger for reverse proxy requets
  43. }
  44. /* Router Object */
  45. type Router struct {
  46. Option *RouterOption
  47. ProxyEndpoints *sync.Map
  48. Running bool
  49. Root *ProxyEndpoint
  50. mux http.Handler
  51. server *http.Server
  52. tlsListener net.Listener
  53. loadBalancer *loadbalance.RouteManager //Load balancer routing manager
  54. routingRules []*RoutingRule
  55. tlsRedirectStop chan bool //Stop channel for tls redirection server
  56. rateLimterStop chan bool //Stop channel for rate limiter
  57. rateLimitCounter RequestCountPerIpTable //Request counter for rate limter
  58. }
  59. /* Basic Auth Related Data structure*/
  60. // Auth credential for basic auth on certain endpoints
  61. type BasicAuthCredentials struct {
  62. Username string
  63. PasswordHash string
  64. }
  65. // Auth credential for basic auth on certain endpoints
  66. type BasicAuthUnhashedCredentials struct {
  67. Username string
  68. Password string
  69. }
  70. // Paths to exclude in basic auth enabled proxy handler
  71. type BasicAuthExceptionRule struct {
  72. PathPrefix string
  73. }
  74. /* Custom Header Related Data structure */
  75. // Header injection direction type
  76. type HeaderDirection int
  77. const (
  78. HeaderDirection_ZoraxyToUpstream HeaderDirection = 0 //Inject (or remove) header to request out-going from Zoraxy to backend server
  79. HeaderDirection_ZoraxyToDownstream HeaderDirection = 1 //Inject (or remove) header to request out-going from Zoraxy to client (e.g. browser)
  80. )
  81. // User defined headers to add into a proxy endpoint
  82. type UserDefinedHeader struct {
  83. Direction HeaderDirection
  84. Key string
  85. Value string
  86. IsRemove bool //Instead of set, remove this key instead
  87. }
  88. /* Routing Rule Data Structures */
  89. // A Virtual Directory endpoint, provide a subset of ProxyEndpoint for better
  90. // program structure than directly using ProxyEndpoint
  91. type VirtualDirectoryEndpoint struct {
  92. MatchingPath string //Matching prefix of the request path, also act as key
  93. Domain string //Domain or IP to proxy to
  94. RequireTLS bool //Target domain require TLS
  95. SkipCertValidations bool //Set to true to accept self signed certs
  96. Disabled bool //If the rule is enabled
  97. proxy *dpcore.ReverseProxy `json:"-"`
  98. parent *ProxyEndpoint `json:"-"`
  99. }
  100. // A proxy endpoint record, a general interface for handling inbound routing
  101. type ProxyEndpoint struct {
  102. ProxyType int //The type of this proxy, see const def
  103. RootOrMatchingDomain string //Matching domain for host, also act as key
  104. MatchingDomainAlias []string //A list of domains that alias to this rule
  105. ActiveOrigins []*loadbalance.Upstream //Activated Upstream or origin servers IP or domain to proxy to
  106. InactiveOrigins []*loadbalance.Upstream //Disabled Upstream or origin servers IP or domain to proxy to
  107. UseStickySession bool //Use stick session for load balancing
  108. UseActiveLoadBalance bool //Use active loadbalancing, default passive
  109. Disabled bool //If the rule is disabled
  110. //Inbound TLS/SSL Related
  111. BypassGlobalTLS bool //Bypass global TLS setting options if TLS Listener enabled (parent.tlsListener != nil)
  112. //Virtual Directories
  113. VirtualDirectories []*VirtualDirectoryEndpoint
  114. //Custom Headers
  115. UserDefinedHeaders []*UserDefinedHeader //Custom headers to append when proxying requests from this endpoint
  116. RequestHostOverwrite string //If not empty, this domain will be used to overwrite the Host field in request header
  117. HSTSMaxAge int64 //HSTS max age, set to 0 for disable HSTS headers
  118. EnablePermissionPolicyHeader bool //Enable injection of permission policy header
  119. PermissionPolicy *permissionpolicy.PermissionsPolicy //Permission policy header
  120. DisableHopByHopHeaderRemoval bool //Do not remove hop-by-hop headers
  121. //Authentication
  122. RequireBasicAuth bool //Set to true to request basic auth before proxy
  123. BasicAuthCredentials []*BasicAuthCredentials //Basic auth credentials
  124. BasicAuthExceptionRules []*BasicAuthExceptionRule //Path to exclude in a basic auth enabled proxy target
  125. // Rate Limiting
  126. RequireRateLimit bool
  127. RateLimit int64 // Rate limit in requests per second
  128. //Access Control
  129. AccessFilterUUID string //Access filter ID
  130. //Fallback routing logic (Special Rule Sets Only)
  131. DefaultSiteOption int //Fallback routing logic options
  132. DefaultSiteValue string //Fallback routing target, optional
  133. //Internal Logic Elements
  134. parent *Router `json:"-"`
  135. }
  136. /*
  137. Routing type specific interface
  138. These are options that only avaible for a specific interface
  139. when running, these are converted into "ProxyEndpoint" objects
  140. for more generic routing logic
  141. */
  142. // Root options are those that are required for reverse proxy handler to work
  143. const (
  144. DefaultSite_InternalStaticWebServer = 0
  145. DefaultSite_ReverseProxy = 1
  146. DefaultSite_Redirect = 2
  147. DefaultSite_NotFoundPage = 3
  148. )
  149. /*
  150. Web Templates
  151. */
  152. var (
  153. //go:embed templates/forbidden.html
  154. page_forbidden []byte
  155. //go:embed templates/hosterror.html
  156. page_hosterror []byte
  157. )