123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433 |
- package dynamicproxy
- import (
- "context"
- "crypto/tls"
- "encoding/json"
- "errors"
- "log"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "sync"
- "time"
- "imuslab.com/zoraxy/mod/dynamicproxy/dpcore"
- )
- func NewDynamicProxy(option RouterOption) (*Router, error) {
- proxyMap := sync.Map{}
- domainMap := sync.Map{}
- thisRouter := Router{
- Option: &option,
- ProxyEndpoints: &proxyMap,
- SubdomainEndpoint: &domainMap,
- Running: false,
- server: nil,
- routingRules: []*RoutingRule{},
- tldMap: map[string]int{},
- }
- thisRouter.mux = &ProxyHandler{
- Parent: &thisRouter,
- }
-
-
- if len(rawTldMap) > 0 {
- json.Unmarshal(rawTldMap, &thisRouter.tldMap)
- }
- return &thisRouter, nil
- }
- func (router *Router) UpdateTLSSetting(tlsEnabled bool) {
- router.Option.UseTls = tlsEnabled
- router.Restart()
- }
- func (router *Router) UpdateTLSVersion(requireLatest bool) {
- router.Option.ForceTLSLatest = requireLatest
- router.Restart()
- }
- func (router *Router) UpdatePort80ListenerState(useRedirect bool) {
- router.Option.ListenOnPort80 = useRedirect
- router.Restart()
- }
- func (router *Router) UpdateHttpToHttpsRedirectSetting(useRedirect bool) {
- router.Option.ForceHttpsRedirect = useRedirect
- router.Restart()
- }
- func (router *Router) StartProxyService() error {
-
- if router.server != nil {
- return errors.New("Reverse proxy server already running")
- }
-
- if router.Root == nil {
- return errors.New("Reverse proxy router root not set")
- }
-
- loadedRootOption, err := loadRootRoutingOptionsFromFile()
- if err != nil {
- return err
- }
- router.RootRoutingOptions = loadedRootOption
- minVersion := tls.VersionTLS10
- if router.Option.ForceTLSLatest {
- minVersion = tls.VersionTLS12
- }
- config := &tls.Config{
- GetCertificate: router.Option.TlsManager.GetCert,
- MinVersion: uint16(minVersion),
- }
- if router.Option.UseTls {
-
- router.server = &http.Server{
- Addr: ":" + strconv.Itoa(router.Option.Port),
- Handler: router.mux,
- TLSConfig: config,
- }
- router.Running = true
- if router.Option.Port != 80 && router.Option.ListenOnPort80 {
-
- httpServer := &http.Server{
- Addr: ":80",
- Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-
- domainOnly := r.Host
- if strings.Contains(r.Host, ":") {
- hostPath := strings.Split(r.Host, ":")
- domainOnly = hostPath[0]
- }
- sep := router.getSubdomainProxyEndpointFromHostname(domainOnly)
- if sep != nil && sep.BypassGlobalTLS {
-
- originalHostHeader := r.Host
- if r.URL != nil {
- r.Host = r.URL.Host
- } else {
-
- r.URL, _ = url.Parse(originalHostHeader)
- }
- sep.Proxy.ServeHTTP(w, r, &dpcore.ResponseRewriteRuleSet{
- ProxyDomain: sep.Domain,
- OriginalHost: originalHostHeader,
- UseTLS: sep.RequireTLS,
- PathPrefix: "",
- })
- return
- }
- if router.Option.ForceHttpsRedirect {
-
- protocol := "https://"
- if router.Option.Port == 443 {
- http.Redirect(w, r, protocol+r.Host+r.RequestURI, http.StatusTemporaryRedirect)
- } else {
- http.Redirect(w, r, protocol+r.Host+":"+strconv.Itoa(router.Option.Port)+r.RequestURI, http.StatusTemporaryRedirect)
- }
- } else {
-
- if sep != nil {
-
- w.WriteHeader(http.StatusBadRequest)
- w.Write([]byte("400 - Bad Request"))
- } else {
-
- http.NotFound(w, r)
- }
- }
- }),
- ReadTimeout: 3 * time.Second,
- WriteTimeout: 3 * time.Second,
- IdleTimeout: 120 * time.Second,
- }
- log.Println("Starting HTTP-to-HTTPS redirector (port 80)")
-
- stopChan := make(chan bool)
-
- go func() {
- <-stopChan
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- httpServer.Shutdown(ctx)
- log.Println("HTTP to HTTPS redirection listener stopped")
- }()
-
- go func() {
- if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
-
- stopChan <- true
- log.Fatalf("Could not start redirection server: %v\n", err)
- }
- }()
- router.tlsRedirectStop = stopChan
- }
-
- log.Println("Reverse proxy service started in the background (TLS mode)")
- go func() {
- if err := router.server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
- log.Fatalf("Could not start proxy server: %v\n", err)
- }
- }()
- } else {
-
- router.tlsListener = nil
- router.server = &http.Server{Addr: ":" + strconv.Itoa(router.Option.Port), Handler: router.mux}
- router.Running = true
- log.Println("Reverse proxy service started in the background (Plain HTTP mode)")
- go func() {
- router.server.ListenAndServe()
-
- }()
- }
- return nil
- }
- func (router *Router) StopProxyService() error {
- if router.server == nil {
- return errors.New("Reverse proxy server already stopped")
- }
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- err := router.server.Shutdown(ctx)
- if err != nil {
- return err
- }
- if router.tlsListener != nil {
- router.tlsListener.Close()
- }
- if router.tlsRedirectStop != nil {
- router.tlsRedirectStop <- true
- }
-
- router.tlsListener = nil
- router.server = nil
- router.Running = false
- router.tlsRedirectStop = nil
- return nil
- }
- func (router *Router) Restart() error {
-
- var err error = nil
- if router.Running {
- err := router.StopProxyService()
- if err != nil {
- return err
- }
-
- err = router.StartProxyService()
- if err != nil {
- return err
- }
- }
- return err
- }
- func (router *Router) IsProxiedSubdomain(r *http.Request) bool {
- hostname := r.Header.Get("X-Forwarded-Host")
- if hostname == "" {
- hostname = r.Host
- }
- hostname = strings.Split(hostname, ":")[0]
- subdEndpoint := router.getSubdomainProxyEndpointFromHostname(hostname)
- return subdEndpoint != nil
- }
- func (router *Router) AddVirtualDirectoryProxyService(options *VdirOptions) error {
- domain := options.Domain
- if domain[len(domain)-1:] == "/" {
- domain = domain[:len(domain)-1]
- }
-
- webProxyEndpoint := domain
- if options.RequireTLS {
- webProxyEndpoint = "https://" + webProxyEndpoint
- } else {
- webProxyEndpoint = "http://" + webProxyEndpoint
- }
-
- path, err := url.Parse(webProxyEndpoint)
- if err != nil {
- return err
- }
- proxy := dpcore.NewDynamicProxyCore(path, options.RootName, options.SkipCertValidations)
- endpointObject := ProxyEndpoint{
- ProxyType: ProxyType_Vdir,
- RootOrMatchingDomain: options.RootName,
- Domain: domain,
- RequireTLS: options.RequireTLS,
- SkipCertValidations: options.SkipCertValidations,
- RequireBasicAuth: options.RequireBasicAuth,
- BasicAuthCredentials: options.BasicAuthCredentials,
- BasicAuthExceptionRules: options.BasicAuthExceptionRules,
- Proxy: proxy,
- }
- router.ProxyEndpoints.Store(options.RootName, &endpointObject)
- log.Println("Registered Proxy Rule: ", options.RootName+" to "+domain)
- return nil
- }
- func (router *Router) LoadProxy(ptype string, key string) (*ProxyEndpoint, error) {
- if ptype == "vdir" {
- proxy, ok := router.ProxyEndpoints.Load(key)
- if !ok {
- return nil, errors.New("target proxy not found")
- }
- targetProxy := proxy.(*ProxyEndpoint)
- targetProxy.parent = router
- return targetProxy, nil
- } else if ptype == "subd" {
- proxy, ok := router.SubdomainEndpoint.Load(key)
- if !ok {
- return nil, errors.New("target proxy not found")
- }
- targetProxy := proxy.(*ProxyEndpoint)
- targetProxy.parent = router
- return targetProxy, nil
- }
- return nil, errors.New("unsupported ptype")
- }
- func (router *Router) SetRootProxy(options *RootOptions) error {
- proxyLocation := options.ProxyLocation
- if proxyLocation[len(proxyLocation)-1:] == "/" {
- proxyLocation = proxyLocation[:len(proxyLocation)-1]
- }
- webProxyEndpoint := proxyLocation
- if options.RequireTLS {
- webProxyEndpoint = "https://" + webProxyEndpoint
- } else {
- webProxyEndpoint = "http://" + webProxyEndpoint
- }
-
- path, err := url.Parse(webProxyEndpoint)
- if err != nil {
- return err
- }
- proxy := dpcore.NewDynamicProxyCore(path, "", options.SkipCertValidations)
- rootEndpoint := ProxyEndpoint{
- ProxyType: ProxyType_Vdir,
- RootOrMatchingDomain: "/",
- Domain: proxyLocation,
- RequireTLS: options.RequireTLS,
- SkipCertValidations: options.SkipCertValidations,
- RequireBasicAuth: options.RequireBasicAuth,
- BasicAuthCredentials: options.BasicAuthCredentials,
- BasicAuthExceptionRules: options.BasicAuthExceptionRules,
- Proxy: proxy,
- }
- router.Root = &rootEndpoint
- return nil
- }
- func (r *Router) GetSDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
- m := make(map[string]*ProxyEndpoint)
- r.SubdomainEndpoint.Range(func(key, value interface{}) bool {
- k, ok := key.(string)
- if !ok {
- return true
- }
- v, ok := value.(*ProxyEndpoint)
- if !ok {
- return true
- }
- m[k] = v
- return true
- })
- return m
- }
- func (r *Router) GetVDProxyEndpointsAsMap() map[string]*ProxyEndpoint {
- m := make(map[string]*ProxyEndpoint)
- r.ProxyEndpoints.Range(func(key, value interface{}) bool {
- k, ok := key.(string)
- if !ok {
- return true
- }
- v, ok := value.(*ProxyEndpoint)
- if !ok {
- return true
- }
- m[k] = v
- return true
- })
- return m
- }
|