dynamicproxy.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. thisRouter := Router{
  22. Option: &option,
  23. ProxyEndpoints: &proxyMap,
  24. Running: false,
  25. server: nil,
  26. routingRules: []*RoutingRule{},
  27. tldMap: map[string]int{},
  28. }
  29. thisRouter.mux = &ProxyHandler{
  30. Parent: &thisRouter,
  31. }
  32. //Prase the tld map for tld redirection in main router
  33. //See Server.go declarations
  34. if len(rawTldMap) > 0 {
  35. json.Unmarshal(rawTldMap, &thisRouter.tldMap)
  36. }
  37. return &thisRouter, nil
  38. }
  39. // Update TLS setting in runtime. Will restart the proxy server
  40. // if it is already running in the background
  41. func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
  42. router.Option.UseTls = tlsEnabled
  43. router.Restart()
  44. }
  45. // Update TLS Version in runtime. Will restart proxy server if running.
  46. // Set this to true to force TLS 1.2 or above
  47. func (router *Router) UpdateTLSVersion(requireLatest bool) {
  48. router.Option.ForceTLSLatest = requireLatest
  49. router.Restart()
  50. }
  51. // Update port 80 listener state
  52. func (router *Router) UpdatePort80ListenerState(useRedirect bool) {
  53. router.Option.ListenOnPort80 = useRedirect
  54. router.Restart()
  55. }
  56. // Update https redirect, which will require updates
  57. func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
  58. router.Option.ForceHttpsRedirect = useRedirect
  59. router.Restart()
  60. }
  61. // Start the dynamic routing
  62. func (router *Router) StartProxyService() error {
  63. //Create a new server object
  64. if router.server != nil {
  65. return errors.New("Reverse proxy server already running")
  66. }
  67. //Check if root route is set
  68. if router.Root == nil {
  69. return errors.New("Reverse proxy router root not set")
  70. }
  71. minVersion := tls.VersionTLS10
  72. if router.Option.ForceTLSLatest {
  73. minVersion = tls.VersionTLS12
  74. }
  75. config := &tls.Config{
  76. GetCertificate: router.Option.TlsManager.GetCert,
  77. MinVersion: uint16(minVersion),
  78. }
  79. if router.Option.UseTls {
  80. /*
  81. //Serve with TLS mode
  82. ln, err := tls.Listen("tcp", ":"+strconv.Itoa(router.Option.Port), config)
  83. if err != nil {
  84. log.Println(err)
  85. router.Running = false
  86. return err
  87. }
  88. router.tlsListener = ln
  89. */
  90. router.server = &http.Server{
  91. Addr: ":" + strconv.Itoa(router.Option.Port),
  92. Handler: router.mux,
  93. TLSConfig: config,
  94. }
  95. router.Running = true
  96. if router.Option.Port != 80 && router.Option.ListenOnPort80 {
  97. //Add a 80 to 443 redirector
  98. httpServer := &http.Server{
  99. Addr: ":80",
  100. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  101. //Check if the domain requesting allow non TLS mode
  102. domainOnly := r.Host
  103. if strings.Contains(r.Host, ":") {
  104. hostPath := strings.Split(r.Host, ":")
  105. domainOnly = hostPath[0]
  106. }
  107. sep := router.getProxyEndpointFromHostname(domainOnly)
  108. if sep != nil && sep.BypassGlobalTLS {
  109. //Allow routing via non-TLS handler
  110. originalHostHeader := r.Host
  111. if r.URL != nil {
  112. r.Host = r.URL.Host
  113. } else {
  114. //Fallback when the upstream proxy screw something up in the header
  115. r.URL, _ = url.Parse(originalHostHeader)
  116. }
  117. sep.proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
  118. ProxyDomain: sep.Domain,
  119. OriginalHost: originalHostHeader,
  120. UseTLS: sep.RequireTLS,
  121. PathPrefix: "",
  122. })
  123. return
  124. }
  125. if router.Option.ForceHttpsRedirect {
  126. //Redirect to https is enabled
  127. protocol := "https://"
  128. if router.Option.Port == 443 {
  129. http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
  130. } else {
  131. http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
  132. }
  133. } else {
  134. //Do not do redirection
  135. if sep != nil {
  136. //Sub-domain exists but not allow non-TLS access
  137. w.WriteHeader(http.StatusBadRequest)
  138. w.Write([]byte("400 - Bad Request"))
  139. } else {
  140. //No defined sub-domain
  141. http.NotFound(w, r)
  142. }
  143. }
  144. }),
  145. ReadTimeout: 3 * time.Second,
  146. WriteTimeout: 3 * time.Second,
  147. IdleTimeout: 120 * time.Second,
  148. }
  149. log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
  150. //Create a redirection stop channel
  151. stopChan := make(chan bool)
  152. //Start a blocking wait for shutting down the http to https redirection server
  153. go func() {
  154. <-stopChan
  155. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  156. defer cancel()
  157. httpServer.Shutdown(ctx)
  158. log.Println("HTTP to HTTPS redirection listener stopped")
  159. }()
  160. //Start the http server that listens to port 80 and redirect to 443
  161. go func() {
  162. if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  163. //Unable to startup port 80 listener. Handle shutdown process gracefully
  164. stopChan <- true
  165. log.Fatalf("Could not start redirection server: %v\n", err)
  166. }
  167. }()
  168. router.tlsRedirectStop = stopChan
  169. }
  170. //Start the TLS server
  171. log.Println("Reverse proxy service started in the background (TLS mode)")
  172. go func() {
  173. if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
  174. log.Fatalf("Could not start proxy server: %v\n", err)
  175. }
  176. }()
  177. } else {
  178. //Serve with non TLS mode
  179. router.tlsListener = nil
  180. router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
  181. router.Running = true
  182. log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
  183. go func() {
  184. router.server.ListenAndServe()
  185. //log.Println("[DynamicProxy] " + err.Error())
  186. }()
  187. }
  188. return nil
  189. }
  190. func (router *Router) StopProxyService() error {
  191. if router.server == nil {
  192. return errors.New("Reverse proxy server already stopped")
  193. }
  194. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  195. defer cancel()
  196. err := router.server.Shutdown(ctx)
  197. if err != nil {
  198. return err
  199. }
  200. if router.tlsListener != nil {
  201. router.tlsListener.Close()
  202. }
  203. if router.tlsRedirectStop != nil {
  204. router.tlsRedirectStop <- true
  205. }
  206. //Discard the server object
  207. router.tlsListener = nil
  208. router.server = nil
  209. router.Running = false
  210. router.tlsRedirectStop = nil
  211. return nil
  212. }
  213. // Restart the current router if it is running.
  214. func (router *Router) Restart() error {
  215. //Stop the router if it is already running
  216. var err error = nil
  217. if router.Running {
  218. err := router.StopProxyService()
  219. if err != nil {
  220. return err
  221. }
  222. // Start the server
  223. err = router.StartProxyService()
  224. if err != nil {
  225. return err
  226. }
  227. }
  228. return err
  229. }
  230. /*
  231. Check if a given request is accessed via a proxied subdomain
  232. */
  233. func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
  234. hostname := r.Header.Get("X-Forwarded-Host")
  235. if hostname == "" {
  236. hostname = r.Host
  237. }
  238. hostname = strings.Split(hostname, ":")[0]
  239. subdEndpoint := router.getProxyEndpointFromHostname(hostname)
  240. return subdEndpoint != nil
  241. }
  242. /*
  243. Load routing from RP
  244. */
  245. func (router *Router) LoadProxy(matchingDomain string) (*ProxyEndpoint, error) {
  246. var targetProxyEndpoint *ProxyEndpoint
  247. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  248. key, ok := key.(string)
  249. if !ok {
  250. return true
  251. }
  252. v, ok := value.(*ProxyEndpoint)
  253. if !ok {
  254. return true
  255. }
  256. if key == matchingDomain {
  257. targetProxyEndpoint = v
  258. }
  259. return true
  260. })
  261. if targetProxyEndpoint == nil {
  262. return nil, errors.New("target routing rule not found")
  263. }
  264. return targetProxyEndpoint, nil
  265. }
  266. // Deep copy a proxy endpoint, excluding runtime paramters
  267. func CopyEndpoint(endpoint *ProxyEndpoint) *ProxyEndpoint {
  268. js, _ := json.Marshal(endpoint)
  269. newProxyEndpoint := ProxyEndpoint{}
  270. err := json.Unmarshal(js, &newProxyEndpoint)
  271. if err != nil {
  272. return nil
  273. }
  274. return &newProxyEndpoint
  275. }
  276. func (r *Router) GetProxyEndpointsAsMap() map[string]*ProxyEndpoint {
  277. m := make(map[string]*ProxyEndpoint)
  278. r.ProxyEndpoints.Range(func(key, value interface{}) bool {
  279. k, ok := key.(string)
  280. if !ok {
  281. return true
  282. }
  283. v, ok := value.(*ProxyEndpoint)
  284. if !ok {
  285. return true
  286. }
  287. m[k] = v
  288. return true
  289. })
  290. return m
  291. }