config.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package main
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "imuslab.com/zoraxy/mod/dynamicproxy"
  15. "imuslab.com/zoraxy/mod/utils"
  16. )
  17. /*
  18. Reverse Proxy Configs
  19. The following section handle
  20. the reverse proxy configs
  21. */
  22. type Record struct {
  23. ProxyType string
  24. Rootname string
  25. ProxyTarget string
  26. UseTLS bool
  27. BypassGlobalTLS bool
  28. SkipTlsValidation bool
  29. RequireBasicAuth bool
  30. BasicAuthCredentials []*dynamicproxy.BasicAuthCredentials
  31. BasicAuthExceptionRules []*dynamicproxy.BasicAuthExceptionRule
  32. }
  33. /*
  34. Load Reverse Proxy Config from file and append it to current runtime proxy router
  35. */
  36. func LoadReverseProxyConfig(configFilepath string) error {
  37. //Load the config file from disk
  38. endpointConfig, err := os.ReadFile(configFilepath)
  39. if err != nil {
  40. return err
  41. }
  42. //Parse it into dynamic proxy endpoint
  43. thisConfigEndpoint := dynamicproxy.ProxyEndpoint{}
  44. err = json.Unmarshal(endpointConfig, &thisConfigEndpoint)
  45. if err != nil {
  46. return err
  47. }
  48. //Matching domain not set. Assume root
  49. if thisConfigEndpoint.RootOrMatchingDomain == "" {
  50. thisConfigEndpoint.RootOrMatchingDomain = "/"
  51. }
  52. if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyType_Root {
  53. //This is a root config file
  54. rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
  55. if err != nil {
  56. return err
  57. }
  58. dynamicProxyRouter.SetProxyRouteAsRoot(rootProxyEndpoint)
  59. } else if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyType_Host {
  60. //This is a host config file
  61. readyProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
  62. if err != nil {
  63. return err
  64. }
  65. dynamicProxyRouter.AddProxyRouteToRuntime(readyProxyEndpoint)
  66. } else {
  67. return errors.New("not supported proxy type")
  68. }
  69. SystemWideLogger.PrintAndLog("Proxy", thisConfigEndpoint.RootOrMatchingDomain+" -> "+thisConfigEndpoint.Domain+" routing rule loaded", nil)
  70. return nil
  71. }
  72. func filterProxyConfigFilename(filename string) string {
  73. //Filter out wildcard characters
  74. filename = strings.ReplaceAll(filename, "*", "(ST)")
  75. filename = strings.ReplaceAll(filename, "?", "(QM)")
  76. filename = strings.ReplaceAll(filename, "[", "(OB)")
  77. filename = strings.ReplaceAll(filename, "]", "(CB)")
  78. filename = strings.ReplaceAll(filename, "#", "(HT)")
  79. return filepath.ToSlash(filename)
  80. }
  81. func SaveReverseProxyConfig(endpoint *dynamicproxy.ProxyEndpoint) error {
  82. //Get filename for saving
  83. filename := filepath.Join("./conf/proxy/", endpoint.RootOrMatchingDomain+".config")
  84. if endpoint.ProxyType == dynamicproxy.ProxyType_Root {
  85. filename = "./conf/proxy/root.config"
  86. }
  87. filename = filterProxyConfigFilename(filename)
  88. //Save config to file
  89. js, err := json.MarshalIndent(endpoint, "", " ")
  90. if err != nil {
  91. return err
  92. }
  93. return os.WriteFile(filename, js, 0775)
  94. }
  95. func RemoveReverseProxyConfig(endpoint string) error {
  96. filename := filepath.Join("./conf/proxy/", endpoint+".config")
  97. if endpoint == "/" {
  98. filename = "./conf/proxy/root.config"
  99. }
  100. filename = filterProxyConfigFilename(filename)
  101. if !utils.FileExists(filename) {
  102. return errors.New("target endpoint not exists")
  103. }
  104. return os.Remove(filename)
  105. }
  106. // Get the default root config that point to the internal static web server
  107. // this will be used if root config is not found (new deployment / missing root.config file)
  108. func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
  109. //Default settings
  110. rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&dynamicproxy.ProxyEndpoint{
  111. ProxyType: dynamicproxy.ProxyType_Root,
  112. RootOrMatchingDomain: "/",
  113. Domain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
  114. RequireTLS: false,
  115. BypassGlobalTLS: false,
  116. SkipCertValidations: false,
  117. VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
  118. RequireBasicAuth: false,
  119. BasicAuthCredentials: []*dynamicproxy.BasicAuthCredentials{},
  120. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  121. DefaultSiteOption: dynamicproxy.DefaultSite_InternalStaticWebServer,
  122. DefaultSiteValue: "",
  123. })
  124. if err != nil {
  125. return nil, err
  126. }
  127. return rootProxyEndpoint, nil
  128. }
  129. /*
  130. Importer and Exporter of Zoraxy proxy config
  131. */
  132. func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
  133. includeSysDBRaw, err := utils.GetPara(r, "includeDB")
  134. includeSysDB := false
  135. if includeSysDBRaw == "true" {
  136. //Include the system database in backup snapshot
  137. //Temporary set it to read only
  138. sysdb.ReadOnly = true
  139. includeSysDB = true
  140. }
  141. // Specify the folder path to be zipped
  142. folderPath := "./conf/"
  143. // Set the Content-Type header to indicate it's a zip file
  144. w.Header().Set("Content-Type", "application/zip")
  145. // Set the Content-Disposition header to specify the file name
  146. w.Header().Set("Content-Disposition", "attachment; filename=\"config.zip\"")
  147. // Create a zip writer
  148. zipWriter := zip.NewWriter(w)
  149. defer zipWriter.Close()
  150. // Walk through the folder and add files to the zip
  151. err = filepath.Walk(folderPath, func(filePath string, fileInfo os.FileInfo, err error) error {
  152. if err != nil {
  153. return err
  154. }
  155. if folderPath == filePath {
  156. //Skip root folder
  157. return nil
  158. }
  159. // Create a new file in the zip
  160. if !utils.IsDir(filePath) {
  161. zipFile, err := zipWriter.Create(filePath)
  162. if err != nil {
  163. return err
  164. }
  165. // Open the file on disk
  166. file, err := os.Open(filePath)
  167. if err != nil {
  168. return err
  169. }
  170. defer file.Close()
  171. // Copy the file contents to the zip file
  172. _, err = io.Copy(zipFile, file)
  173. if err != nil {
  174. return err
  175. }
  176. }
  177. return nil
  178. })
  179. if includeSysDB {
  180. //Also zip in the sysdb
  181. zipFile, err := zipWriter.Create("sys.db")
  182. if err != nil {
  183. SystemWideLogger.PrintAndLog("Backup", "Unable to zip sysdb", err)
  184. return
  185. }
  186. // Open the file on disk
  187. file, err := os.Open("sys.db")
  188. if err != nil {
  189. SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
  190. return
  191. }
  192. defer file.Close()
  193. // Copy the file contents to the zip file
  194. _, err = io.Copy(zipFile, file)
  195. if err != nil {
  196. SystemWideLogger.Println(err)
  197. return
  198. }
  199. //Restore sysdb state
  200. sysdb.ReadOnly = false
  201. }
  202. if err != nil {
  203. // Handle the error and send an HTTP response with the error message
  204. http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
  205. return
  206. }
  207. }
  208. func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
  209. // Check if the request is a POST with a file upload
  210. if r.Method != http.MethodPost {
  211. http.Error(w, "Invalid request method", http.StatusBadRequest)
  212. return
  213. }
  214. // Max file size limit (10 MB in this example)
  215. r.ParseMultipartForm(10 << 20)
  216. // Get the uploaded file
  217. file, handler, err := r.FormFile("file")
  218. if err != nil {
  219. http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
  220. return
  221. }
  222. defer file.Close()
  223. if filepath.Ext(handler.Filename) != ".zip" {
  224. http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
  225. return
  226. }
  227. // Create the target directory to unzip the files
  228. targetDir := "./conf"
  229. if utils.FileExists(targetDir) {
  230. //Backup the old config to old
  231. os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
  232. }
  233. err = os.MkdirAll(targetDir, os.ModePerm)
  234. if err != nil {
  235. http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
  236. return
  237. }
  238. // Open the zip file
  239. zipReader, err := zip.NewReader(file, handler.Size)
  240. if err != nil {
  241. http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
  242. return
  243. }
  244. restoreDatabase := false
  245. // Extract each file from the zip archive
  246. for _, zipFile := range zipReader.File {
  247. // Open the file in the zip archive
  248. rc, err := zipFile.Open()
  249. if err != nil {
  250. http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
  251. return
  252. }
  253. defer rc.Close()
  254. // Create the corresponding file on disk
  255. zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
  256. fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
  257. if zipFile.Name == "sys.db" {
  258. //Sysdb replacement. Close the database and restore
  259. sysdb.Close()
  260. restoreDatabase = true
  261. } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
  262. //Malformed zip file.
  263. http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
  264. return
  265. }
  266. //Check if parent dir exists
  267. if !utils.FileExists(filepath.Dir(zipFile.Name)) {
  268. os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
  269. }
  270. //Create the file
  271. newFile, err := os.Create(zipFile.Name)
  272. if err != nil {
  273. http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
  274. return
  275. }
  276. defer newFile.Close()
  277. // Copy the file contents from the zip to the new file
  278. _, err = io.Copy(newFile, rc)
  279. if err != nil {
  280. http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
  281. return
  282. }
  283. }
  284. // Send a success response
  285. w.WriteHeader(http.StatusOK)
  286. SystemWideLogger.Println("Configuration restored")
  287. fmt.Fprintln(w, "Configuration restored")
  288. if restoreDatabase {
  289. go func() {
  290. SystemWideLogger.Println("Database altered. Restarting in 3 seconds...")
  291. time.Sleep(3 * time.Second)
  292. os.Exit(0)
  293. }()
  294. }
  295. }