dynamicproxy.go 11 KB

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