1
0

dynamicproxy.go 7.1 KB

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