1
0

dynamicproxy.go 9.5 KB

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