1
0

config.go 9.6 KB

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