dynamicproxy.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. package dynamicproxy
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "errors"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  14. )
  15. /*
  16. Zoraxy Dynamic Proxy
  17. */
  18. func NewDynamicProxy(option RouterOption) (*Router, error) {
  19. proxyMap := sync.Map{}
  20. domainMap := sync.Map{}
  21. thisRouter := Router{
  22. Option: &option,
  23. ProxyEndpoints: &proxyMap,
  24. SubdomainEndpoint: &domainMap,
  25. Running: false,
  26. server: nil,
  27. routingRules: []*RoutingRule{},
  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 https redirect, which will require updates
  41. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  42. router.Option.ForceHttpsRedirect = useRedirect
  43. router.Restart()
  44. }
  45. // Start the dynamic routing
  46. func (router *Router) StartProxyService() error {
  47. //Create a new server object
  48. if router.server != nil {
  49. return errors.New("Reverse proxy server already running")
  50. }
  51. if router.Root == nil {
  52. return errors.New("Reverse proxy router root not set")
  53. }
  54. config := &tls.Config{
  55. GetCertificate: router.Option.TlsManager.GetCert,
  56. }
  57. if router.Option.UseTls {
  58. //Serve with TLS mode
  59. ln, err := tls.Listen("tcp", ":"+strconv.Itoa(router.Option.Port), config)
  60. if err != nil {
  61. log.Println(err)
  62. router.Running = false
  63. return err
  64. }
  65. router.tlsListener = ln
  66. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  67. router.Running = true
  68. if router.Option.Port != 80 && router.Option.ForceHttpsRedirect {
  69. //Add a 80 to 443 redirector
  70. httpServer := &http.Server{
  71. Addr: ":80",
  72. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  73. protocol := "https://"
  74. if router.Option.Port == 443 {
  75. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  76. } else {
  77. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  78. }
  79. }),
  80. ReadTimeout: 3 * time.Second,
  81. WriteTimeout: 3 * time.Second,
  82. IdleTimeout: 120 * time.Second,
  83. }
  84. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  85. //Create a redirection stop channel
  86. stopChan := make(chan bool)
  87. //Start a blocking wait for shutting down the http to https redirection server
  88. go func() {
  89. <-stopChan
  90. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  91. defer cancel()
  92. httpServer.Shutdown(ctx)
  93. log.Println("HTTP to HTTPS redirection listener stopped")
  94. }()
  95. //Start the http server that listens to port 80 and redirect to 443
  96. go func() {
  97. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  98. //Unable to startup port 80 listener. Handle shutdown process gracefully
  99. stopChan <- true
  100. log.Fatalf("Could not start server: %v\n", err)
  101. }
  102. }()
  103. router.tlsRedirectStop = stopChan
  104. }
  105. //Start the TLS server
  106. log.Println("Reverse proxy service started in the background (TLS mode)")
  107. go func() {
  108. if err := router.server.Serve(ln); err != nil && err != http.ErrServerClosed {
  109. log.Fatalf("Could not start server: %v\n", err)
  110. }
  111. }()
  112. } else {
  113. //Serve with non TLS mode
  114. router.tlsListener = nil
  115. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  116. router.Running = true
  117. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  118. go func() {
  119. router.server.ListenAndServe()
  120. //log.Println("[DynamicProxy] " + err.Error())
  121. }()
  122. }
  123. return nil
  124. }
  125. func (router *Router) StopProxyService() error {
  126. if router.server == nil {
  127. return errors.New("Reverse proxy server already stopped")
  128. }
  129. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  130. defer cancel()
  131. err := router.server.Shutdown(ctx)
  132. if err != nil {
  133. return err
  134. }
  135. if router.tlsListener != nil {
  136. router.tlsListener.Close()
  137. }
  138. if router.tlsRedirectStop != nil {
  139. router.tlsRedirectStop <- true
  140. }
  141. //Discard the server object
  142. router.tlsListener = nil
  143. router.server = nil
  144. router.Running = false
  145. router.tlsRedirectStop = nil
  146. return nil
  147. }
  148. // Restart the current router if it is running.
  149. // Startup the server if it is not running initially
  150. func (router *Router) Restart() error {
  151. //Stop the router if it is already running
  152. if router.Running {
  153. err := router.StopProxyService()
  154. if err != nil {
  155. return err
  156. }
  157. }
  158. //Start the server
  159. err := router.StartProxyService()
  160. return err
  161. }
  162. /*
  163. Check if a given request is accessed via a proxied subdomain
  164. */
  165. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  166. hostname := r.Header.Get("X-Forwarded-Host")
  167. if hostname == "" {
  168. hostname = r.Host
  169. }
  170. hostname = strings.Split(hostname, ":")[0]
  171. subdEndpoint := router.getSubdomainProxyEndpointFromHostname(hostname)
  172. return subdEndpoint != nil
  173. }
  174. /*
  175. Add an URL into a custom proxy services
  176. */
  177. func (router *Router) AddVirtualDirectoryProxyService(options *VdirOptions) error {
  178. domain := options.Domain
  179. if domain[len(domain)-1:] == "/" {
  180. domain = domain[:len(domain)-1]
  181. }
  182. /*
  183. if rootname[len(rootname)-1:] == "/" {
  184. rootname = rootname[:len(rootname)-1]
  185. }
  186. */
  187. webProxyEndpoint := domain
  188. if options.RequireTLS {
  189. webProxyEndpoint = "https://" + webProxyEndpoint
  190. } else {
  191. webProxyEndpoint = "http://" + webProxyEndpoint
  192. }
  193. //Create a new proxy agent for this root
  194. path, err := url.Parse(webProxyEndpoint)
  195. if err != nil {
  196. return err
  197. }
  198. proxy := dpcore.NewDynamicProxyCore(path, options.RootName, options.SkipCertValidations)
  199. endpointObject := ProxyEndpoint{
  200. ProxyType: ProxyType_Vdir,
  201. RootOrMatchingDomain: options.RootName,
  202. Domain: domain,
  203. RequireTLS: options.RequireTLS,
  204. SkipCertValidations: options.SkipCertValidations,
  205. RequireBasicAuth: options.RequireBasicAuth,
  206. BasicAuthCredentials: options.BasicAuthCredentials,
  207. Proxy: proxy,
  208. }
  209. router.ProxyEndpoints.Store(options.RootName, &endpointObject)
  210. log.Println("Adding Proxy Rule: ", options.RootName+" to "+domain)
  211. return nil
  212. }
  213. /*
  214. Remove routing from RP
  215. */
  216. func (router *Router) RemoveProxy(ptype string, key string) error {
  217. //fmt.Println(ptype, key)
  218. if ptype == "vdir" {
  219. router.ProxyEndpoints.Delete(key)
  220. return nil
  221. } else if ptype == "subd" {
  222. router.SubdomainEndpoint.Delete(key)
  223. return nil
  224. }
  225. return errors.New("invalid ptype")
  226. }
  227. /*
  228. Add an default router for the proxy server
  229. */
  230. func (router *Router) SetRootProxy(options *RootOptions) error {
  231. proxyLocation := options.ProxyLocation
  232. if proxyLocation[len(proxyLocation)-1:] == "/" {
  233. proxyLocation = proxyLocation[:len(proxyLocation)-1]
  234. }
  235. webProxyEndpoint := proxyLocation
  236. if options.RequireTLS {
  237. webProxyEndpoint = "https://" + webProxyEndpoint
  238. } else {
  239. webProxyEndpoint = "http://" + webProxyEndpoint
  240. }
  241. //Create a new proxy agent for this root
  242. path, err := url.Parse(webProxyEndpoint)
  243. if err != nil {
  244. return err
  245. }
  246. proxy := dpcore.NewDynamicProxyCore(path, "", options.SkipCertValidations)
  247. rootEndpoint := ProxyEndpoint{
  248. ProxyType: ProxyType_Vdir,
  249. RootOrMatchingDomain: "/",
  250. Domain: proxyLocation,
  251. RequireTLS: options.RequireTLS,
  252. SkipCertValidations: options.SkipCertValidations,
  253. RequireBasicAuth: options.RequireBasicAuth,
  254. BasicAuthCredentials: options.BasicAuthCredentials,
  255. Proxy: proxy,
  256. }
  257. router.Root = &rootEndpoint
  258. return nil
  259. }
  260. // Helpers to export the syncmap for easier processing
  261. func (r *Router) GetSDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  262. m := make(map[string]*ProxyEndpoint)
  263. r.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  264. k, ok := key.(string)
  265. if !ok {
  266. return true
  267. }
  268. v, ok := value.(*ProxyEndpoint)
  269. if !ok {
  270. return true
  271. }
  272. m[k] = v
  273. return true
  274. })
  275. return m
  276. }
  277. func (r *Router) GetVDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  278. m := make(map[string]*ProxyEndpoint)
  279. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  280. k, ok := key.(string)
  281. if !ok {
  282. return true
  283. }
  284. v, ok := value.(*ProxyEndpoint)
  285. if !ok {
  286. return true
  287. }
  288. m[k] = v
  289. return true
  290. })
  291. return m
  292. }