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