dynamicproxy.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. selectedUpstream, err := router.loadBalancer.GetRequestUpstreamTarget(r, sep.Origins)
  135. if err != nil {
  136. http.ServeFile(w, r, "./web/hosterror.html")
  137. log.Println(err.Error())
  138. router.logRequest(r, false, 404, "vdir-http", r.Host)
  139. }
  140. selectedUpstream.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  141. ProxyDomain: selectedUpstream.OriginIpOrDomain,
  142. OriginalHost: originalHostHeader,
  143. UseTLS: selectedUpstream.RequireTLS,
  144. PathPrefix: "",
  145. Version: sep.parent.Option.HostVersion,
  146. })
  147. return
  148. }
  149. if router.Option.ForceHttpsRedirect {
  150. //Redirect to https is enabled
  151. protocol := "https://"
  152. if router.Option.Port == 443 {
  153. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  154. } else {
  155. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  156. }
  157. } else {
  158. //Do not do redirection
  159. if sep != nil {
  160. //Sub-domain exists but not allow non-TLS access
  161. w.WriteHeader(http.StatusBadRequest)
  162. w.Write([]byte("400 - Bad Request"))
  163. } else {
  164. //No defined sub-domain
  165. http.NotFound(w, r)
  166. }
  167. }
  168. }),
  169. ReadTimeout: 3 * time.Second,
  170. WriteTimeout: 3 * time.Second,
  171. IdleTimeout: 120 * time.Second,
  172. }
  173. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  174. //Create a redirection stop channel
  175. stopChan := make(chan bool)
  176. //Start a blocking wait for shutting down the http to https redirection server
  177. go func() {
  178. <-stopChan
  179. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  180. defer cancel()
  181. httpServer.Shutdown(ctx)
  182. log.Println("HTTP to HTTPS redirection listener stopped")
  183. }()
  184. //Start the http server that listens to port 80 and redirect to 443
  185. go func() {
  186. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  187. //Unable to startup port 80 listener. Handle shutdown process gracefully
  188. stopChan <- true
  189. log.Fatalf("Could not start redirection server: %v\n", err)
  190. }
  191. }()
  192. router.tlsRedirectStop = stopChan
  193. }
  194. //Start the TLS server
  195. log.Println("Reverse proxy service started in the background (TLS mode)")
  196. go func() {
  197. if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
  198. log.Fatalf("Could not start proxy server: %v\n", err)
  199. }
  200. }()
  201. } else {
  202. //Serve with non TLS mode
  203. router.tlsListener = nil
  204. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  205. router.Running = true
  206. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  207. go func() {
  208. router.server.ListenAndServe()
  209. //log.Println("[DynamicProxy] " + err.Error())
  210. }()
  211. }
  212. return nil
  213. }
  214. func (router *Router) StopProxyService() error {
  215. if router.server == nil {
  216. return errors.New("reverse proxy server already stopped")
  217. }
  218. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  219. defer cancel()
  220. err := router.server.Shutdown(ctx)
  221. if err != nil {
  222. return err
  223. }
  224. //Stop TLS listener
  225. if router.tlsListener != nil {
  226. router.tlsListener.Close()
  227. }
  228. //Stop rate limiter
  229. if router.rateLimterStop != nil {
  230. go func() {
  231. // As the rate timer loop has a 1 sec ticker
  232. // stop the rate limiter in go routine can prevent
  233. // front end from freezing for 1 sec
  234. router.rateLimterStop <- true
  235. }()
  236. }
  237. //Stop TLS redirection (from port 80)
  238. if router.tlsRedirectStop != nil {
  239. router.tlsRedirectStop <- true
  240. }
  241. //Discard the server object
  242. router.tlsListener = nil
  243. router.server = nil
  244. router.Running = false
  245. router.tlsRedirectStop = nil
  246. return nil
  247. }
  248. // Restart the current router if it is running.
  249. func (router *Router) Restart() error {
  250. //Stop the router if it is already running
  251. if router.Running {
  252. err := router.StopProxyService()
  253. if err != nil {
  254. return err
  255. }
  256. time.Sleep(300 * time.Millisecond)
  257. // Start the server
  258. err = router.StartProxyService()
  259. if err != nil {
  260. return err
  261. }
  262. }
  263. return nil
  264. }
  265. /*
  266. Check if a given request is accessed via a proxied subdomain
  267. */
  268. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  269. hostname := r.Header.Get("X-Forwarded-Host")
  270. if hostname == "" {
  271. hostname = r.Host
  272. }
  273. hostname = strings.Split(hostname, ":")[0]
  274. subdEndpoint := router.getProxyEndpointFromHostname(hostname)
  275. return subdEndpoint != nil
  276. }
  277. /*
  278. Load routing from RP
  279. */
  280. func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
  281. var targetProxyEndpoint *ProxyEndpoint
  282. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  283. key, ok := key.(string)
  284. if !ok {
  285. return true
  286. }
  287. v, ok := value.(*ProxyEndpoint)
  288. if !ok {
  289. return true
  290. }
  291. if key == matchingDomain {
  292. targetProxyEndpoint = v
  293. }
  294. return true
  295. })
  296. if targetProxyEndpoint == nil {
  297. return nil, errors.New("target routing rule not found")
  298. }
  299. return targetProxyEndpoint, nil
  300. }
  301. // Deep copy a proxy endpoint, excluding runtime paramters
  302. func CopyEndpoint(endpoint *ProxyEndpoint) *ProxyEndpoint {
  303. js, _ := json.Marshal(endpoint)
  304. newProxyEndpoint := ProxyEndpoint{}
  305. err := json.Unmarshal(js, &newProxyEndpoint)
  306. if err != nil {
  307. return nil
  308. }
  309. return &newProxyEndpoint
  310. }
  311. func (r *Router) GetProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  312. m := make(map[string]*ProxyEndpoint)
  313. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  314. k, ok := key.(string)
  315. if !ok {
  316. return true
  317. }
  318. v, ok := value.(*ProxyEndpoint)
  319. if !ok {
  320. return true
  321. }
  322. m[k] = v
  323. return true
  324. })
  325. return m
  326. }