dynamicproxy.go 8.6 KB

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