1
0

config.go 7.1 KB

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