dynamicproxy.go 8.4 KB

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