osutil.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 http://mozilla.org/MPL/2.0/.
  6. // Package osutil implements utilities for native OS support.
  7. package osutil
  8. import (
  9. "errors"
  10. "fmt"
  11. "io"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strings"
  16. "github.com/syncthing/syncthing/internal/sync"
  17. )
  18. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  19. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  20. // often enough that there is any contention on this lock.
  21. var renameLock = sync.NewMutex()
  22. // TryRename renames a file, leaving source file intact in case of failure.
  23. // Tries hard to succeed on various systems by temporarily tweaking directory
  24. // permissions and removing the destination file when necessary.
  25. func TryRename(from, to string) error {
  26. renameLock.Lock()
  27. defer renameLock.Unlock()
  28. return withPreparedTarget(to, func() error {
  29. return os.Rename(from, to)
  30. })
  31. }
  32. // Rename moves a temporary file to it's final place.
  33. // Will make sure to delete the from file if the operation fails, so use only
  34. // for situations like committing a temp file to it's final location.
  35. // Tries hard to succeed on various systems by temporarily tweaking directory
  36. // permissions and removing the destination file when necessary.
  37. func Rename(from, to string) error {
  38. // Don't leave a dangling temp file in case of rename error
  39. defer os.Remove(from)
  40. return TryRename(from, to)
  41. }
  42. // Copy copies the file content from source to destination.
  43. // Tries hard to succeed on various systems by temporarily tweaking directory
  44. // permissions and removing the destination file when necessary.
  45. func Copy(from, to string) (err error) {
  46. return withPreparedTarget(to, func() error {
  47. return copyFileContents(from, to)
  48. })
  49. }
  50. // InWritableDir calls fn(path), while making sure that the directory
  51. // containing `path` is writable for the duration of the call.
  52. func InWritableDir(fn func(string) error, path string) error {
  53. dir := filepath.Dir(path)
  54. info, err := os.Stat(dir)
  55. if err != nil {
  56. return err
  57. }
  58. if !info.IsDir() {
  59. return errors.New("Not a directory: " + path)
  60. }
  61. if info.Mode()&0200 == 0 {
  62. // A non-writeable directory (for this user; we assume that's the
  63. // relevant part). Temporarily change the mode so we can delete the
  64. // file or directory inside it.
  65. err = os.Chmod(dir, 0755)
  66. if err == nil {
  67. defer func() {
  68. err = os.Chmod(dir, info.Mode())
  69. if err != nil {
  70. // We managed to change the permission bits like a
  71. // millisecond ago, so it'd be bizarre if we couldn't
  72. // change it back.
  73. panic(err)
  74. }
  75. }()
  76. }
  77. }
  78. return fn(path)
  79. }
  80. // Remove removes the given path. On Windows, removes the read-only attribute
  81. // from the target prior to deletion.
  82. func Remove(path string) error {
  83. if runtime.GOOS == "windows" {
  84. info, err := os.Stat(path)
  85. if err != nil {
  86. return err
  87. }
  88. if info.Mode()&0200 == 0 {
  89. os.Chmod(path, 0700)
  90. }
  91. }
  92. return os.Remove(path)
  93. }
  94. func ExpandTilde(path string) (string, error) {
  95. if path == "~" {
  96. return getHomeDir()
  97. }
  98. path = filepath.FromSlash(path)
  99. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  100. return path, nil
  101. }
  102. home, err := getHomeDir()
  103. if err != nil {
  104. return "", err
  105. }
  106. return filepath.Join(home, path[2:]), nil
  107. }
  108. func getHomeDir() (string, error) {
  109. var home string
  110. switch runtime.GOOS {
  111. case "windows":
  112. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  113. if home == "" {
  114. home = os.Getenv("UserProfile")
  115. }
  116. default:
  117. home = os.Getenv("HOME")
  118. }
  119. if home == "" {
  120. return "", ErrNoHome
  121. }
  122. return home, nil
  123. }
  124. // Tries hard to succeed on various systems by temporarily tweaking directory
  125. // permissions and removing the destination file when necessary.
  126. func withPreparedTarget(to string, f func() error) error {
  127. // Make sure the destination directory is writeable
  128. toDir := filepath.Dir(to)
  129. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  130. os.Chmod(toDir, 0755)
  131. defer os.Chmod(toDir, info.Mode())
  132. }
  133. // On Windows, make sure the destination file is writeable (or we can't delete it)
  134. if runtime.GOOS == "windows" {
  135. os.Chmod(to, 0666)
  136. err := os.Remove(to)
  137. if err != nil && !os.IsNotExist(err) {
  138. return err
  139. }
  140. }
  141. return f()
  142. }
  143. // copyFileContents copies the contents of the file named src to the file named
  144. // by dst. The file will be created if it does not already exist. If the
  145. // destination file exists, all it's contents will be replaced by the contents
  146. // of the source file.
  147. func copyFileContents(src, dst string) (err error) {
  148. in, err := os.Open(src)
  149. if err != nil {
  150. return
  151. }
  152. defer in.Close()
  153. out, err := os.Create(dst)
  154. if err != nil {
  155. return
  156. }
  157. defer func() {
  158. cerr := out.Close()
  159. if err == nil {
  160. err = cerr
  161. }
  162. }()
  163. if _, err = io.Copy(out, in); err != nil {
  164. return
  165. }
  166. err = out.Sync()
  167. return
  168. }