1
0

dynamicproxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package dynamicproxy
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "log"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
  16. "imuslab.com/zoraxy/mod/utils"
  17. )
  18. /*
  19. Zoraxy Dynamic Proxy
  20. */
  21. func NewDynamicProxy(option RouterOption) (*Router, error) {
  22. proxyMap := sync.Map{}
  23. domainMap := sync.Map{}
  24. thisRouter := Router{
  25. Option: &option,
  26. ProxyEndpoints: &proxyMap,
  27. SubdomainEndpoint: &domainMap,
  28. Running: false,
  29. server: nil,
  30. routingRules: []*RoutingRule{},
  31. tldMap: map[string]int{},
  32. }
  33. thisRouter.mux = &ProxyHandler{
  34. Parent: &thisRouter,
  35. }
  36. //Prase the tld map for tld redirection in main router
  37. //See Server.go declarations
  38. if len(rawTldMap) > 0 {
  39. json.Unmarshal(rawTldMap, &thisRouter.tldMap)
  40. }
  41. return &thisRouter, nil
  42. }
  43. // Update TLS setting in runtime. Will restart the proxy server
  44. // if it is already running in the background
  45. func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
  46. router.Option.UseTls = tlsEnabled
  47. router.Restart()
  48. }
  49. // Update TLS Version in runtime. Will restart proxy server if running.
  50. // Set this to true to force TLS 1.2 or above
  51. func (router *Router) UpdateTLSVersion(requireLatest bool) {
  52. router.Option.ForceTLSLatest = requireLatest
  53. router.Restart()
  54. }
  55. // Update https redirect, which will require updates
  56. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  57. router.Option.ForceHttpsRedirect = useRedirect
  58. router.Restart()
  59. }
  60. // Start the dynamic routing
  61. func (router *Router) StartProxyService() error {
  62. //Create a new server object
  63. if router.server != nil {
  64. return errors.New("Reverse proxy server already running")
  65. }
  66. //Check if root route is set
  67. if router.Root == nil {
  68. return errors.New("Reverse proxy router root not set")
  69. }
  70. //Load root options from file
  71. rootConfigFilepath := "conf/root_config.json"
  72. if !utils.FileExists(rootConfigFilepath) {
  73. //Not found. Create a root option
  74. js, _ := json.MarshalIndent(RootRoutingOptions{}, "", " ")
  75. err := os.WriteFile(rootConfigFilepath, js, 0775)
  76. if err != nil {
  77. return errors.New("Unable to write root config to file: " + err.Error())
  78. }
  79. }
  80. newRootOption := RootRoutingOptions{}
  81. rootOptionsBytes, err := os.ReadFile(rootConfigFilepath)
  82. if err != nil {
  83. log.Println("[Error] Unable to read root config file at " + rootConfigFilepath + ": " + err.Error())
  84. return err
  85. }
  86. err = json.Unmarshal(rootOptionsBytes, &newRootOption)
  87. if err != nil {
  88. log.Println("[Error] Unable to parse root config file: " + err.Error())
  89. return err
  90. }
  91. router.RootRoutingOptions = &newRootOption
  92. minVersion := tls.VersionTLS10
  93. if router.Option.ForceTLSLatest {
  94. minVersion = tls.VersionTLS12
  95. }
  96. config := &tls.Config{
  97. GetCertificate: router.Option.TlsManager.GetCert,
  98. MinVersion: uint16(minVersion),
  99. }
  100. if router.Option.UseTls {
  101. //Serve with TLS mode
  102. ln, err := tls.Listen("tcp", ":"+strconv.Itoa(router.Option.Port), config)
  103. if err != nil {
  104. log.Println(err)
  105. router.Running = false
  106. return err
  107. }
  108. router.tlsListener = ln
  109. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  110. router.Running = true
  111. if router.Option.Port != 80 && router.Option.ForceHttpsRedirect {
  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. protocol := "https://"
  117. if router.Option.Port == 443 {
  118. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  119. } else {
  120. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  121. }
  122. }),
  123. ReadTimeout: 3 * time.Second,
  124. WriteTimeout: 3 * time.Second,
  125. IdleTimeout: 120 * time.Second,
  126. }
  127. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  128. //Create a redirection stop channel
  129. stopChan := make(chan bool)
  130. //Start a blocking wait for shutting down the http to https redirection server
  131. go func() {
  132. <-stopChan
  133. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  134. defer cancel()
  135. httpServer.Shutdown(ctx)
  136. log.Println("HTTP to HTTPS redirection listener stopped")
  137. }()
  138. //Start the http server that listens to port 80 and redirect to 443
  139. go func() {
  140. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  141. //Unable to startup port 80 listener. Handle shutdown process gracefully
  142. stopChan <- true
  143. log.Fatalf("Could not start server: %v\n", err)
  144. }
  145. }()
  146. router.tlsRedirectStop = stopChan
  147. }
  148. //Start the TLS server
  149. log.Println("Reverse proxy service started in the background (TLS mode)")
  150. go func() {
  151. if err := router.server.Serve(ln); err != nil && err != http.ErrServerClosed {
  152. log.Fatalf("Could not start server: %v\n", err)
  153. }
  154. }()
  155. } else {
  156. //Serve with non TLS mode
  157. router.tlsListener = nil
  158. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  159. router.Running = true
  160. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  161. go func() {
  162. router.server.ListenAndServe()
  163. //log.Println("[DynamicProxy] " + err.Error())
  164. }()
  165. }
  166. return nil
  167. }
  168. func (router *Router) StopProxyService() error {
  169. if router.server == nil {
  170. return errors.New("Reverse proxy server already stopped")
  171. }
  172. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  173. defer cancel()
  174. err := router.server.Shutdown(ctx)
  175. if err != nil {
  176. return err
  177. }
  178. if router.tlsListener != nil {
  179. router.tlsListener.Close()
  180. }
  181. if router.tlsRedirectStop != nil {
  182. router.tlsRedirectStop <- true
  183. }
  184. //Discard the server object
  185. router.tlsListener = nil
  186. router.server = nil
  187. router.Running = false
  188. router.tlsRedirectStop = nil
  189. return nil
  190. }
  191. // Restart the current router if it is running.
  192. func (router *Router) Restart() error {
  193. //Stop the router if it is already running
  194. var err error = nil
  195. if router.Running {
  196. err := router.StopProxyService()
  197. if err != nil {
  198. return err
  199. }
  200. // Start the server
  201. err = router.StartProxyService()
  202. if err != nil {
  203. return err
  204. }
  205. }
  206. return err
  207. }
  208. /*
  209. Check if a given request is accessed via a proxied subdomain
  210. */
  211. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  212. hostname := r.Header.Get("X-Forwarded-Host")
  213. if hostname == "" {
  214. hostname = r.Host
  215. }
  216. hostname = strings.Split(hostname, ":")[0]
  217. subdEndpoint := router.getSubdomainProxyEndpointFromHostname(hostname)
  218. return subdEndpoint != nil
  219. }
  220. /*
  221. Add an URL into a custom proxy services
  222. */
  223. func (router *Router) AddVirtualDirectoryProxyService(options *VdirOptions) error {
  224. domain := options.Domain
  225. if domain[len(domain)-1:] == "/" {
  226. domain = domain[:len(domain)-1]
  227. }
  228. /*
  229. if rootname[len(rootname)-1:] == "/" {
  230. rootname = rootname[:len(rootname)-1]
  231. }
  232. */
  233. webProxyEndpoint := domain
  234. if options.RequireTLS {
  235. webProxyEndpoint = "https://" + webProxyEndpoint
  236. } else {
  237. webProxyEndpoint = "http://" + webProxyEndpoint
  238. }
  239. //Create a new proxy agent for this root
  240. path, err := url.Parse(webProxyEndpoint)
  241. if err != nil {
  242. return err
  243. }
  244. proxy := dpcore.NewDynamicProxyCore(path, options.RootName, options.SkipCertValidations)
  245. endpointObject := ProxyEndpoint{
  246. ProxyType: ProxyType_Vdir,
  247. RootOrMatchingDomain: options.RootName,
  248. Domain: domain,
  249. RequireTLS: options.RequireTLS,
  250. SkipCertValidations: options.SkipCertValidations,
  251. RequireBasicAuth: options.RequireBasicAuth,
  252. BasicAuthCredentials: options.BasicAuthCredentials,
  253. BasicAuthExceptionRules: options.BasicAuthExceptionRules,
  254. Proxy: proxy,
  255. }
  256. router.ProxyEndpoints.Store(options.RootName, &endpointObject)
  257. log.Println("Registered Proxy Rule: ", options.RootName+" to "+domain)
  258. return nil
  259. }
  260. /*
  261. Load routing from RP
  262. */
  263. func (router *Router) LoadProxy(ptype string, key string) (*ProxyEndpoint, error) {
  264. if ptype == "vdir" {
  265. proxy, ok := router.ProxyEndpoints.Load(key)
  266. if !ok {
  267. return nil, errors.New("target proxy not found")
  268. }
  269. targetProxy := proxy.(*ProxyEndpoint)
  270. targetProxy.parent = router
  271. return targetProxy, nil
  272. } else if ptype == "subd" {
  273. proxy, ok := router.SubdomainEndpoint.Load(key)
  274. if !ok {
  275. return nil, errors.New("target proxy not found")
  276. }
  277. targetProxy := proxy.(*ProxyEndpoint)
  278. targetProxy.parent = router
  279. return targetProxy, nil
  280. }
  281. return nil, errors.New("unsupported ptype")
  282. }
  283. /*
  284. Add an default router for the proxy server
  285. */
  286. func (router *Router) SetRootProxy(options *RootOptions) error {
  287. proxyLocation := options.ProxyLocation
  288. if proxyLocation[len(proxyLocation)-1:] == "/" {
  289. proxyLocation = proxyLocation[:len(proxyLocation)-1]
  290. }
  291. webProxyEndpoint := proxyLocation
  292. if options.RequireTLS {
  293. webProxyEndpoint = "https://" + webProxyEndpoint
  294. } else {
  295. webProxyEndpoint = "http://" + webProxyEndpoint
  296. }
  297. //Create a new proxy agent for this root
  298. path, err := url.Parse(webProxyEndpoint)
  299. if err != nil {
  300. return err
  301. }
  302. proxy := dpcore.NewDynamicProxyCore(path, "", options.SkipCertValidations)
  303. rootEndpoint := ProxyEndpoint{
  304. ProxyType: ProxyType_Vdir,
  305. RootOrMatchingDomain: "/",
  306. Domain: proxyLocation,
  307. RequireTLS: options.RequireTLS,
  308. SkipCertValidations: options.SkipCertValidations,
  309. RequireBasicAuth: options.RequireBasicAuth,
  310. BasicAuthCredentials: options.BasicAuthCredentials,
  311. BasicAuthExceptionRules: options.BasicAuthExceptionRules,
  312. Proxy: proxy,
  313. }
  314. router.Root = &rootEndpoint
  315. return nil
  316. }
  317. // Helpers to export the syncmap for easier processing
  318. func (r *Router) GetSDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  319. m := make(map[string]*ProxyEndpoint)
  320. r.SubdomainEndpoint.Range(func(key, value interface{}) bool {
  321. k, ok := key.(string)
  322. if !ok {
  323. return true
  324. }
  325. v, ok := value.(*ProxyEndpoint)
  326. if !ok {
  327. return true
  328. }
  329. m[k] = v
  330. return true
  331. })
  332. return m
  333. }
  334. func (r *Router) GetVDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  335. m := make(map[string]*ProxyEndpoint)
  336. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  337. k, ok := key.(string)
  338. if !ok {
  339. return true
  340. }
  341. v, ok := value.(*ProxyEndpoint)
  342. if !ok {
  343. return true
  344. }
  345. m[k] = v
  346. return true
  347. })
  348. return m
  349. }