typedef.go 7.7 KB

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