dynamicproxy.go 8.4 KB

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