dynamicproxy.go 8.2 KB

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