dynamicproxy.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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("Registered Proxy Rule: ", options.RootName+" to "+domain)
  211. return nil
  212. }
  213. /*
  214. Load routing from RP
  215. */
  216. func (router *Router) LoadProxy(ptype string, key string) (*ProxyEndpoint, error) {
  217. if ptype == "vdir" {
  218. proxy, ok := router.ProxyEndpoints.Load(key)
  219. if !ok {
  220. return nil, errors.New("target proxy not found")
  221. }
  222. return proxy.(*ProxyEndpoint), nil
  223. } else if ptype == "subd" {
  224. proxy, ok := router.SubdomainEndpoint.Load(key)
  225. if !ok {
  226. return nil, errors.New("target proxy not found")
  227. }
  228. return proxy.(*ProxyEndpoint), nil
  229. }
  230. return nil, errors.New("unsupported ptype")
  231. }
  232. /*
  233. Save routing from RP
  234. */
  235. func (router *Router) SaveProxy(ptype string, key string, newConfig *ProxyEndpoint) {
  236. if ptype == "vdir" {
  237. router.ProxyEndpoints.Store(key, newConfig)
  238. } else if ptype == "subd" {
  239. router.SubdomainEndpoint.Store(key, newConfig)
  240. }
  241. }
  242. /*
  243. Remove routing from RP
  244. */
  245. func (router *Router) RemoveProxy(ptype string, key string) error {
  246. //fmt.Println(ptype, key)
  247. if ptype == "vdir" {
  248. router.ProxyEndpoints.Delete(key)
  249. return nil
  250. } else if ptype == "subd" {
  251. router.SubdomainEndpoint.Delete(key)
  252. return nil
  253. }
  254. return errors.New("invalid ptype")
  255. }
  256. /*
  257. Add an default router for the proxy server
  258. */
  259. func (router *Router) SetRootProxy(options *RootOptions) error {
  260. proxyLocation := options.ProxyLocation
  261. if proxyLocation[len(proxyLocation)-1:] == "/" {
  262. proxyLocation = proxyLocation[:len(proxyLocation)-1]
  263. }
  264. webProxyEndpoint := proxyLocation
  265. if options.RequireTLS {
  266. webProxyEndpoint = "https://" + webProxyEndpoint
  267. } else {
  268. webProxyEndpoint = "http://" + webProxyEndpoint
  269. }
  270. //Create a new proxy agent for this root
  271. path, err := url.Parse(webProxyEndpoint)
  272. if err != nil {
  273. return err
  274. }
  275. proxy := dpcore.NewDynamicProxyCore(path, "", options.SkipCertValidations)
  276. rootEndpoint := ProxyEndpoint{
  277. ProxyType: ProxyType_Vdir,
  278. RootOrMatchingDomain: "/",
  279. Domain: proxyLocation,
  280. RequireTLS: options.RequireTLS,
  281. SkipCertValidations: options.SkipCertValidations,
  282. RequireBasicAuth: options.RequireBasicAuth,
  283. BasicAuthCredentials: options.BasicAuthCredentials,
  284. Proxy: proxy,
  285. }
  286. router.Root = &rootEndpoint
  287. return nil
  288. }
  289. // Helpers to export the syncmap for easier processing
  290. func (r *Router) GetSDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  291. m := make(map[string]*ProxyEndpoint)
  292. r.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  293. k, ok := key.(string)
  294. if !ok {
  295. return true
  296. }
  297. v, ok := value.(*ProxyEndpoint)
  298. if !ok {
  299. return true
  300. }
  301. m[k] = v
  302. return true
  303. })
  304. return m
  305. }
  306. func (r *Router) GetVDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  307. m := make(map[string]*ProxyEndpoint)
  308. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  309. k, ok := key.(string)
  310. if !ok {
  311. return true
  312. }
  313. v, ok := value.(*ProxyEndpoint)
  314. if !ok {
  315. return true
  316. }
  317. m[k] = v
  318. return true
  319. })
  320. return m
  321. }