1
0

config.go 8.8 KB

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