dynamicproxy.go 7.4 KB

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