dynamicproxy.go 9.1 KB

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