config.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. os.WriteFile(filename, js, 0775)
  94. return nil
  95. }
  96. func RemoveReverseProxyConfig(endpoint string) error {
  97. filename := filepath.Join("./conf/proxy/", endpoint+".config")
  98. if endpoint == "/" {
  99. filename = "./conf/proxy/root.config"
  100. }
  101. filename = filterProxyConfigFilename(filename)
  102. if !utils.FileExists(filename) {
  103. return errors.New("target endpoint not exists")
  104. }
  105. return os.Remove(filename)
  106. }
  107. // Get the default root config that point to the internal static web server
  108. // this will be used if root config is not found (new deployment / missing root.config file)
  109. func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
  110. //Default settings
  111. rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&dynamicproxy.ProxyEndpoint{
  112. ProxyType: dynamicproxy.ProxyType_Root,
  113. RootOrMatchingDomain: "/",
  114. Domain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
  115. RequireTLS: false,
  116. BypassGlobalTLS: false,
  117. SkipCertValidations: false,
  118. VirtualDirectories: []*dynamicproxy.VirtualDirectoryEndpoint{},
  119. RequireBasicAuth: false,
  120. BasicAuthCredentials: []*dynamicproxy.BasicAuthCredentials{},
  121. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  122. DefaultSiteOption: dynamicproxy.DefaultSite_InternalStaticWebServer,
  123. DefaultSiteValue: "",
  124. })
  125. if err != nil {
  126. return nil, err
  127. }
  128. return rootProxyEndpoint, nil
  129. }
  130. /*
  131. Importer and Exporter of Zoraxy proxy config
  132. */
  133. func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
  134. includeSysDBRaw, err := utils.GetPara(r, "includeDB")
  135. includeSysDB := false
  136. if includeSysDBRaw == "true" {
  137. //Include the system database in backup snapshot
  138. //Temporary set it to read only
  139. sysdb.ReadOnly = true
  140. includeSysDB = true
  141. }
  142. // Specify the folder path to be zipped
  143. folderPath := "./conf/"
  144. // Set the Content-Type header to indicate it's a zip file
  145. w.Header().Set("Content-Type", "application/zip")
  146. // Set the Content-Disposition header to specify the file name
  147. w.Header().Set("Content-Disposition", "attachment; filename=\"config.zip\"")
  148. // Create a zip writer
  149. zipWriter := zip.NewWriter(w)
  150. defer zipWriter.Close()
  151. // Walk through the folder and add files to the zip
  152. err = filepath.Walk(folderPath, func(filePath string, fileInfo os.FileInfo, err error) error {
  153. if err != nil {
  154. return err
  155. }
  156. if folderPath == filePath {
  157. //Skip root folder
  158. return nil
  159. }
  160. // Create a new file in the zip
  161. if !utils.IsDir(filePath) {
  162. zipFile, err := zipWriter.Create(filePath)
  163. if err != nil {
  164. return err
  165. }
  166. // Open the file on disk
  167. file, err := os.Open(filePath)
  168. if err != nil {
  169. return err
  170. }
  171. defer file.Close()
  172. // Copy the file contents to the zip file
  173. _, err = io.Copy(zipFile, file)
  174. if err != nil {
  175. return err
  176. }
  177. }
  178. return nil
  179. })
  180. if includeSysDB {
  181. //Also zip in the sysdb
  182. zipFile, err := zipWriter.Create("sys.db")
  183. if err != nil {
  184. SystemWideLogger.PrintAndLog("Backup", "Unable to zip sysdb", err)
  185. return
  186. }
  187. // Open the file on disk
  188. file, err := os.Open("sys.db")
  189. if err != nil {
  190. SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
  191. return
  192. }
  193. defer file.Close()
  194. // Copy the file contents to the zip file
  195. _, err = io.Copy(zipFile, file)
  196. if err != nil {
  197. SystemWideLogger.Println(err)
  198. return
  199. }
  200. //Restore sysdb state
  201. sysdb.ReadOnly = false
  202. }
  203. if err != nil {
  204. // Handle the error and send an HTTP response with the error message
  205. http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
  206. return
  207. }
  208. }
  209. func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
  210. // Check if the request is a POST with a file upload
  211. if r.Method != http.MethodPost {
  212. http.Error(w, "Invalid request method", http.StatusBadRequest)
  213. return
  214. }
  215. // Max file size limit (10 MB in this example)
  216. r.ParseMultipartForm(10 << 20)
  217. // Get the uploaded file
  218. file, handler, err := r.FormFile("file")
  219. if err != nil {
  220. http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
  221. return
  222. }
  223. defer file.Close()
  224. if filepath.Ext(handler.Filename) != ".zip" {
  225. http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
  226. return
  227. }
  228. // Create the target directory to unzip the files
  229. targetDir := "./conf"
  230. if utils.FileExists(targetDir) {
  231. //Backup the old config to old
  232. os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
  233. }
  234. err = os.MkdirAll(targetDir, os.ModePerm)
  235. if err != nil {
  236. http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
  237. return
  238. }
  239. // Open the zip file
  240. zipReader, err := zip.NewReader(file, handler.Size)
  241. if err != nil {
  242. http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
  243. return
  244. }
  245. restoreDatabase := false
  246. // Extract each file from the zip archive
  247. for _, zipFile := range zipReader.File {
  248. // Open the file in the zip archive
  249. rc, err := zipFile.Open()
  250. if err != nil {
  251. http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
  252. return
  253. }
  254. defer rc.Close()
  255. // Create the corresponding file on disk
  256. zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
  257. fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
  258. if zipFile.Name == "sys.db" {
  259. //Sysdb replacement. Close the database and restore
  260. sysdb.Close()
  261. restoreDatabase = true
  262. } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
  263. //Malformed zip file.
  264. http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
  265. return
  266. }
  267. //Check if parent dir exists
  268. if !utils.FileExists(filepath.Dir(zipFile.Name)) {
  269. os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
  270. }
  271. //Create the file
  272. newFile, err := os.Create(zipFile.Name)
  273. if err != nil {
  274. http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
  275. return
  276. }
  277. defer newFile.Close()
  278. // Copy the file contents from the zip to the new file
  279. _, err = io.Copy(newFile, rc)
  280. if err != nil {
  281. http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
  282. return
  283. }
  284. }
  285. // Send a success response
  286. w.WriteHeader(http.StatusOK)
  287. SystemWideLogger.Println("Configuration restored")
  288. fmt.Fprintln(w, "Configuration restored")
  289. if restoreDatabase {
  290. go func() {
  291. SystemWideLogger.Println("Database altered. Restarting in 3 seconds...")
  292. time.Sleep(3 * time.Second)
  293. os.Exit(0)
  294. }()
  295. }
  296. }