config.go 9.7 KB

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