config.go 7.2 KB

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