dynamicproxy.go 8.8 KB

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