1
0

config.go 9.7 KB

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