dynamicproxy.go 8.0 KB

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