dynamicproxy.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package dynamicproxy
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "log"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  15. )
  16. /*
  17. Zoraxy Dynamic Proxy
  18. */
  19. func NewDynamicProxy(option RouterOption) (*Router, error) {
  20. proxyMap := sync.Map{}
  21. thisRouter := Router{
  22. Option: &option,
  23. ProxyEndpoints: &proxyMap,
  24. Running: false,
  25. server: nil,
  26. routingRules: []*RoutingRule{},
  27. loadBalancer: option.LoadBalancer,
  28. rateLimitCounter: RequestCountPerIpTable{},
  29. }
  30. thisRouter.mux = &ProxyHandler{
  31. Parent: &thisRouter,
  32. }
  33. return &thisRouter, nil
  34. }
  35. // Update TLS setting in runtime. Will restart the proxy server
  36. // if it is already running in the background
  37. func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
  38. router.Option.UseTls = tlsEnabled
  39. router.Restart()
  40. }
  41. // Update TLS Version in runtime. Will restart proxy server if running.
  42. // Set this to true to force TLS 1.2 or above
  43. func (router *Router) UpdateTLSVersion(requireLatest bool) {
  44. router.Option.ForceTLSLatest = requireLatest
  45. router.Restart()
  46. }
  47. // Update port 80 listener state
  48. func (router *Router) UpdatePort80ListenerState(useRedirect bool) {
  49. router.Option.ListenOnPort80 = useRedirect
  50. router.Restart()
  51. }
  52. // Update https redirect, which will require updates
  53. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  54. router.Option.ForceHttpsRedirect = useRedirect
  55. router.Restart()
  56. }
  57. // Start the dynamic routing
  58. func (router *Router) StartProxyService() error {
  59. //Create a new server object
  60. if router.server != nil {
  61. return errors.New("reverse proxy server already running")
  62. }
  63. //Check if root route is set
  64. if router.Root == nil {
  65. return errors.New("reverse proxy router root not set")
  66. }
  67. minVersion := tls.VersionTLS10
  68. if router.Option.ForceTLSLatest {
  69. minVersion = tls.VersionTLS12
  70. }
  71. config := &tls.Config{
  72. GetCertificate: router.Option.TlsManager.GetCert,
  73. MinVersion: uint16(minVersion),
  74. }
  75. //Start rate limitor
  76. err := router.startRateLimterCounterResetTicker()
  77. if err != nil {
  78. return err
  79. }
  80. if router.Option.UseTls {
  81. router.server = &http.Server{
  82. Addr: ":" + strconv.Itoa(router.Option.Port),
  83. Handler: router.mux,
  84. TLSConfig: config,
  85. }
  86. router.Running = true
  87. if router.Option.Port != 80 && router.Option.ListenOnPort80 {
  88. //Add a 80 to 443 redirector
  89. httpServer := &http.Server{
  90. Addr: ":80",
  91. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. //Check if the domain requesting allow non TLS mode
  93. domainOnly := r.Host
  94. if strings.Contains(r.Host, ":") {
  95. hostPath := strings.Split(r.Host, ":")
  96. domainOnly = hostPath[0]
  97. }
  98. sep := router.getProxyEndpointFromHostname(domainOnly)
  99. if sep != nil && sep.BypassGlobalTLS {
  100. //Allow routing via non-TLS handler
  101. originalHostHeader := r.Host
  102. if r.URL != nil {
  103. r.Host = r.URL.Host
  104. } else {
  105. //Fallback when the upstream proxy screw something up in the header
  106. r.URL, _ = url.Parse(originalHostHeader)
  107. }
  108. //Access Check (blacklist / whitelist)
  109. ruleID := sep.AccessFilterUUID
  110. if sep.AccessFilterUUID == "" {
  111. //Use default rule
  112. ruleID = "default"
  113. }
  114. accessRule, err := router.Option.AccessController.GetAccessRuleByID(ruleID)
  115. if err == nil {
  116. isBlocked, _ := accessRequestBlocked(accessRule, router.Option.WebDirectory, w, r)
  117. if isBlocked {
  118. return
  119. }
  120. }
  121. // Rate Limit
  122. if sep.RequireRateLimit {
  123. if err := router.handleRateLimit(w, r, sep); err != nil {
  124. return
  125. }
  126. }
  127. //Validate basic auth
  128. if sep.RequireBasicAuth {
  129. err := handleBasicAuth(w, r, sep)
  130. if err != nil {
  131. return
  132. }
  133. }
  134. sep.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  135. ProxyDomain: sep.Domain,
  136. OriginalHost: originalHostHeader,
  137. UseTLS: sep.RequireTLS,
  138. PathPrefix: "",
  139. Version: sep.parent.Option.HostVersion,
  140. })
  141. return
  142. }
  143. if router.Option.ForceHttpsRedirect {
  144. //Redirect to https is enabled
  145. protocol := "https://"
  146. if router.Option.Port == 443 {
  147. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  148. } else {
  149. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  150. }
  151. } else {
  152. //Do not do redirection
  153. if sep != nil {
  154. //Sub-domain exists but not allow non-TLS access
  155. w.WriteHeader(http.StatusBadRequest)
  156. w.Write([]byte("400 - Bad Request"))
  157. } else {
  158. //No defined sub-domain
  159. http.NotFound(w, r)
  160. }
  161. }
  162. }),
  163. ReadTimeout: 3 * time.Second,
  164. WriteTimeout: 3 * time.Second,
  165. IdleTimeout: 120 * time.Second,
  166. }
  167. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  168. //Create a redirection stop channel
  169. stopChan := make(chan bool)
  170. //Start a blocking wait for shutting down the http to https redirection server
  171. go func() {
  172. <-stopChan
  173. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  174. defer cancel()
  175. httpServer.Shutdown(ctx)
  176. log.Println("HTTP to HTTPS redirection listener stopped")
  177. }()
  178. //Start the http server that listens to port 80 and redirect to 443
  179. go func() {
  180. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  181. //Unable to startup port 80 listener. Handle shutdown process gracefully
  182. stopChan <- true
  183. log.Fatalf("Could not start redirection server: %v\n", err)
  184. }
  185. }()
  186. router.tlsRedirectStop = stopChan
  187. }
  188. //Start the TLS server
  189. log.Println("Reverse proxy service started in the background (TLS mode)")
  190. go func() {
  191. if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
  192. log.Fatalf("Could not start proxy server: %v\n", err)
  193. }
  194. }()
  195. } else {
  196. //Serve with non TLS mode
  197. router.tlsListener = nil
  198. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  199. router.Running = true
  200. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  201. go func() {
  202. router.server.ListenAndServe()
  203. //log.Println("[DynamicProxy] " + err.Error())
  204. }()
  205. }
  206. return nil
  207. }
  208. func (router *Router) StopProxyService() error {
  209. if router.server == nil {
  210. return errors.New("reverse proxy server already stopped")
  211. }
  212. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  213. defer cancel()
  214. err := router.server.Shutdown(ctx)
  215. if err != nil {
  216. return err
  217. }
  218. //Stop TLS listener
  219. if router.tlsListener != nil {
  220. router.tlsListener.Close()
  221. }
  222. //Stop rate limiter
  223. if router.rateLimterStop != nil {
  224. go func() {
  225. // As the rate timer loop has a 1 sec ticker
  226. // stop the rate limiter in go routine can prevent
  227. // front end from freezing for 1 sec
  228. router.rateLimterStop <- true
  229. }()
  230. }
  231. //Stop TLS redirection (from port 80)
  232. if router.tlsRedirectStop != nil {
  233. router.tlsRedirectStop <- true
  234. }
  235. //Discard the server object
  236. router.tlsListener = nil
  237. router.server = nil
  238. router.Running = false
  239. router.tlsRedirectStop = nil
  240. return nil
  241. }
  242. // Restart the current router if it is running.
  243. func (router *Router) Restart() error {
  244. //Stop the router if it is already running
  245. if router.Running {
  246. err := router.StopProxyService()
  247. if err != nil {
  248. return err
  249. }
  250. time.Sleep(300 * time.Millisecond)
  251. // Start the server
  252. err = router.StartProxyService()
  253. if err != nil {
  254. return err
  255. }
  256. }
  257. return nil
  258. }
  259. /*
  260. Check if a given request is accessed via a proxied subdomain
  261. */
  262. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  263. hostname := r.Header.Get("X-Forwarded-Host")
  264. if hostname == "" {
  265. hostname = r.Host
  266. }
  267. hostname = strings.Split(hostname, ":")[0]
  268. subdEndpoint := router.getProxyEndpointFromHostname(hostname)
  269. return subdEndpoint != nil
  270. }
  271. /*
  272. Load routing from RP
  273. */
  274. func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
  275. var targetProxyEndpoint *ProxyEndpoint
  276. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  277. key, ok := key.(string)
  278. if !ok {
  279. return true
  280. }
  281. v, ok := value.(*ProxyEndpoint)
  282. if !ok {
  283. return true
  284. }
  285. if key == matchingDomain {
  286. targetProxyEndpoint = v
  287. }
  288. return true
  289. })
  290. if targetProxyEndpoint == nil {
  291. return nil, errors.New("target routing rule not found")
  292. }
  293. return targetProxyEndpoint, nil
  294. }
  295. // Deep copy a proxy endpoint, excluding runtime paramters
  296. func CopyEndpoint(endpoint *ProxyEndpoint) *ProxyEndpoint {
  297. js, _ := json.Marshal(endpoint)
  298. newProxyEndpoint := ProxyEndpoint{}
  299. err := json.Unmarshal(js, &newProxyEndpoint)
  300. if err != nil {
  301. return nil
  302. }
  303. return &newProxyEndpoint
  304. }
  305. func (r *Router) GetProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  306. m := make(map[string]*ProxyEndpoint)
  307. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  308. k, ok := key.(string)
  309. if !ok {
  310. return true
  311. }
  312. v, ok := value.(*ProxyEndpoint)
  313. if !ok {
  314. return true
  315. }
  316. m[k] = v
  317. return true
  318. })
  319. return m
  320. }