dynamicproxy.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. go func() {
  130. //Start another router to check if the router.server is killed. If yes, kill this server as well
  131. go func() {
  132. <-stopChan
  133. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  134. defer cancel()
  135. httpServer.Shutdown(ctx)
  136. log.Println("HTTP to HTTPS redirection listener stopped")
  137. }()
  138. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  139. log.Fatalf("Could not start server: %v\n", err)
  140. }
  141. }()
  142. router.tlsRedirectStop = stopChan
  143. }
  144. log.Println("Reverse proxy service started in the background (TLS mode)")
  145. go func() {
  146. if err := router.server.Serve(ln); err != nil && err != http.ErrServerClosed {
  147. log.Fatalf("Could not start server: %v\n", err)
  148. }
  149. }()
  150. } else {
  151. //Serve with non TLS mode
  152. router.tlsListener = nil
  153. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  154. router.Running = true
  155. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  156. go func() {
  157. router.server.ListenAndServe()
  158. //log.Println("[DynamicProxy] " + err.Error())
  159. }()
  160. }
  161. return nil
  162. }
  163. func (router *Router) StopProxyService() error {
  164. if router.server == nil {
  165. return errors.New("Reverse proxy server already stopped")
  166. }
  167. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  168. defer cancel()
  169. err := router.server.Shutdown(ctx)
  170. if err != nil {
  171. return err
  172. }
  173. if router.tlsListener != nil {
  174. router.tlsListener.Close()
  175. }
  176. if router.tlsRedirectStop != nil {
  177. router.tlsRedirectStop <- true
  178. }
  179. //Discard the server object
  180. router.tlsListener = nil
  181. router.server = nil
  182. router.Running = false
  183. router.tlsRedirectStop = nil
  184. return nil
  185. }
  186. // Restart the current router if it is running.
  187. // Startup the server if it is not running initially
  188. func (router *Router) Restart() error {
  189. //Stop the router if it is already running
  190. if router.Running {
  191. err := router.StopProxyService()
  192. if err != nil {
  193. return err
  194. }
  195. }
  196. //Start the server
  197. err := router.StartProxyService()
  198. return err
  199. }
  200. /*
  201. Check if a given request is accessed via a proxied subdomain
  202. */
  203. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  204. hostname := r.Header.Get("X-Forwarded-Host")
  205. if hostname == "" {
  206. hostname = r.Host
  207. }
  208. hostname = strings.Split(hostname, ":")[0]
  209. subdEndpoint := router.getSubdomainProxyEndpointFromHostname(hostname)
  210. return subdEndpoint != nil
  211. }
  212. /*
  213. Add an URL into a custom proxy services
  214. */
  215. func (router *Router) AddVirtualDirectoryProxyService(rootname string, domain string, requireTLS bool) error {
  216. if domain[len(domain)-1:] == "/" {
  217. domain = domain[:len(domain)-1]
  218. }
  219. if rootname[len(rootname)-1:] == "/" {
  220. rootname = rootname[:len(rootname)-1]
  221. }
  222. webProxyEndpoint := domain
  223. if requireTLS {
  224. webProxyEndpoint = "https://" + webProxyEndpoint
  225. } else {
  226. webProxyEndpoint = "http://" + webProxyEndpoint
  227. }
  228. //Create a new proxy agent for this root
  229. path, err := url.Parse(webProxyEndpoint)
  230. if err != nil {
  231. return err
  232. }
  233. proxy := dpcore.NewDynamicProxyCore(path, rootname)
  234. endpointObject := ProxyEndpoint{
  235. Root: rootname,
  236. Domain: domain,
  237. RequireTLS: requireTLS,
  238. Proxy: proxy,
  239. }
  240. router.ProxyEndpoints.Store(rootname, &endpointObject)
  241. log.Println("Adding Proxy Rule: ", rootname+" to "+domain)
  242. return nil
  243. }
  244. /*
  245. Remove routing from RP
  246. */
  247. func (router *Router) RemoveProxy(ptype string, key string) error {
  248. //fmt.Println(ptype, key)
  249. if ptype == "vdir" {
  250. router.ProxyEndpoints.Delete(key)
  251. return nil
  252. } else if ptype == "subd" {
  253. router.SubdomainEndpoint.Delete(key)
  254. return nil
  255. }
  256. return errors.New("invalid ptype")
  257. }
  258. /*
  259. Add an default router for the proxy server
  260. */
  261. func (router *Router) SetRootProxy(proxyLocation string, requireTLS bool) error {
  262. if proxyLocation[len(proxyLocation)-1:] == "/" {
  263. proxyLocation = proxyLocation[:len(proxyLocation)-1]
  264. }
  265. webProxyEndpoint := proxyLocation
  266. if requireTLS {
  267. webProxyEndpoint = "https://" + webProxyEndpoint
  268. } else {
  269. webProxyEndpoint = "http://" + webProxyEndpoint
  270. }
  271. //Create a new proxy agent for this root
  272. path, err := url.Parse(webProxyEndpoint)
  273. if err != nil {
  274. return err
  275. }
  276. proxy := dpcore.NewDynamicProxyCore(path, "")
  277. rootEndpoint := ProxyEndpoint{
  278. Root: "/",
  279. Domain: proxyLocation,
  280. RequireTLS: requireTLS,
  281. Proxy: proxy,
  282. }
  283. router.Root = &rootEndpoint
  284. return nil
  285. }
  286. // Helpers to export the syncmap for easier processing
  287. func (r *Router) GetSDProxyEndpointsAsMap() map[string]*SubdomainEndpoint {
  288. m := make(map[string]*SubdomainEndpoint)
  289. r.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  290. k, ok := key.(string)
  291. if !ok {
  292. return true
  293. }
  294. v, ok := value.(*SubdomainEndpoint)
  295. if !ok {
  296. return true
  297. }
  298. m[k] = v
  299. return true
  300. })
  301. return m
  302. }
  303. func (r *Router) GetVDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  304. m := make(map[string]*ProxyEndpoint)
  305. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  306. k, ok := key.(string)
  307. if !ok {
  308. return true
  309. }
  310. v, ok := value.(*ProxyEndpoint)
  311. if !ok {
  312. return true
  313. }
  314. m[k] = v
  315. return true
  316. })
  317. return m
  318. }