static.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. package filesystem
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "path/filepath"
  15. "runtime"
  16. "strconv"
  17. "strings"
  18. "net/url"
  19. mimetype "github.com/gabriel-vasile/mimetype"
  20. "imuslab.com/arozos/mod/apt"
  21. "imuslab.com/arozos/mod/filesystem/arozfs"
  22. "imuslab.com/arozos/mod/filesystem/shortcut"
  23. "imuslab.com/arozos/mod/info/logger"
  24. )
  25. // Control Signals for background file operation tasks
  26. const (
  27. FsOpr_Continue = 0 //Continue file operations
  28. FsOpr_Pause = 1 //Pause and wait until opr back to continue
  29. FsOpr_Cancel = 2 //Cancel and finish the file operation
  30. FsOpr_Error = 3 //Error occured in recent sections
  31. FsOpr_Completed = 4 //Operation completed. Delete pending
  32. )
  33. // Structure definations
  34. type FileData struct {
  35. Filename string
  36. Filepath string
  37. Realpath string
  38. IsDir bool
  39. Filesize int64
  40. Displaysize string
  41. ModTime int64
  42. IsShared bool
  43. Shortcut *arozfs.ShortcutData //This will return nil or undefined if it is not a shortcut file
  44. }
  45. type TrashedFile struct {
  46. Filename string
  47. Filepath string
  48. FileExt string
  49. IsDir bool
  50. Filesize int64
  51. RemoveTimestamp int64
  52. RemoveDate string
  53. OriginalPath string
  54. OriginalFilename string
  55. }
  56. type FileProperties struct {
  57. VirtualPath string
  58. StoragePath string
  59. Basename string
  60. VirtualDirname string
  61. StorageDirname string
  62. Ext string
  63. MimeType string
  64. Filesize int64
  65. Permission string
  66. LastModTime string
  67. LastModUnix int64
  68. IsDirectory bool
  69. }
  70. /*
  71. HierarchySpecificConfig Template
  72. */
  73. type EmptyHierarchySpecificConfig struct {
  74. HierarchyType string
  75. }
  76. func (e EmptyHierarchySpecificConfig) ResolveVrootPath(string, string) (string, error) {
  77. return "", nil
  78. }
  79. func (e EmptyHierarchySpecificConfig) ResolveRealPath(string, string) (string, error) {
  80. return "", nil
  81. }
  82. var DefaultEmptyHierarchySpecificConfig = EmptyHierarchySpecificConfig{
  83. HierarchyType: "placeholder",
  84. }
  85. // Check if the two file system are identical.
  86. func MatchingFileSystem(fsa *FileSystemHandler, fsb *FileSystemHandler) bool {
  87. return fsa.Filesystem == fsb.Filesystem
  88. }
  89. /*
  90. Get the ID part of a virtual path, return ID, subpath and error
  91. The ID is split off before the subpath is cleaned. Cleaning the whole path
  92. read "user:.." as one ordinary element, so "user:../bob/notes.txt" kept its
  93. ".." and every caller joined it onto the requesting user's home folder. A
  94. subpath that climbs above its root is now refused with
  95. arozfs.ErrPathEscapesRoot.
  96. */
  97. func GetIDFromVirtualPath(vpath string) (string, string, error) {
  98. if !strings.Contains(vpath, ":") {
  99. return "", "", errors.New("Path missing Virtual Device ID. Given: " + vpath)
  100. }
  101. vdID, subpath, _ := strings.Cut(arozfs.ToSlash(vpath), ":")
  102. //Older code passed paths through filepath.Clean, which prefixes "./"
  103. vdID = strings.TrimPrefix(vdID, "./")
  104. if arozfs.SubpathEscapesRoot(subpath) {
  105. return "", "", arozfs.ErrPathEscapesRoot
  106. }
  107. if subpath != "" {
  108. //A bare root ("user:/") still gives an empty subpath, as before
  109. subpath = strings.TrimSuffix(path.Clean(subpath), "/")
  110. }
  111. return vdID, subpath, nil
  112. }
  113. func GetFileDataFromPath(fsh *FileSystemHandler, vpath string, realpath string, sizeRounding int) FileData {
  114. fileSize := fsh.FileSystemAbstraction.GetFileSize(realpath)
  115. displaySize := GetFileDisplaySize(fileSize, sizeRounding)
  116. modtime, _ := fsh.FileSystemAbstraction.GetModTime(realpath)
  117. var shortcutInfo *arozfs.ShortcutData = nil
  118. if filepath.Ext(realpath) == ".shortcut" {
  119. shortcutContent, err := fsh.FileSystemAbstraction.ReadFile(realpath)
  120. if err != nil {
  121. shortcutInfo = nil
  122. } else {
  123. shortcutInfo, err = shortcut.ReadShortcut(shortcutContent)
  124. if err != nil {
  125. shortcutInfo = nil
  126. }
  127. }
  128. }
  129. return FileData{
  130. Filename: filepath.Base(realpath),
  131. Filepath: vpath,
  132. Realpath: filepath.ToSlash(realpath),
  133. IsDir: fsh.FileSystemAbstraction.IsDir(realpath),
  134. Filesize: fileSize,
  135. Displaysize: displaySize,
  136. ModTime: modtime,
  137. IsShared: false,
  138. Shortcut: shortcutInfo,
  139. }
  140. }
  141. func CheckMounted(mountpoint string) bool {
  142. if runtime.GOOS == "windows" {
  143. //Windows
  144. //Check if the given folder exists
  145. info, err := os.Stat(mountpoint)
  146. if os.IsNotExist(err) {
  147. return false
  148. }
  149. return info.IsDir()
  150. } else {
  151. //Linux
  152. cmd := exec.Command("mountpoint", mountpoint)
  153. out, err := cmd.CombinedOutput()
  154. if err != nil {
  155. return false
  156. }
  157. outstring := strings.TrimSpace(string(out))
  158. if strings.Contains(outstring, " is a mountpoint") {
  159. return true
  160. } else {
  161. return false
  162. }
  163. }
  164. }
  165. func MountDevice(mountpt string, mountdev string, filesystem string) error {
  166. //Check if running under sudo mode and in linux
  167. if runtime.GOOS == "linux" {
  168. //Try to mount the file system
  169. if mountdev == "" {
  170. return errors.New("Disk with automount enabled has no mountdev value: " + mountpt)
  171. }
  172. if mountpt == "" {
  173. return errors.New("Invalid storage.json. Mount point not given or not exists for " + mountdev)
  174. }
  175. //Check if device exists
  176. if !FileExists(mountdev) {
  177. //Device driver not exists.
  178. return errors.New("Device not exists: " + mountdev)
  179. }
  180. //Mount the device
  181. if CheckMounted(mountpt) {
  182. logger.PrintAndLog("Filesystem", mountpt+" already mounted.", nil)
  183. } else {
  184. logger.PrintAndLog("Filesystem", "Mounting "+mountdev+"("+filesystem+") to "+filepath.Clean(mountpt), nil)
  185. cmd := exec.Command("mount", "-t", filesystem, mountdev, filepath.Clean(mountpt))
  186. cmd.Stdout = os.Stdout
  187. cmd.Stderr = os.Stderr
  188. cmd.Run()
  189. }
  190. //Check if the path exists
  191. if !FileExists(mountpt) {
  192. //Mounted but path still not found. Skip this device
  193. return errors.New("Unable to find " + mountpt)
  194. }
  195. } else {
  196. return errors.New("Unsupported platform")
  197. }
  198. return nil
  199. }
  200. // ResolveDeviceByUUID tries to find a block device path (e.g. /dev/sdb1) by its
  201. // partition UUID using blkid. Linux only. Returns an error if the UUID is not found.
  202. func ResolveDeviceByUUID(partUUID string) (string, error) {
  203. if runtime.GOOS != "linux" {
  204. return "", errors.New("UUID-based device lookup is only supported on Linux")
  205. }
  206. if partUUID == "" {
  207. return "", errors.New("empty UUID given")
  208. }
  209. cmd := exec.Command("blkid", "-U", partUUID)
  210. var out bytes.Buffer
  211. cmd.Stdout = &out
  212. if err := cmd.Run(); err != nil {
  213. return "", fmt.Errorf("device with UUID %s not found: %v", partUUID, err)
  214. }
  215. devPath := strings.TrimSpace(out.String())
  216. if devPath == "" {
  217. return "", fmt.Errorf("UUID %s did not resolve to any device", partUUID)
  218. }
  219. return devPath, nil
  220. }
  221. func GetFileSize(filename string) int64 {
  222. fi, err := os.Stat(filename)
  223. if err != nil {
  224. return 0
  225. }
  226. // get the size
  227. return fi.Size()
  228. }
  229. func IsInsideHiddenFolder(path string) bool {
  230. thisPathInfo := filepath.ToSlash(filepath.Clean(path))
  231. pathData := strings.Split(thisPathInfo, "/")
  232. for _, thispd := range pathData {
  233. if len(thispd) > 0 && thispd[:1] == "." {
  234. //This path contain one of the folder is hidden
  235. return true
  236. }
  237. }
  238. return false
  239. }
  240. /*
  241. Wildcard Replacement Glob, design to hanle path with [ or ] inside.
  242. You can also pass in normal path for globing if you are not sure.
  243. */
  244. func WGlob(path string) ([]string, error) {
  245. files, err := filepath.Glob(path)
  246. if err != nil {
  247. return []string{}, err
  248. }
  249. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  250. if len(files) == 0 {
  251. //Handle reverse check. Replace all [ and ] with ?
  252. newSearchPath := strings.ReplaceAll(path, "[", "?")
  253. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  254. //Scan with all the similar structure except [ and ]
  255. tmpFilelist, _ := filepath.Glob(newSearchPath)
  256. for _, file := range tmpFilelist {
  257. file = filepath.ToSlash(file)
  258. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  259. files = append(files, file)
  260. }
  261. }
  262. }
  263. }
  264. //Convert all filepaths to slash
  265. for i := 0; i < len(files); i++ {
  266. files[i] = filepath.ToSlash(files[i])
  267. }
  268. return files, nil
  269. }
  270. /*
  271. Get Directory Size with native syscall (local drive only)
  272. faster than GetDirectorySize if system support du
  273. */
  274. func GetDirectorySizeNative(filename string) (int64, error) {
  275. d, err := apt.PackageExists("du")
  276. if err != nil || !d {
  277. return 0, err
  278. }
  279. //Convert the filename to absolute path
  280. abspath, err := filepath.Abs(filename)
  281. if err != nil {
  282. return 0, err
  283. }
  284. //du command exists
  285. //use native syscall to get disk size
  286. cmd := exec.Command("du", "-sb", abspath)
  287. out, err := cmd.CombinedOutput()
  288. if err != nil {
  289. return 0, err
  290. }
  291. //Return value is something like 481491222874 /media/storage2
  292. //We need to trim off the spaces
  293. tmp := string(out)
  294. tmp = strings.TrimSpace(tmp)
  295. tmp = strings.ReplaceAll(tmp, "\t", " ")
  296. for strings.Contains(tmp, " ") {
  297. tmp = strings.ReplaceAll(tmp, " ", " ")
  298. }
  299. chunks := strings.Split(tmp, " ")
  300. if len(chunks) <= 1 {
  301. return 0, errors.New("malformed output")
  302. }
  303. //The first chunk should be the size in bytes
  304. size, err := strconv.Atoi(chunks[0])
  305. if err != nil {
  306. return 0, errors.New("malformed output")
  307. }
  308. return int64(size), nil
  309. }
  310. /*
  311. Get Directory size, require filepath and include Hidden files option(true / false)
  312. Return total file size and file count
  313. */
  314. func GetDirctorySize(filename string, includeHidden bool) (int64, int) {
  315. var size int64 = 0
  316. var fileCount int = 0
  317. err := filepath.Walk(filename, func(thisFilename string, info os.FileInfo, err error) error {
  318. if err != nil {
  319. return err
  320. }
  321. if !info.IsDir() {
  322. if includeHidden {
  323. //append all into the file count and size
  324. size += info.Size()
  325. fileCount++
  326. } else {
  327. //Check if this is hidden
  328. if !IsInsideHiddenFolder(thisFilename) {
  329. size += info.Size()
  330. fileCount++
  331. }
  332. }
  333. }
  334. return err
  335. })
  336. if err != nil {
  337. return 0, fileCount
  338. }
  339. return size, fileCount
  340. }
  341. func GetFileDisplaySize(filesize int64, rounding int) string {
  342. precisionString := "%." + strconv.Itoa(rounding) + "f"
  343. bytes := float64(filesize)
  344. kilobytes := float64(bytes / 1024)
  345. if kilobytes < 1 {
  346. return fmt.Sprintf(precisionString, bytes) + "Bytes"
  347. }
  348. megabytes := float64(kilobytes / 1024)
  349. if megabytes < 1 {
  350. return fmt.Sprintf(precisionString, kilobytes) + "KB"
  351. }
  352. gigabytes := float64(megabytes / 1024)
  353. if gigabytes < 1 {
  354. return fmt.Sprintf(precisionString, megabytes) + "MB"
  355. }
  356. terabytes := float64(gigabytes / 1024)
  357. if terabytes < 1 {
  358. return fmt.Sprintf(precisionString, gigabytes) + "GB"
  359. }
  360. petabytes := float64(terabytes / 1024)
  361. if petabytes < 1 {
  362. return fmt.Sprintf(precisionString, terabytes) + "TB"
  363. }
  364. exabytes := float64(petabytes / 1024)
  365. if exabytes < 1 {
  366. return fmt.Sprintf(precisionString, petabytes) + "PB"
  367. }
  368. zettabytes := float64(exabytes / 1024)
  369. if zettabytes < 1 {
  370. return fmt.Sprintf(precisionString, exabytes) + "EB"
  371. }
  372. return fmt.Sprintf(precisionString, zettabytes) + "ZB"
  373. }
  374. func DecodeURI(inputPath string) string {
  375. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  376. inputPath, _ = url.QueryUnescape(inputPath)
  377. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  378. return inputPath
  379. }
  380. func GetMime(filename string) (string, string, error) {
  381. fileMime, err := mimetype.DetectFile(filename)
  382. if err != nil {
  383. return mime.TypeByExtension(filepath.Ext(filename)), filepath.Ext(filename), nil
  384. }
  385. return fileMime.String(), fileMime.Extension(), nil
  386. }
  387. func GetModTime(filepath string) (int64, error) {
  388. f, err := os.Open(filepath)
  389. if err != nil {
  390. return -1, err
  391. }
  392. statinfo, err := f.Stat()
  393. if err != nil {
  394. return -1, err
  395. }
  396. f.Close()
  397. return statinfo.ModTime().Unix(), nil
  398. }
  399. func UnderTheSameRoot(srcAbs string, destAbs string) (bool, error) {
  400. srcRoot, err := GetPhysicalRootFromPath(srcAbs)
  401. if err != nil {
  402. return false, err
  403. }
  404. destRoot, err := GetPhysicalRootFromPath(destAbs)
  405. if err != nil {
  406. return false, err
  407. }
  408. if srcRoot != "" && destRoot != "" {
  409. if srcRoot == destRoot {
  410. //apply fast move
  411. return true, nil
  412. }
  413. }
  414. return false, nil
  415. }
  416. // Get the physical root of a given filepath, e.g. C: or /home
  417. func GetPhysicalRootFromPath(filename string) (string, error) {
  418. filename, err := filepath.Abs(filename)
  419. if err != nil {
  420. return "", err
  421. }
  422. if filename[:1] == "/" {
  423. //Handle cases like /home/pi/foo.txt => return home
  424. filename = filename[1:]
  425. }
  426. filename = strings.TrimSpace(filename)
  427. if filename == "" {
  428. return "", nil
  429. }
  430. filename = filepath.ToSlash(filepath.Clean(filename))
  431. pathChunks := strings.Split(filename, "/")
  432. return pathChunks[0], nil
  433. }
  434. func GetFileSHA256Sum(filename string) (string, error) {
  435. f, err := os.Open(filename)
  436. if err != nil {
  437. return "", err
  438. }
  439. defer f.Close()
  440. h := sha256.New()
  441. if _, err := io.Copy(h, f); err != nil {
  442. return "", err
  443. }
  444. return hex.EncodeToString(h.Sum(nil)), nil
  445. }
  446. func GetFileMD5Sum(fsh *FileSystemHandler, rpath string) (string, error) {
  447. file, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  448. if err != nil {
  449. return "", err
  450. }
  451. h := md5.New()
  452. if _, err := io.Copy(h, file); err != nil {
  453. return "", err
  454. }
  455. file.Close()
  456. return hex.EncodeToString(h.Sum(nil)), nil
  457. }