dynamicproxy.go 11 KB

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