config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. //Make sure the tags are not nil
  50. if thisConfigEndpoint.Tags == nil {
  51. thisConfigEndpoint.Tags = []string{}
  52. }
  53. //Matching domain not set. Assume root
  54. if thisConfigEndpoint.RootOrMatchingDomain == "" {
  55. thisConfigEndpoint.RootOrMatchingDomain = "/"
  56. }
  57. if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyTypeRoot {
  58. //This is a root config file
  59. rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
  60. if err != nil {
  61. return err
  62. }
  63. dynamicProxyRouter.SetProxyRouteAsRoot(rootProxyEndpoint)
  64. } else if thisConfigEndpoint.ProxyType == dynamicproxy.ProxyTypeHost {
  65. //This is a host config file
  66. readyProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&thisConfigEndpoint)
  67. if err != nil {
  68. return err
  69. }
  70. dynamicProxyRouter.AddProxyRouteToRuntime(readyProxyEndpoint)
  71. } else {
  72. return errors.New("not supported proxy type")
  73. }
  74. SystemWideLogger.PrintAndLog("proxy-config", thisConfigEndpoint.RootOrMatchingDomain+" -> "+loadbalance.GetUpstreamsAsString(thisConfigEndpoint.ActiveOrigins)+" routing rule loaded", nil)
  75. return nil
  76. }
  77. func filterProxyConfigFilename(filename string) string {
  78. //Filter out wildcard characters
  79. filename = strings.ReplaceAll(filename, "*", "(ST)")
  80. filename = strings.ReplaceAll(filename, "?", "(QM)")
  81. filename = strings.ReplaceAll(filename, "[", "(OB)")
  82. filename = strings.ReplaceAll(filename, "]", "(CB)")
  83. filename = strings.ReplaceAll(filename, "#", "(HT)")
  84. return filepath.ToSlash(filename)
  85. }
  86. func SaveReverseProxyConfig(endpoint *dynamicproxy.ProxyEndpoint) error {
  87. //Get filename for saving
  88. filename := filepath.Join("./conf/proxy/", endpoint.RootOrMatchingDomain+".config")
  89. if endpoint.ProxyType == dynamicproxy.ProxyTypeRoot {
  90. filename = "./conf/proxy/root.config"
  91. }
  92. filename = filterProxyConfigFilename(filename)
  93. //Save config to file
  94. js, err := json.MarshalIndent(endpoint, "", " ")
  95. if err != nil {
  96. return err
  97. }
  98. return os.WriteFile(filename, js, 0775)
  99. }
  100. func RemoveReverseProxyConfig(endpoint string) error {
  101. filename := filepath.Join("./conf/proxy/", endpoint+".config")
  102. if endpoint == "/" {
  103. filename = "./conf/proxy/root.config"
  104. }
  105. filename = filterProxyConfigFilename(filename)
  106. if !utils.FileExists(filename) {
  107. return errors.New("target endpoint not exists")
  108. }
  109. return os.Remove(filename)
  110. }
  111. // Get the default root config that point to the internal static web server
  112. // this will be used if root config is not found (new deployment / missing root.config file)
  113. func GetDefaultRootConfig() (*dynamicproxy.ProxyEndpoint, error) {
  114. //Get the default proxy endpoint
  115. rootProxyEndpointConfig := dynamicproxy.GetDefaultProxyEndpoint()
  116. rootProxyEndpointConfig.ProxyType = dynamicproxy.ProxyTypeRoot
  117. rootProxyEndpointConfig.RootOrMatchingDomain = "/"
  118. rootProxyEndpointConfig.ActiveOrigins = []*loadbalance.Upstream{
  119. {
  120. OriginIpOrDomain: "127.0.0.1:" + staticWebServer.GetListeningPort(),
  121. RequireTLS: false,
  122. SkipCertValidations: false,
  123. Weight: 0,
  124. },
  125. }
  126. rootProxyEndpointConfig.DefaultSiteOption = dynamicproxy.DefaultSite_InternalStaticWebServer
  127. rootProxyEndpointConfig.DefaultSiteValue = ""
  128. //Default settings
  129. rootProxyEndpoint, err := dynamicProxyRouter.PrepareProxyRoute(&rootProxyEndpointConfig)
  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. includeSysDB = true
  145. }
  146. // Specify the folder path to be zipped
  147. if !utils.FileExists("./conf") {
  148. SystemWideLogger.PrintAndLog("Backup", "Configuration folder not found", nil)
  149. return
  150. }
  151. folderPath := "./conf"
  152. // Set the Content-Type header to indicate it's a zip file
  153. w.Header().Set("Content-Type", "application/zip")
  154. // Set the Content-Disposition header to specify the file name, add timestamp to the filename
  155. w.Header().Set("Content-Disposition", "attachment; filename=\"zoraxy-config-"+time.Now().Format("2006-01-02-15-04-05")+".zip\"")
  156. // Create a zip writer
  157. zipWriter := zip.NewWriter(w)
  158. defer zipWriter.Close()
  159. // Walk through the folder and add files to the zip
  160. err := filepath.Walk(folderPath, func(filePath string, fileInfo os.FileInfo, err error) error {
  161. if err != nil {
  162. return err
  163. }
  164. if folderPath == filePath {
  165. //Skip root folder
  166. return nil
  167. }
  168. // Create a new file in the zip
  169. if !utils.IsDir(filePath) {
  170. zipFile, err := zipWriter.Create(filePath)
  171. if err != nil {
  172. return err
  173. }
  174. // Open the file on disk
  175. file, err := os.Open(filePath)
  176. if err != nil {
  177. return err
  178. }
  179. defer file.Close()
  180. // Copy the file contents to the zip file
  181. _, err = io.Copy(zipFile, file)
  182. if err != nil {
  183. return err
  184. }
  185. }
  186. return nil
  187. })
  188. if includeSysDB {
  189. //Also zip in the sysdb
  190. zipFile, err := zipWriter.Create("sys.db")
  191. if err != nil {
  192. SystemWideLogger.PrintAndLog("Backup", "Unable to zip sysdb", err)
  193. return
  194. }
  195. // Open the file on disk
  196. file, err := os.Open("./sys.db")
  197. if err != nil {
  198. SystemWideLogger.PrintAndLog("Backup", "Unable to open sysdb", err)
  199. return
  200. }
  201. defer file.Close()
  202. // Copy the file contents to the zip file
  203. _, err = io.Copy(zipFile, file)
  204. if err != nil {
  205. SystemWideLogger.Println(err)
  206. return
  207. }
  208. }
  209. if err != nil {
  210. // Handle the error and send an HTTP response with the error message
  211. http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
  212. return
  213. }
  214. }
  215. func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
  216. // Check if the request is a POST with a file upload
  217. if r.Method != http.MethodPost {
  218. http.Error(w, "Invalid request method", http.StatusBadRequest)
  219. return
  220. }
  221. // Max file size limit (10 MB in this example)
  222. r.ParseMultipartForm(10 << 20)
  223. // Get the uploaded file
  224. file, handler, err := r.FormFile("file")
  225. if err != nil {
  226. http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
  227. return
  228. }
  229. defer file.Close()
  230. if filepath.Ext(handler.Filename) != ".zip" {
  231. http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
  232. return
  233. }
  234. // Create the target directory to unzip the files
  235. targetDir := "./conf"
  236. if utils.FileExists(targetDir) {
  237. //Backup the old config to old
  238. //backupPath := filepath.Dir(*path_conf) + filepath.Base(*path_conf) + ".old_" + strconv.Itoa(int(time.Now().Unix()))
  239. //os.Rename(*path_conf, backupPath)
  240. os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
  241. }
  242. err = os.MkdirAll(targetDir, os.ModePerm)
  243. if err != nil {
  244. http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
  245. return
  246. }
  247. // Open the zip file
  248. zipReader, err := zip.NewReader(file, handler.Size)
  249. if err != nil {
  250. http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
  251. return
  252. }
  253. restoreDatabase := false
  254. // Extract each file from the zip archive
  255. for _, zipFile := range zipReader.File {
  256. // Open the file in the zip archive
  257. rc, err := zipFile.Open()
  258. if err != nil {
  259. http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
  260. return
  261. }
  262. defer rc.Close()
  263. // Create the corresponding file on disk
  264. zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
  265. fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
  266. if zipFile.Name == "sys.db" {
  267. //Sysdb replacement. Close the database and restore
  268. sysdb.Close()
  269. restoreDatabase = true
  270. } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
  271. //Malformed zip file.
  272. http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
  273. return
  274. }
  275. //Check if parent dir exists
  276. if !utils.FileExists(filepath.Dir(zipFile.Name)) {
  277. os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
  278. }
  279. //Create the file
  280. newFile, err := os.Create(zipFile.Name)
  281. if err != nil {
  282. http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
  283. return
  284. }
  285. defer newFile.Close()
  286. // Copy the file contents from the zip to the new file
  287. _, err = io.Copy(newFile, rc)
  288. if err != nil {
  289. http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
  290. return
  291. }
  292. }
  293. // Send a success response
  294. w.WriteHeader(http.StatusOK)
  295. SystemWideLogger.Println("Configuration restored")
  296. fmt.Fprintln(w, "Configuration restored")
  297. if restoreDatabase {
  298. go func() {
  299. SystemWideLogger.Println("Database altered. Restarting in 3 seconds...")
  300. time.Sleep(3 * time.Second)
  301. os.Exit(0)
  302. }()
  303. }
  304. }