1
0

dynamicproxy.go 9.7 KB

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