1
0

filemanager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. package filemanager
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "imuslab.com/zoraxy/mod/utils"
  12. )
  13. /*
  14. File Manager
  15. This is a simple package that handles file management
  16. under the web server directory
  17. */
  18. type FileManager struct {
  19. Directory string
  20. }
  21. // Create a new file manager with directory as root
  22. func NewFileManager(directory string) *FileManager {
  23. return &FileManager{
  24. Directory: directory,
  25. }
  26. }
  27. // Handle listing of a given directory
  28. func (fm *FileManager) HandleList(w http.ResponseWriter, r *http.Request) {
  29. directory, err := utils.GetPara(r, "dir")
  30. if err != nil {
  31. utils.SendErrorResponse(w, "invalid directory given")
  32. return
  33. }
  34. // Construct the absolute path to the target directory
  35. targetDir := filepath.Join(fm.Directory, directory)
  36. // Clean path to prevent path escape #274
  37. isValidRequest := validatePathEscape(targetDir, fm.Directory)
  38. if !isValidRequest {
  39. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  40. return
  41. }
  42. // Open the target directory
  43. dirEntries, err := os.ReadDir(targetDir)
  44. if err != nil {
  45. utils.SendErrorResponse(w, "unable to open directory")
  46. return
  47. }
  48. // Create a slice to hold the file information
  49. var files []map[string]interface{} = []map[string]interface{}{}
  50. // Iterate through the directory entries
  51. for _, dirEntry := range dirEntries {
  52. fileInfo := make(map[string]interface{})
  53. fileInfo["filename"] = dirEntry.Name()
  54. fileInfo["filepath"] = filepath.Join(directory, dirEntry.Name())
  55. fileInfo["isDir"] = dirEntry.IsDir()
  56. // Get file size and last modified time
  57. finfo, err := dirEntry.Info()
  58. if err != nil {
  59. //unable to load its info. Skip this file
  60. continue
  61. }
  62. fileInfo["lastModified"] = finfo.ModTime().Unix()
  63. if !dirEntry.IsDir() {
  64. // If it's a file, get its size
  65. fileInfo["size"] = finfo.Size()
  66. } else {
  67. // If it's a directory, set size to 0
  68. fileInfo["size"] = 0
  69. }
  70. // Append file info to the list
  71. files = append(files, fileInfo)
  72. }
  73. // Serialize the file info slice to JSON
  74. jsonData, err := json.Marshal(files)
  75. if err != nil {
  76. utils.SendErrorResponse(w, "unable to marshal JSON")
  77. return
  78. }
  79. // Set response headers and send the JSON response
  80. w.Header().Set("Content-Type", "application/json")
  81. w.WriteHeader(http.StatusOK)
  82. w.Write(jsonData)
  83. }
  84. // Handle upload of a file (multi-part), 25MB max
  85. func (fm *FileManager) HandleUpload(w http.ResponseWriter, r *http.Request) {
  86. dir, err := utils.PostPara(r, "dir")
  87. if err != nil {
  88. log.Println("no dir given")
  89. utils.SendErrorResponse(w, "invalid dir given")
  90. return
  91. }
  92. // Parse the multi-part form data
  93. err = r.ParseMultipartForm(25 << 20)
  94. if err != nil {
  95. utils.SendErrorResponse(w, "unable to parse form data")
  96. return
  97. }
  98. // Get the uploaded file
  99. file, fheader, err := r.FormFile("file")
  100. if err != nil {
  101. log.Println(err.Error())
  102. utils.SendErrorResponse(w, "unable to get uploaded file")
  103. return
  104. }
  105. defer file.Close()
  106. // Specify the directory where you want to save the uploaded file
  107. uploadDir := filepath.Join(fm.Directory, dir)
  108. // Clean path to prevent path escape #274
  109. isValidRequest := validatePathEscape(uploadDir, fm.Directory)
  110. if !isValidRequest {
  111. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  112. return
  113. }
  114. if !utils.FileExists(uploadDir) {
  115. utils.SendErrorResponse(w, "upload target directory not exists")
  116. return
  117. }
  118. filename := sanitizeFilename(fheader.Filename)
  119. if !isValidFilename(filename) {
  120. utils.SendErrorResponse(w, "filename contain invalid or reserved characters")
  121. return
  122. }
  123. // Create the file on the server
  124. filePath := filepath.Join(uploadDir, filepath.Base(filename))
  125. out, err := os.Create(filePath)
  126. if err != nil {
  127. utils.SendErrorResponse(w, "unable to create file on the server")
  128. return
  129. }
  130. defer out.Close()
  131. // Copy the uploaded file to the server
  132. _, err = io.Copy(out, file)
  133. if err != nil {
  134. utils.SendErrorResponse(w, "unable to copy file to server")
  135. return
  136. }
  137. // Respond with a success message or appropriate response
  138. utils.SendOK(w)
  139. }
  140. // Handle download of a selected file, serve with content dispose header
  141. func (fm *FileManager) HandleDownload(w http.ResponseWriter, r *http.Request) {
  142. filename, err := utils.GetPara(r, "file")
  143. if err != nil {
  144. utils.SendErrorResponse(w, "invalid filepath given")
  145. return
  146. }
  147. filePath := filepath.Join(fm.Directory, filename)
  148. // Clean path to prevent path escape #274
  149. isValidRequest := validatePathEscape(filePath, fm.Directory)
  150. if !isValidRequest {
  151. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  152. return
  153. }
  154. previewMode, _ := utils.GetPara(r, "preview")
  155. if previewMode == "true" {
  156. // Serve the file using http.ServeFile
  157. http.ServeFile(w, r, filePath)
  158. } else {
  159. // Trigger a download with content disposition headers
  160. w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(filename))
  161. http.ServeFile(w, r, filePath)
  162. }
  163. }
  164. // HandleNewFolder creates a new folder in the specified directory
  165. func (fm *FileManager) HandleNewFolder(w http.ResponseWriter, r *http.Request) {
  166. // Parse the directory name from the request
  167. dirName, err := utils.PostPara(r, "path")
  168. if err != nil {
  169. utils.SendErrorResponse(w, "invalid directory name")
  170. return
  171. }
  172. //Prevent path escape
  173. dirName = strings.ReplaceAll(dirName, "\\", "/")
  174. dirName = strings.ReplaceAll(dirName, "../", "")
  175. // Specify the directory where you want to create the new folder
  176. newFolderPath := filepath.Join(fm.Directory, dirName)
  177. isValidRequest := validatePathEscape(newFolderPath, fm.Directory)
  178. if !isValidRequest {
  179. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  180. return
  181. }
  182. // Check if the folder already exists
  183. if _, err := os.Stat(newFolderPath); os.IsNotExist(err) {
  184. // Create the new folder
  185. err := os.Mkdir(newFolderPath, os.ModePerm)
  186. if err != nil {
  187. utils.SendErrorResponse(w, "unable to create the new folder")
  188. return
  189. }
  190. // Respond with a success message or appropriate response
  191. utils.SendOK(w)
  192. } else {
  193. // If the folder already exists, respond with an error
  194. utils.SendErrorResponse(w, "folder already exists")
  195. }
  196. }
  197. // HandleFileCopy copies a file or directory from the source path to the destination path
  198. func (fm *FileManager) HandleFileCopy(w http.ResponseWriter, r *http.Request) {
  199. // Parse the source and destination paths from the request
  200. srcPath, err := utils.PostPara(r, "srcpath")
  201. if err != nil {
  202. utils.SendErrorResponse(w, "invalid source path")
  203. return
  204. }
  205. destPath, err := utils.PostPara(r, "destpath")
  206. if err != nil {
  207. utils.SendErrorResponse(w, "invalid destination path")
  208. return
  209. }
  210. // Validate and sanitize the source and destination paths
  211. srcPath = filepath.Clean(srcPath)
  212. destPath = filepath.Clean(destPath)
  213. // Construct the absolute paths
  214. absSrcPath := filepath.Join(fm.Directory, srcPath)
  215. absDestPath := filepath.Join(fm.Directory, destPath)
  216. //Make sure the copy source and dest are within web directory folder
  217. isValidRequest := validatePathEscape(absSrcPath, fm.Directory)
  218. if !isValidRequest {
  219. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  220. return
  221. }
  222. isValidRequest = validatePathEscape(absDestPath, fm.Directory)
  223. if !isValidRequest {
  224. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  225. return
  226. }
  227. // Check if the source path exists
  228. if _, err := os.Stat(absSrcPath); os.IsNotExist(err) {
  229. utils.SendErrorResponse(w, "source path does not exist")
  230. return
  231. }
  232. // Check if the destination path exists
  233. if _, err := os.Stat(absDestPath); os.IsNotExist(err) {
  234. utils.SendErrorResponse(w, "destination path does not exist")
  235. return
  236. }
  237. //Join the name to create final paste filename
  238. absDestPath = filepath.Join(absDestPath, filepath.Base(absSrcPath))
  239. //Reject opr if already exists
  240. if utils.FileExists(absDestPath) {
  241. utils.SendErrorResponse(w, "target already exists")
  242. return
  243. }
  244. // Perform the copy operation based on whether the source is a file or directory
  245. if isDir(absSrcPath) {
  246. // Recursive copy for directories
  247. err := copyDirectory(absSrcPath, absDestPath)
  248. if err != nil {
  249. utils.SendErrorResponse(w, fmt.Sprintf("error copying directory: %v", err))
  250. return
  251. }
  252. } else {
  253. // Copy a single file
  254. err := copyFile(absSrcPath, absDestPath)
  255. if err != nil {
  256. utils.SendErrorResponse(w, fmt.Sprintf("error copying file: %v", err))
  257. return
  258. }
  259. }
  260. utils.SendOK(w)
  261. }
  262. func (fm *FileManager) HandleFileMove(w http.ResponseWriter, r *http.Request) {
  263. // Parse the source and destination paths from the request
  264. srcPath, err := utils.PostPara(r, "srcpath")
  265. if err != nil {
  266. utils.SendErrorResponse(w, "invalid source path")
  267. return
  268. }
  269. destPath, err := utils.PostPara(r, "destpath")
  270. if err != nil {
  271. utils.SendErrorResponse(w, "invalid destination path")
  272. return
  273. }
  274. // Validate and sanitize the source and destination paths
  275. srcPath = filepath.Clean(srcPath)
  276. destPath = filepath.Clean(destPath)
  277. // Construct the absolute paths
  278. absSrcPath := filepath.Join(fm.Directory, srcPath)
  279. absDestPath := filepath.Join(fm.Directory, destPath)
  280. //Make sure move source and target are within web server directory
  281. isValidRequest := validatePathEscape(absSrcPath, fm.Directory)
  282. if !isValidRequest {
  283. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  284. return
  285. }
  286. isValidRequest = validatePathEscape(absDestPath, fm.Directory)
  287. if !isValidRequest {
  288. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  289. return
  290. }
  291. // Check if the source path exists
  292. if _, err := os.Stat(absSrcPath); os.IsNotExist(err) {
  293. utils.SendErrorResponse(w, "source path does not exist")
  294. return
  295. }
  296. // Check if the destination path exists
  297. if _, err := os.Stat(absDestPath); !os.IsNotExist(err) {
  298. utils.SendErrorResponse(w, "destination path already exists")
  299. return
  300. }
  301. // Rename the source to the destination
  302. err = os.Rename(absSrcPath, absDestPath)
  303. if err != nil {
  304. utils.SendErrorResponse(w, fmt.Sprintf("error moving file/directory: %v", err))
  305. return
  306. }
  307. utils.SendOK(w)
  308. }
  309. func (fm *FileManager) HandleFileProperties(w http.ResponseWriter, r *http.Request) {
  310. // Parse the target file or directory path from the request
  311. filePath, err := utils.GetPara(r, "file")
  312. if err != nil {
  313. utils.SendErrorResponse(w, "invalid file path")
  314. return
  315. }
  316. // Construct the absolute path to the target file or directory
  317. absPath := filepath.Join(fm.Directory, filePath)
  318. isValidRequest := validatePathEscape(absPath, fm.Directory)
  319. if !isValidRequest {
  320. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  321. return
  322. }
  323. // Check if the target path exists
  324. _, err = os.Stat(absPath)
  325. if err != nil {
  326. utils.SendErrorResponse(w, "file or directory does not exist")
  327. return
  328. }
  329. // Initialize a map to hold file properties
  330. fileProps := make(map[string]interface{})
  331. fileProps["filename"] = filepath.Base(absPath)
  332. fileProps["filepath"] = filePath
  333. fileProps["isDir"] = isDir(absPath)
  334. // Get file size and last modified time
  335. finfo, err := os.Stat(absPath)
  336. if err != nil {
  337. utils.SendErrorResponse(w, "unable to retrieve file properties")
  338. return
  339. }
  340. fileProps["lastModified"] = finfo.ModTime().Unix()
  341. if !isDir(absPath) {
  342. // If it's a file, get its size
  343. fileProps["size"] = finfo.Size()
  344. } else {
  345. // If it's a directory, calculate its total size containing all child files and folders
  346. totalSize, err := calculateDirectorySize(absPath)
  347. if err != nil {
  348. utils.SendErrorResponse(w, "unable to calculate directory size")
  349. return
  350. }
  351. fileProps["size"] = totalSize
  352. }
  353. // Count the number of sub-files and sub-folders
  354. numSubFiles, numSubFolders, err := countSubFilesAndFolders(absPath)
  355. if err != nil {
  356. utils.SendErrorResponse(w, "unable to count sub-files and sub-folders")
  357. return
  358. }
  359. fileProps["fileCounts"] = numSubFiles
  360. fileProps["folderCounts"] = numSubFolders
  361. // Serialize the file properties to JSON
  362. jsonData, err := json.Marshal(fileProps)
  363. if err != nil {
  364. utils.SendErrorResponse(w, "unable to marshal JSON")
  365. return
  366. }
  367. // Set response headers and send the JSON response
  368. w.Header().Set("Content-Type", "application/json")
  369. w.WriteHeader(http.StatusOK)
  370. w.Write(jsonData)
  371. }
  372. // HandleFileDelete deletes a file or directory
  373. func (fm *FileManager) HandleFileDelete(w http.ResponseWriter, r *http.Request) {
  374. // Parse the target file or directory path from the request
  375. filePath, err := utils.PostPara(r, "target")
  376. if err != nil {
  377. utils.SendErrorResponse(w, "invalid file path")
  378. return
  379. }
  380. // Construct the absolute path to the target file or directory
  381. absPath := filepath.Join(fm.Directory, filePath)
  382. isValidRequest := validatePathEscape(absPath, fm.Directory)
  383. if !isValidRequest {
  384. http.Error(w, "403 - Forbidden", http.StatusForbidden)
  385. return
  386. }
  387. // Check if the target path exists
  388. _, err = os.Stat(absPath)
  389. if err != nil {
  390. utils.SendErrorResponse(w, "file or directory does not exist")
  391. return
  392. }
  393. // Delete the file or directory
  394. err = os.RemoveAll(absPath)
  395. if err != nil {
  396. utils.SendErrorResponse(w, "error deleting file or directory")
  397. return
  398. }
  399. // Respond with a success message or appropriate response
  400. utils.SendOK(w)
  401. }
  402. // Return true if the path is within the root path
  403. func validatePathEscape(reqestPath string, rootPath string) bool {
  404. reqestPath = filepath.ToSlash(filepath.Clean(reqestPath))
  405. rootPath = filepath.ToSlash(filepath.Clean(rootPath))
  406. requestPathAbs, err := filepath.Abs(reqestPath)
  407. if err != nil {
  408. return false
  409. }
  410. rootPathAbs, err := filepath.Abs(rootPath)
  411. if err != nil {
  412. return false
  413. }
  414. if strings.HasPrefix(requestPathAbs, rootPathAbs) {
  415. return true
  416. }
  417. return false
  418. }