dynamicproxy.go 7.1 KB

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