dynamicproxy.go 7.8 KB

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