1
0

config.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package main
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  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/utils"
  16. )
  17. /*
  18. Reverse Proxy Configs
  19. The following section handle
  20. the reverse proxy configs
  21. */
  22. type Record struct {
  23. ProxyType string
  24. Rootname string
  25. ProxyTarget string
  26. UseTLS bool
  27. SkipTlsValidation bool
  28. RequireBasicAuth bool
  29. BasicAuthCredentials []*dynamicproxy.BasicAuthCredentials
  30. BasicAuthExceptionRules []*dynamicproxy.BasicAuthExceptionRule
  31. }
  32. // Save a reverse proxy config record to file
  33. func SaveReverseProxyConfigToFile(proxyConfigRecord *Record) error {
  34. //TODO: Make this accept new def types
  35. os.MkdirAll("./conf/proxy/", 0775)
  36. filename := getFilenameFromRootName(proxyConfigRecord.Rootname)
  37. //Generate record
  38. thisRecord := proxyConfigRecord
  39. //Write to file
  40. js, _ := json.MarshalIndent(thisRecord, "", " ")
  41. return os.WriteFile(filepath.Join("./conf/proxy/", filename), js, 0775)
  42. }
  43. // Save a running reverse proxy endpoint to file (with automatic endpoint to record conversion)
  44. func SaveReverseProxyEndpointToFile(proxyEndpoint *dynamicproxy.ProxyEndpoint) error {
  45. recordToSave, err := ConvertProxyEndpointToRecord(proxyEndpoint)
  46. if err != nil {
  47. return err
  48. }
  49. return SaveReverseProxyConfigToFile(recordToSave)
  50. }
  51. func RemoveReverseProxyConfigFile(rootname string) error {
  52. filename := getFilenameFromRootName(rootname)
  53. removePendingFile := strings.ReplaceAll(filepath.Join("./conf/proxy/", filename), "\\", "/")
  54. log.Println("Config Removed: ", removePendingFile)
  55. if utils.FileExists(removePendingFile) {
  56. err := os.Remove(removePendingFile)
  57. if err != nil {
  58. log.Println(err.Error())
  59. return err
  60. }
  61. }
  62. //File already gone
  63. return nil
  64. }
  65. // Return ptype, rootname and proxyTarget, error if any
  66. func LoadReverseProxyConfig(filename string) (*Record, error) {
  67. thisRecord := Record{
  68. ProxyType: "",
  69. Rootname: "",
  70. ProxyTarget: "",
  71. UseTLS: false,
  72. SkipTlsValidation: false,
  73. RequireBasicAuth: false,
  74. BasicAuthCredentials: []*dynamicproxy.BasicAuthCredentials{},
  75. BasicAuthExceptionRules: []*dynamicproxy.BasicAuthExceptionRule{},
  76. }
  77. configContent, err := os.ReadFile(filename)
  78. if err != nil {
  79. return &thisRecord, err
  80. }
  81. //Unmarshal the content into config
  82. err = json.Unmarshal(configContent, &thisRecord)
  83. if err != nil {
  84. return &thisRecord, err
  85. }
  86. //Return it
  87. return &thisRecord, nil
  88. }
  89. // Convert a running proxy endpoint object into a save-able record struct
  90. func ConvertProxyEndpointToRecord(targetProxyEndpoint *dynamicproxy.ProxyEndpoint) (*Record, error) {
  91. thisProxyConfigRecord := Record{
  92. ProxyType: targetProxyEndpoint.GetProxyTypeString(),
  93. Rootname: targetProxyEndpoint.RootOrMatchingDomain,
  94. ProxyTarget: targetProxyEndpoint.Domain,
  95. UseTLS: targetProxyEndpoint.RequireTLS,
  96. SkipTlsValidation: targetProxyEndpoint.SkipCertValidations,
  97. RequireBasicAuth: targetProxyEndpoint.RequireBasicAuth,
  98. BasicAuthCredentials: targetProxyEndpoint.BasicAuthCredentials,
  99. BasicAuthExceptionRules: targetProxyEndpoint.BasicAuthExceptionRules,
  100. }
  101. return &thisProxyConfigRecord, nil
  102. }
  103. func getFilenameFromRootName(rootname string) string {
  104. //Generate a filename for this rootname
  105. filename := strings.ReplaceAll(rootname, ".", "_")
  106. filename = strings.ReplaceAll(filename, "/", "-")
  107. filename = filename + ".config"
  108. return filename
  109. }
  110. /*
  111. Importer and Exporter of Zoraxy proxy config
  112. */
  113. func ExportConfigAsZip(w http.ResponseWriter, r *http.Request) {
  114. includeSysDBRaw, err := utils.GetPara(r, "includeDB")
  115. includeSysDB := false
  116. if includeSysDBRaw == "true" {
  117. //Include the system database in backup snapshot
  118. //Temporary set it to read only
  119. sysdb.ReadOnly = true
  120. includeSysDB = true
  121. }
  122. // Specify the folder path to be zipped
  123. folderPath := "./conf/"
  124. // Set the Content-Type header to indicate it's a zip file
  125. w.Header().Set("Content-Type", "application/zip")
  126. // Set the Content-Disposition header to specify the file name
  127. w.Header().Set("Content-Disposition", "attachment; filename=\"config.zip\"")
  128. // Create a zip writer
  129. zipWriter := zip.NewWriter(w)
  130. defer zipWriter.Close()
  131. // Walk through the folder and add files to the zip
  132. err = filepath.Walk(folderPath, func(filePath string, fileInfo os.FileInfo, err error) error {
  133. if err != nil {
  134. return err
  135. }
  136. if folderPath == filePath {
  137. //Skip root folder
  138. return nil
  139. }
  140. // Create a new file in the zip
  141. if !utils.IsDir(filePath) {
  142. zipFile, err := zipWriter.Create(filePath)
  143. if err != nil {
  144. return err
  145. }
  146. // Open the file on disk
  147. file, err := os.Open(filePath)
  148. if err != nil {
  149. return err
  150. }
  151. defer file.Close()
  152. // Copy the file contents to the zip file
  153. _, err = io.Copy(zipFile, file)
  154. if err != nil {
  155. return err
  156. }
  157. }
  158. return nil
  159. })
  160. if includeSysDB {
  161. //Also zip in the sysdb
  162. zipFile, err := zipWriter.Create("sys.db")
  163. if err != nil {
  164. log.Println("[Backup] Unable to zip sysdb: " + err.Error())
  165. return
  166. }
  167. // Open the file on disk
  168. file, err := os.Open("sys.db")
  169. if err != nil {
  170. log.Println("[Backup] Unable to open sysdb: " + err.Error())
  171. return
  172. }
  173. defer file.Close()
  174. // Copy the file contents to the zip file
  175. _, err = io.Copy(zipFile, file)
  176. if err != nil {
  177. log.Println(err)
  178. return
  179. }
  180. //Restore sysdb state
  181. sysdb.ReadOnly = false
  182. }
  183. if err != nil {
  184. // Handle the error and send an HTTP response with the error message
  185. http.Error(w, fmt.Sprintf("Failed to zip folder: %v", err), http.StatusInternalServerError)
  186. return
  187. }
  188. }
  189. func ImportConfigFromZip(w http.ResponseWriter, r *http.Request) {
  190. // Check if the request is a POST with a file upload
  191. if r.Method != http.MethodPost {
  192. http.Error(w, "Invalid request method", http.StatusBadRequest)
  193. return
  194. }
  195. // Max file size limit (10 MB in this example)
  196. r.ParseMultipartForm(10 << 20)
  197. // Get the uploaded file
  198. file, handler, err := r.FormFile("file")
  199. if err != nil {
  200. http.Error(w, "Failed to retrieve uploaded file", http.StatusInternalServerError)
  201. return
  202. }
  203. defer file.Close()
  204. if filepath.Ext(handler.Filename) != ".zip" {
  205. http.Error(w, "Upload file is not a zip file", http.StatusInternalServerError)
  206. return
  207. }
  208. // Create the target directory to unzip the files
  209. targetDir := "./conf"
  210. if utils.FileExists(targetDir) {
  211. //Backup the old config to old
  212. os.Rename("./conf", "./conf.old_"+strconv.Itoa(int(time.Now().Unix())))
  213. }
  214. err = os.MkdirAll(targetDir, os.ModePerm)
  215. if err != nil {
  216. http.Error(w, fmt.Sprintf("Failed to create target directory: %v", err), http.StatusInternalServerError)
  217. return
  218. }
  219. // Open the zip file
  220. zipReader, err := zip.NewReader(file, handler.Size)
  221. if err != nil {
  222. http.Error(w, fmt.Sprintf("Failed to open zip file: %v", err), http.StatusInternalServerError)
  223. return
  224. }
  225. restoreDatabase := false
  226. // Extract each file from the zip archive
  227. for _, zipFile := range zipReader.File {
  228. // Open the file in the zip archive
  229. rc, err := zipFile.Open()
  230. if err != nil {
  231. http.Error(w, fmt.Sprintf("Failed to open file in zip: %v", err), http.StatusInternalServerError)
  232. return
  233. }
  234. defer rc.Close()
  235. // Create the corresponding file on disk
  236. zipFile.Name = strings.ReplaceAll(zipFile.Name, "../", "")
  237. fmt.Println("Restoring: " + strings.ReplaceAll(zipFile.Name, "\\", "/"))
  238. if zipFile.Name == "sys.db" {
  239. //Sysdb replacement. Close the database and restore
  240. sysdb.Close()
  241. restoreDatabase = true
  242. } else if !strings.HasPrefix(strings.ReplaceAll(zipFile.Name, "\\", "/"), "conf/") {
  243. //Malformed zip file.
  244. http.Error(w, fmt.Sprintf("Invalid zip file structure or version too old"), http.StatusInternalServerError)
  245. return
  246. }
  247. //Check if parent dir exists
  248. if !utils.FileExists(filepath.Dir(zipFile.Name)) {
  249. os.MkdirAll(filepath.Dir(zipFile.Name), 0775)
  250. }
  251. //Create the file
  252. newFile, err := os.Create(zipFile.Name)
  253. if err != nil {
  254. http.Error(w, fmt.Sprintf("Failed to create file: %v", err), http.StatusInternalServerError)
  255. return
  256. }
  257. defer newFile.Close()
  258. // Copy the file contents from the zip to the new file
  259. _, err = io.Copy(newFile, rc)
  260. if err != nil {
  261. http.Error(w, fmt.Sprintf("Failed to extract file from zip: %v", err), http.StatusInternalServerError)
  262. return
  263. }
  264. }
  265. // Send a success response
  266. w.WriteHeader(http.StatusOK)
  267. log.Println("Configuration restored")
  268. fmt.Fprintln(w, "Configuration restored")
  269. if restoreDatabase {
  270. go func() {
  271. log.Println("Database altered. Restarting in 3 seconds...")
  272. time.Sleep(3 * time.Second)
  273. os.Exit(0)
  274. }()
  275. }
  276. }