1
0

config.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. 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. }
  206. if err != nil {
  207. // Handle the error and send an HTTP response with the error message
  208. http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
  209. return
  210. }
  211. }
  212. func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
  213. // Check if the request is a POST with a file upload
  214. if r.Method != http.MethodPost {
  215. http.Error(w, "Invalid request method", http.StatusBadRequest)
  216. return
  217. }
  218. // Max file size limit (10 MB in this example)
  219. r.ParseMultipartForm(10 << 20)
  220. // Get the uploaded file
  221. file, handler, err := r.FormFile("file")
  222. if err != nil {
  223. http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
  224. return
  225. }
  226. defer file.Close()
  227. if filepath.Ext(handler.Filename) != ".zip" {
  228. http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
  229. return
  230. }
  231. // Create the target directory to unzip the files
  232. targetDir := "./conf"
  233. if utils.FileExists(targetDir) {
  234. //Backup the old config to old
  235. os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
  236. }
  237. err = os.MkdirAll(targetDir, os.ModePerm)
  238. if err != nil {
  239. http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
  240. return
  241. }
  242. // Open the zip file
  243. zipReader, err := zip.NewReader(file, handler.Size)
  244. if err != nil {
  245. http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
  246. return
  247. }
  248. restoreDatabase := false
  249. // Extract each file from the zip archive
  250. for _, zipFile := range zipReader.File {
  251. // Open the file in the zip archive
  252. rc, err := zipFile.Open()
  253. if err != nil {
  254. http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
  255. return
  256. }
  257. defer rc.Close()
  258. // Create the corresponding file on disk
  259. zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
  260. fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
  261. if zipFile.Name == "sys.db" {
  262. //Sysdb replacement. Close the database and restore
  263. sysdb.Close()
  264. restoreDatabase = true
  265. } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
  266. //Malformed zip file.
  267. http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
  268. return
  269. }
  270. //Check if parent dir exists
  271. if !utils.FileExists(filepath.Dir(zipFile.Name)) {
  272. os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
  273. }
  274. //Create the file
  275. newFile, err := os.Create(zipFile.Name)
  276. if err != nil {
  277. http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
  278. return
  279. }
  280. defer newFile.Close()
  281. // Copy the file contents from the zip to the new file
  282. _, err = io.Copy(newFile, rc)
  283. if err != nil {
  284. http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
  285. return
  286. }
  287. }
  288. // Send a success response
  289. w.WriteHeader(http.StatusOK)
  290. SystemWideLogger.Println("Configuration restored")
  291. fmt.Fprintln(w, "Configuration restored")
  292. if restoreDatabase {
  293. go func() {
  294. SystemWideLogger.Println("Database altered. Restarting in 3 seconds...")
  295. time.Sleep(3 * time.Second)
  296. os.Exit(0)
  297. }()
  298. }
  299. }