1
0

osutil.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. "os"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "github.com/syncthing/syncthing/lib/fs"
  16. "github.com/syncthing/syncthing/lib/sync"
  17. )
  18. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  19. // often enough that there is any contention on this lock.
  20. var renameLock = sync.NewMutex()
  21. // TryRename renames a file, leaving source file intact in case of failure.
  22. // Tries hard to succeed on various systems by temporarily tweaking directory
  23. // permissions and removing the destination file when necessary.
  24. func TryRename(filesystem fs.Filesystem, from, to string) error {
  25. renameLock.Lock()
  26. defer renameLock.Unlock()
  27. return withPreparedTarget(filesystem, from, to, func() error {
  28. return filesystem.Rename(from, to)
  29. })
  30. }
  31. // Rename moves a temporary file to its final place.
  32. // Will make sure to delete the from file if the operation fails, so use only
  33. // for situations like committing a temp file to its final location.
  34. // Tries hard to succeed on various systems by temporarily tweaking directory
  35. // permissions and removing the destination file when necessary.
  36. func Rename(filesystem fs.Filesystem, from, to string) error {
  37. // Don't leave a dangling temp file in case of rename error
  38. if !(runtime.GOOS == "windows" && strings.EqualFold(from, to)) {
  39. defer filesystem.Remove(from)
  40. }
  41. return TryRename(filesystem, from, to)
  42. }
  43. // Copy copies the file content from source to destination.
  44. // Tries hard to succeed on various systems by temporarily tweaking directory
  45. // permissions and removing the destination file when necessary.
  46. func Copy(filesystem fs.Filesystem, from, to string) (err error) {
  47. return withPreparedTarget(filesystem, from, to, func() error {
  48. return copyFileContents(filesystem, from, to)
  49. })
  50. }
  51. // InWritableDir calls fn(path), while making sure that the directory
  52. // containing `path` is writable for the duration of the call.
  53. func InWritableDir(fn func(string) error, fs fs.Filesystem, path string) error {
  54. dir := filepath.Dir(path)
  55. info, err := fs.Stat(dir)
  56. if err != nil {
  57. return err
  58. }
  59. if !info.IsDir() {
  60. return errors.New("Not a directory: " + path)
  61. }
  62. if info.Mode()&0200 == 0 {
  63. // A non-writeable directory (for this user; we assume that's the
  64. // relevant part). Temporarily change the mode so we can delete the
  65. // file or directory inside it.
  66. err = fs.Chmod(dir, 0755)
  67. if err == nil {
  68. defer func() {
  69. err = fs.Chmod(dir, info.Mode())
  70. if err != nil {
  71. // We managed to change the permission bits like a
  72. // millisecond ago, so it'd be bizarre if we couldn't
  73. // change it back.
  74. panic(err)
  75. }
  76. }()
  77. }
  78. }
  79. return fn(path)
  80. }
  81. // Tries hard to succeed on various systems by temporarily tweaking directory
  82. // permissions and removing the destination file when necessary.
  83. func withPreparedTarget(filesystem fs.Filesystem, from, to string, f func() error) error {
  84. // Make sure the destination directory is writeable
  85. toDir := filepath.Dir(to)
  86. if info, err := filesystem.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  87. filesystem.Chmod(toDir, 0755)
  88. defer filesystem.Chmod(toDir, info.Mode())
  89. }
  90. // On Windows, make sure the destination file is writeable (or we can't delete it)
  91. if runtime.GOOS == "windows" {
  92. filesystem.Chmod(to, 0666)
  93. if !strings.EqualFold(from, to) {
  94. err := filesystem.Remove(to)
  95. if err != nil && !fs.IsNotExist(err) {
  96. return err
  97. }
  98. }
  99. }
  100. return f()
  101. }
  102. // copyFileContents copies the contents of the file named src to the file named
  103. // by dst. The file will be created if it does not already exist. If the
  104. // destination file exists, all its contents will be replaced by the contents
  105. // of the source file.
  106. func copyFileContents(filesystem fs.Filesystem, src, dst string) (err error) {
  107. in, err := filesystem.Open(src)
  108. if err != nil {
  109. return
  110. }
  111. defer in.Close()
  112. out, err := filesystem.Create(dst)
  113. if err != nil {
  114. return
  115. }
  116. defer func() {
  117. cerr := out.Close()
  118. if err == nil {
  119. err = cerr
  120. }
  121. }()
  122. _, err = io.Copy(out, in)
  123. return
  124. }
  125. var execExts map[string]bool
  126. func init() {
  127. // PATHEXT contains a list of executable file extensions, on Windows
  128. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  129. // We want the extensions in execExts to be lower case
  130. execExts = make(map[string]bool, len(pathext))
  131. for _, ext := range pathext {
  132. execExts[strings.ToLower(ext)] = true
  133. }
  134. }
  135. // IsWindowsExecutable returns true if the given path has an extension that is
  136. // in the list of executable extensions.
  137. func IsWindowsExecutable(path string) bool {
  138. return execExts[strings.ToLower(filepath.Ext(path))]
  139. }
  140. func IsDeleted(ffs fs.Filesystem, name string) bool {
  141. if _, err := ffs.Lstat(name); fs.IsNotExist(err) {
  142. return true
  143. }
  144. switch TraversesSymlink(ffs, filepath.Dir(name)).(type) {
  145. case *NotADirectoryError, *TraversesSymlinkError:
  146. return true
  147. }
  148. return false
  149. }