dynamicproxy.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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/arozos/ReverseProxy/mod/dynamicproxy/dpcore"
  15. "imuslab.com/arozos/ReverseProxy/mod/dynamicproxy/redirection"
  16. "imuslab.com/arozos/ReverseProxy/mod/reverseproxy"
  17. "imuslab.com/arozos/ReverseProxy/mod/tlscert"
  18. )
  19. /*
  20. Allow users to setup manual proxying for specific path
  21. */
  22. type Router struct {
  23. ListenPort int
  24. ProxyEndpoints *sync.Map
  25. SubdomainEndpoint *sync.Map
  26. Running bool
  27. Root *ProxyEndpoint
  28. tlsCertManager *tlscert.Manager
  29. mux http.Handler
  30. TlsManager *tlscert.Manager
  31. useTLS bool
  32. useHttpToHttpsRedirect bool
  33. server *http.Server
  34. tlsListener net.Listener
  35. redirectionRuleTable *redirection.RuleTable
  36. }
  37. type RouterOption struct {
  38. Port int
  39. UseTls bool
  40. ForceHttpsRedirect bool
  41. TlsManager *tlscert.Manager
  42. RedirectRuleTable *redirection.RuleTable
  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. ListenPort: option.Port,
  64. ProxyEndpoints: &proxyMap,
  65. SubdomainEndpoint: &domainMap,
  66. Running: false,
  67. tlsCertManager: option.TlsManager,
  68. useTLS: option.UseTls,
  69. useHttpToHttpsRedirect: option.ForceHttpsRedirect,
  70. redirectionRuleTable: option.RedirectRuleTable,
  71. server: nil,
  72. }
  73. thisRouter.mux = &ProxyHandler{
  74. Parent: &thisRouter,
  75. }
  76. return &thisRouter, nil
  77. }
  78. // Update TLS setting in runtime. Will restart the proxy server
  79. // if it is already running in the background
  80. func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
  81. router.useTLS = tlsEnabled
  82. router.Restart()
  83. }
  84. // Update https redirect, which will require updates
  85. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  86. router.useHttpToHttpsRedirect = useRedirect
  87. router.Restart()
  88. }
  89. // Start the dynamic routing
  90. func (router *Router) StartProxyService() error {
  91. //Create a new server object
  92. if router.server != nil {
  93. return errors.New("Reverse proxy server already running")
  94. }
  95. if router.Root == nil {
  96. return errors.New("Reverse proxy router root not set")
  97. }
  98. config := &tls.Config{
  99. GetCertificate: router.tlsCertManager.GetCert,
  100. }
  101. if router.useTLS {
  102. //Serve with TLS mode
  103. ln, err := tls.Listen("tcp", ":"+strconv.Itoa(router.ListenPort), config)
  104. if err != nil {
  105. log.Println(err)
  106. return err
  107. }
  108. router.tlsListener = ln
  109. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.ListenPort), Handler: router.mux}
  110. router.Running = true
  111. if router.ListenPort == 443 && router.useHttpToHttpsRedirect {
  112. //Add a 80 to 443 redirector
  113. httpServer := &http.Server{
  114. Addr: ":80",
  115. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  116. http.Redirect(w, r, "https://"+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  117. }),
  118. ReadTimeout: 3 * time.Second,
  119. WriteTimeout: 3 * time.Second,
  120. IdleTimeout: 120 * time.Second,
  121. }
  122. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  123. go func() {
  124. //Start another router to check if the router.server is killed. If yes, kill this server as well
  125. go func() {
  126. for router.server != nil {
  127. time.Sleep(100 * time.Millisecond)
  128. }
  129. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  130. defer cancel()
  131. httpServer.Shutdown(ctx)
  132. log.Println(":80 to :433 redirection listener stopped")
  133. }()
  134. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  135. log.Fatalf("Could not start server: %v\n", err)
  136. }
  137. }()
  138. }
  139. log.Println("Reverse proxy service started in the background (TLS mode)")
  140. go func() {
  141. if err := router.server.Serve(ln); err != nil && err != http.ErrServerClosed {
  142. log.Fatalf("Could not start server: %v\n", err)
  143. }
  144. }()
  145. } else {
  146. //Serve with non TLS mode
  147. router.tlsListener = nil
  148. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.ListenPort), Handler: router.mux}
  149. router.Running = true
  150. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  151. go func() {
  152. router.server.ListenAndServe()
  153. //log.Println("[DynamicProxy] " + err.Error())
  154. }()
  155. }
  156. return nil
  157. }
  158. func (router *Router) StopProxyService() error {
  159. if router.server == nil {
  160. return errors.New("Reverse proxy server already stopped")
  161. }
  162. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  163. defer cancel()
  164. err := router.server.Shutdown(ctx)
  165. if err != nil {
  166. return err
  167. }
  168. if router.tlsListener != nil {
  169. router.tlsListener.Close()
  170. }
  171. //Discard the server object
  172. router.tlsListener = nil
  173. router.server = nil
  174. router.Running = false
  175. return nil
  176. }
  177. // Restart the current router if it is running.
  178. // Startup the server if it is not running initially
  179. func (router *Router) Restart() error {
  180. //Stop the router if it is already running
  181. if router.Running {
  182. err := router.StopProxyService()
  183. if err != nil {
  184. return err
  185. }
  186. }
  187. //Start the server
  188. err := router.StartProxyService()
  189. return err
  190. }
  191. /*
  192. Add an URL into a custom proxy services
  193. */
  194. func (router *Router) AddVirtualDirectoryProxyService(rootname string, domain string, requireTLS bool) error {
  195. if domain[len(domain)-1:] == "/" {
  196. domain = domain[:len(domain)-1]
  197. }
  198. if rootname[len(rootname)-1:] == "/" {
  199. rootname = rootname[:len(rootname)-1]
  200. }
  201. webProxyEndpoint := domain
  202. if requireTLS {
  203. webProxyEndpoint = "https://" + webProxyEndpoint
  204. } else {
  205. webProxyEndpoint = "http://" + webProxyEndpoint
  206. }
  207. //Create a new proxy agent for this root
  208. path, err := url.Parse(webProxyEndpoint)
  209. if err != nil {
  210. return err
  211. }
  212. proxy := dpcore.NewDynamicProxyCore(path, rootname)
  213. endpointObject := ProxyEndpoint{
  214. Root: rootname,
  215. Domain: domain,
  216. RequireTLS: requireTLS,
  217. Proxy: proxy,
  218. }
  219. router.ProxyEndpoints.Store(rootname, &endpointObject)
  220. log.Println("Adding Proxy Rule: ", rootname+" to "+domain)
  221. return nil
  222. }
  223. /*
  224. Remove routing from RP
  225. */
  226. func (router *Router) RemoveProxy(ptype string, key string) error {
  227. //fmt.Println(ptype, key)
  228. if ptype == "vdir" {
  229. router.ProxyEndpoints.Delete(key)
  230. return nil
  231. } else if ptype == "subd" {
  232. router.SubdomainEndpoint.Delete(key)
  233. return nil
  234. }
  235. return errors.New("invalid ptype")
  236. }
  237. /*
  238. Add an default router for the proxy server
  239. */
  240. func (router *Router) SetRootProxy(proxyLocation string, requireTLS bool) error {
  241. if proxyLocation[len(proxyLocation)-1:] == "/" {
  242. proxyLocation = proxyLocation[:len(proxyLocation)-1]
  243. }
  244. webProxyEndpoint := proxyLocation
  245. if requireTLS {
  246. webProxyEndpoint = "https://" + webProxyEndpoint
  247. } else {
  248. webProxyEndpoint = "http://" + webProxyEndpoint
  249. }
  250. //Create a new proxy agent for this root
  251. path, err := url.Parse(webProxyEndpoint)
  252. if err != nil {
  253. return err
  254. }
  255. proxy := dpcore.NewDynamicProxyCore(path, "")
  256. rootEndpoint := ProxyEndpoint{
  257. Root: "/",
  258. Domain: proxyLocation,
  259. RequireTLS: requireTLS,
  260. Proxy: proxy,
  261. }
  262. router.Root = &rootEndpoint
  263. return nil
  264. }
  265. // Do all the main routing in here
  266. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  267. //Check if this is a redirection url
  268. if h.Parent.redirectionRuleTable.IsRedirectable(r) {
  269. h.Parent.redirectionRuleTable.HandleRedirect(w, r)
  270. return
  271. }
  272. domainOnly := r.Host
  273. if strings.Contains(r.Host, ":") {
  274. hostPath := strings.Split(r.Host, ":")
  275. domainOnly = hostPath[0]
  276. }
  277. if strings.Contains(r.Host, ".") {
  278. //This might be a subdomain. See if there are any subdomain proxy router for this
  279. //Remove the port if any
  280. sep := h.Parent.getSubdomainProxyEndpointFromHostname(domainOnly)
  281. if sep != nil {
  282. h.subdomainRequest(w, r, sep)
  283. return
  284. }
  285. }
  286. //Clean up the request URI
  287. proxyingPath := strings.TrimSpace(r.RequestURI)
  288. targetProxyEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath)
  289. if targetProxyEndpoint != nil {
  290. h.proxyRequest(w, r, targetProxyEndpoint)
  291. } else {
  292. h.proxyRequest(w, r, h.Parent.Root)
  293. }
  294. }