dynamicproxy.go 7.8 KB

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