123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351 |
- package main
- import (
- "archive/zip"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "imuslab.com/zoraxy/mod/dynamicproxy"
- "imuslab.com/zoraxy/mod/utils"
- )
- type Record struct {
- ProxyType string
- Rootname string
- ProxyTarget string
- UseTLS bool
- BypassGlobalTLS bool
- SkipTlsValidation bool
- RequireBasicAuth bool
- BasicAuthCredentials []*dynamicproxy.BasicAuthCredentials
- BasicAuthExceptionRules []*dynamicproxy.BasicAuthExceptionRule
- }
- func LoadReverseProxyConfig(configFilepath string) error {
-
- endpointConfig, err := os.ReadFile(configFilepath)
- if err != nil {
- return err
- }
-
- thisConfigEndpoint := dynamicproxy.ProxyEndpoint{}
- err = json.Unmarshal(endpointConfig, &thisConfigEndpoint)
- if err != nil {
- return err
- }
-
- if thisConfigEndpoint.RootOrMatchingDomain == "" {
- thisConfigEndpoint.RootOrMatchingDomain = "/"
- }
- if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyType_Root {
-
- rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
- if err != nil {
- return err
- }
- dynamicProxyRouter.SetProxyRouteAsRoot(rootProxyEndpoint)
- } else if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyType_Host {
-
- readyProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
- if err != nil {
- return err
- }
- dynamicProxyRouter.AddProxyRouteToRuntime(readyProxyEndpoint)
- } else {
- return errors.New("not supported proxy type")
- }
- SystemWideLogger.PrintAndLog("Proxy", thisConfigEndpoint.RootOrMatchingDomain+" -> "+thisConfigEndpoint.Domain+" routing rule loaded", nil)
- return nil
- }
- func filterProxyConfigFilename(filename string) string {
-
- filename = strings.ReplaceAll(filename, "*", "(ST)")
- filename = strings.ReplaceAll(filename, "?", "(QM)")
- filename = strings.ReplaceAll(filename, "[", "(OB)")
- filename = strings.ReplaceAll(filename, "]", "(CB)")
- filename = strings.ReplaceAll(filename, "#", "(HT)")
- return filepath.ToSlash(filename)
- }
- func SaveReverseProxyConfig(endpoint *dynamicproxy.ProxyEndpoint) error {
-
- filename := filepath.Join("./conf/proxy/", endpoint.RootOrMatchingDomain+".config")
- if endpoint.ProxyType == dynamicproxy.ProxyType_Root {
- filename = "./conf/proxy/root.config"
- }
- filename = filterProxyConfigFilename(filename)
-
- js, err := json.MarshalIndent(endpoint, "", " ")
- if err != nil {
- return err
- }
- os.WriteFile(filename, js, 0775)
- return nil
- }
- func RemoveReverseProxyConfig(endpoint string) error {
- filename := filepath.Join("./conf/proxy/", endpoint+".config")
- if endpoint == "/" {
- filename = "./conf/proxy/root.config"
- }
- filename = filterProxyConfigFilename(filename)
- if !utils.FileExists(filename) {
- return errors.New("target endpoint not exists")
- }
- return os.Remove(filename)
- }
- func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
-
- rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&dynamicproxy.ProxyEndpoint{
- ProxyType: dynamicproxy.ProxyType_Root,
- RootOrMatchingDomain: "/",
- Domain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
- RequireTLS: false,
- BypassGlobalTLS: false,
- SkipCertValidations: false,
- VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
- RequireBasicAuth: false,
- BasicAuthCredentials: []*dynamicproxy.BasicAuthCredentials{},
- BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
- DefaultSiteOption: dynamicproxy.DefaultSite_InternalStaticWebServer,
- DefaultSiteValue: "",
- })
- if err != nil {
- return nil, err
- }
- return rootProxyEndpoint, nil
- }
- func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
- includeSysDBRaw, err := utils.GetPara(r, "includeDB")
- includeSysDB := false
- if includeSysDBRaw == "true" {
-
-
- sysdb.ReadOnly = true
- includeSysDB = true
- }
-
- folderPath := "./conf/"
-
- w.Header().Set("Content-Type", "application/zip")
-
- w.Header().Set("Content-Disposition", "attachment; filename=\"config.zip\"")
-
- zipWriter := zip.NewWriter(w)
- defer zipWriter.Close()
-
- err = filepath.Walk(folderPath, func(filePath string, fileInfo os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- if folderPath == filePath {
-
- return nil
- }
-
- if !utils.IsDir(filePath) {
- zipFile, err := zipWriter.Create(filePath)
- if err != nil {
- return err
- }
-
- file, err := os.Open(filePath)
- if err != nil {
- return err
- }
- defer file.Close()
-
- _, err = io.Copy(zipFile, file)
- if err != nil {
- return err
- }
- }
- return nil
- })
- if includeSysDB {
-
- zipFile, err := zipWriter.Create("sys.db")
- if err != nil {
- SystemWideLogger.PrintAndLog("Backup", "Unable to zip sysdb", err)
- return
- }
-
- file, err := os.Open("sys.db")
- if err != nil {
- SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
- return
- }
- defer file.Close()
-
- _, err = io.Copy(zipFile, file)
- if err != nil {
- SystemWideLogger.Println(err)
- return
- }
-
- sysdb.ReadOnly = false
- }
- if err != nil {
-
- http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
- return
- }
- }
- func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
-
- if r.Method != http.MethodPost {
- http.Error(w, "Invalid request method", http.StatusBadRequest)
- return
- }
-
- r.ParseMultipartForm(10 << 20)
-
- file, handler, err := r.FormFile("file")
- if err != nil {
- http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
- return
- }
- defer file.Close()
- if filepath.Ext(handler.Filename) != ".zip" {
- http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
- return
- }
-
- targetDir := "./conf"
- if utils.FileExists(targetDir) {
-
- os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
- }
- err = os.MkdirAll(targetDir, os.ModePerm)
- if err != nil {
- http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
- return
- }
-
- zipReader, err := zip.NewReader(file, handler.Size)
- if err != nil {
- http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
- return
- }
- restoreDatabase := false
-
- for _, zipFile := range zipReader.File {
-
- rc, err := zipFile.Open()
- if err != nil {
- http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
- return
- }
- defer rc.Close()
-
- zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
- fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
- if zipFile.Name == "sys.db" {
-
- sysdb.Close()
- restoreDatabase = true
- } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
-
- http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
- return
- }
-
- if !utils.FileExists(filepath.Dir(zipFile.Name)) {
- os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
- }
-
- newFile, err := os.Create(zipFile.Name)
- if err != nil {
- http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
- return
- }
- defer newFile.Close()
-
- _, err = io.Copy(newFile, rc)
- if err != nil {
- http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
- return
- }
- }
-
- w.WriteHeader(http.StatusOK)
- SystemWideLogger.Println("Configuration restored")
- fmt.Fprintln(w, "Configuration restored")
- if restoreDatabase {
- go func() {
- SystemWideLogger.Println("Database altered. Restarting in 3 seconds...")
- time.Sleep(3 * time.Second)
- os.Exit(0)
- }()
- }
- }
|