dynamicproxy.go 8.4 KB

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