typedef.go 8.2 KB

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