dynamicproxy.go 8.9 KB

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