dynamicproxy.go 9.5 KB

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