dynamicproxy.go 8.0 KB

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