osutil.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. // Package osutil implements utilities for native OS support.
  7. package osutil
  8. import (
  9. "errors"
  10. "io"
  11. "path/filepath"
  12. "runtime"
  13. "strings"
  14. "github.com/syncthing/syncthing/lib/fs"
  15. "github.com/syncthing/syncthing/lib/sync"
  16. )
  17. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  18. // often enough that there is any contention on this lock.
  19. var renameLock = sync.NewMutex()
  20. // RenameOrCopy renames a file, leaving source file intact in case of failure.
  21. // Tries hard to succeed on various systems by temporarily tweaking directory
  22. // permissions and removing the destination file when necessary.
  23. func RenameOrCopy(src, dst fs.Filesystem, from, to string) error {
  24. renameLock.Lock()
  25. defer renameLock.Unlock()
  26. return withPreparedTarget(dst, from, to, func() error {
  27. // Optimisation 1
  28. if src.Type() == dst.Type() && src.URI() == dst.URI() {
  29. return src.Rename(from, to)
  30. }
  31. // "Optimisation" 2
  32. // Try to find a common prefix between the two filesystems, use that as the base for the new one
  33. // and try a rename.
  34. if src.Type() == dst.Type() {
  35. commonPrefix := fs.CommonPrefix(src.URI(), dst.URI())
  36. if len(commonPrefix) > 0 {
  37. commonFs := fs.NewFilesystem(src.Type(), commonPrefix)
  38. err := commonFs.Rename(
  39. filepath.Join(strings.TrimPrefix(src.URI(), commonPrefix), from),
  40. filepath.Join(strings.TrimPrefix(dst.URI(), commonPrefix), to),
  41. )
  42. if err == nil {
  43. return nil
  44. }
  45. }
  46. }
  47. // Everything is sad, do a copy and delete.
  48. if _, err := dst.Stat(to); !fs.IsNotExist(err) {
  49. err := dst.Remove(to)
  50. if err != nil {
  51. return err
  52. }
  53. }
  54. err := copyFileContents(src, dst, from, to)
  55. if err != nil {
  56. _ = dst.Remove(to)
  57. return err
  58. }
  59. return withPreparedTarget(src, from, from, func() error {
  60. return src.Remove(from)
  61. })
  62. })
  63. }
  64. // Copy copies the file content from source to destination.
  65. // Tries hard to succeed on various systems by temporarily tweaking directory
  66. // permissions and removing the destination file when necessary.
  67. func Copy(src, dst fs.Filesystem, from, to string) (err error) {
  68. return withPreparedTarget(dst, from, to, func() error {
  69. return copyFileContents(src, dst, from, to)
  70. })
  71. }
  72. // InWritableDir calls fn(path), while making sure that the directory
  73. // containing `path` is writable for the duration of the call.
  74. func InWritableDir(fn func(string) error, fs fs.Filesystem, path string) error {
  75. dir := filepath.Dir(path)
  76. info, err := fs.Stat(dir)
  77. if err != nil {
  78. return err
  79. }
  80. if !info.IsDir() {
  81. return errors.New("Not a directory: " + path)
  82. }
  83. if info.Mode()&0200 == 0 {
  84. // A non-writeable directory (for this user; we assume that's the
  85. // relevant part). Temporarily change the mode so we can delete the
  86. // file or directory inside it.
  87. err = fs.Chmod(dir, 0755)
  88. if err == nil {
  89. defer func() {
  90. err = fs.Chmod(dir, info.Mode())
  91. if err != nil {
  92. // We managed to change the permission bits like a
  93. // millisecond ago, so it'd be bizarre if we couldn't
  94. // change it back.
  95. panic(err)
  96. }
  97. }()
  98. }
  99. }
  100. return fn(path)
  101. }
  102. // Tries hard to succeed on various systems by temporarily tweaking directory
  103. // permissions and removing the destination file when necessary.
  104. func withPreparedTarget(filesystem fs.Filesystem, from, to string, f func() error) error {
  105. // Make sure the destination directory is writeable
  106. toDir := filepath.Dir(to)
  107. if info, err := filesystem.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  108. filesystem.Chmod(toDir, 0755)
  109. defer filesystem.Chmod(toDir, info.Mode())
  110. }
  111. // On Windows, make sure the destination file is writeable (or we can't delete it)
  112. if runtime.GOOS == "windows" {
  113. filesystem.Chmod(to, 0666)
  114. if !strings.EqualFold(from, to) {
  115. err := filesystem.Remove(to)
  116. if err != nil && !fs.IsNotExist(err) {
  117. return err
  118. }
  119. }
  120. }
  121. return f()
  122. }
  123. // copyFileContents copies the contents of the file named src to the file named
  124. // by dst. The file will be created if it does not already exist. If the
  125. // destination file exists, all its contents will be replaced by the contents
  126. // of the source file.
  127. func copyFileContents(srcFs, dstFs fs.Filesystem, src, dst string) (err error) {
  128. in, err := srcFs.Open(src)
  129. if err != nil {
  130. return
  131. }
  132. defer in.Close()
  133. out, err := dstFs.Create(dst)
  134. if err != nil {
  135. return
  136. }
  137. defer func() {
  138. cerr := out.Close()
  139. if err == nil {
  140. err = cerr
  141. }
  142. }()
  143. _, err = io.Copy(out, in)
  144. return
  145. }
  146. func IsDeleted(ffs fs.Filesystem, name string) bool {
  147. if _, err := ffs.Lstat(name); fs.IsNotExist(err) {
  148. return true
  149. }
  150. switch TraversesSymlink(ffs, filepath.Dir(name)).(type) {
  151. case *NotADirectoryError, *TraversesSymlinkError:
  152. return true
  153. }
  154. return false
  155. }