dynamicproxy.go 9.6 KB

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