dynamicproxy.go 8.6 KB

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