osutil.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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(from, 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. if !(runtime.GOOS == "windows" && strings.EqualFold(from, to)) {
  40. defer os.Remove(from)
  41. }
  42. return TryRename(from, to)
  43. }
  44. // Copy copies the file content from source to destination.
  45. // Tries hard to succeed on various systems by temporarily tweaking directory
  46. // permissions and removing the destination file when necessary.
  47. func Copy(from, to string) (err error) {
  48. return withPreparedTarget(from, to, func() error {
  49. return copyFileContents(from, to)
  50. })
  51. }
  52. // InWritableDir calls fn(path), while making sure that the directory
  53. // containing `path` is writable for the duration of the call.
  54. func InWritableDir(fn func(string) error, path string) error {
  55. dir := filepath.Dir(path)
  56. info, err := os.Stat(dir)
  57. if err != nil {
  58. return err
  59. }
  60. if !info.IsDir() {
  61. return errors.New("Not a directory: " + path)
  62. }
  63. if info.Mode()&0200 == 0 {
  64. // A non-writeable directory (for this user; we assume that's the
  65. // relevant part). Temporarily change the mode so we can delete the
  66. // file or directory inside it.
  67. err = os.Chmod(dir, 0755)
  68. if err == nil {
  69. defer func() {
  70. err = os.Chmod(dir, info.Mode())
  71. if err != nil {
  72. // We managed to change the permission bits like a
  73. // millisecond ago, so it'd be bizarre if we couldn't
  74. // change it back.
  75. panic(err)
  76. }
  77. }()
  78. }
  79. }
  80. return fn(path)
  81. }
  82. // Remove removes the given path. On Windows, removes the read-only attribute
  83. // from the target prior to deletion.
  84. func Remove(path string) error {
  85. if runtime.GOOS == "windows" {
  86. info, err := os.Stat(path)
  87. if err != nil {
  88. return err
  89. }
  90. if info.Mode()&0200 == 0 {
  91. os.Chmod(path, 0700)
  92. }
  93. }
  94. return os.Remove(path)
  95. }
  96. func ExpandTilde(path string) (string, error) {
  97. if path == "~" {
  98. return getHomeDir()
  99. }
  100. path = filepath.FromSlash(path)
  101. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  102. return path, nil
  103. }
  104. home, err := getHomeDir()
  105. if err != nil {
  106. return "", err
  107. }
  108. return filepath.Join(home, path[2:]), nil
  109. }
  110. func getHomeDir() (string, error) {
  111. var home string
  112. switch runtime.GOOS {
  113. case "windows":
  114. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  115. if home == "" {
  116. home = os.Getenv("UserProfile")
  117. }
  118. default:
  119. home = os.Getenv("HOME")
  120. }
  121. if home == "" {
  122. return "", ErrNoHome
  123. }
  124. return home, nil
  125. }
  126. // Tries hard to succeed on various systems by temporarily tweaking directory
  127. // permissions and removing the destination file when necessary.
  128. func withPreparedTarget(from, to string, f func() error) error {
  129. // Make sure the destination directory is writeable
  130. toDir := filepath.Dir(to)
  131. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  132. os.Chmod(toDir, 0755)
  133. defer os.Chmod(toDir, info.Mode())
  134. }
  135. // On Windows, make sure the destination file is writeable (or we can't delete it)
  136. if runtime.GOOS == "windows" {
  137. os.Chmod(to, 0666)
  138. if !strings.EqualFold(from, to) {
  139. err := os.Remove(to)
  140. if err != nil && !os.IsNotExist(err) {
  141. return err
  142. }
  143. }
  144. }
  145. return f()
  146. }
  147. // copyFileContents copies the contents of the file named src to the file named
  148. // by dst. The file will be created if it does not already exist. If the
  149. // destination file exists, all it's contents will be replaced by the contents
  150. // of the source file.
  151. func copyFileContents(src, dst string) (err error) {
  152. in, err := os.Open(src)
  153. if err != nil {
  154. return
  155. }
  156. defer in.Close()
  157. out, err := os.Create(dst)
  158. if err != nil {
  159. return
  160. }
  161. defer func() {
  162. cerr := out.Close()
  163. if err == nil {
  164. err = cerr
  165. }
  166. }()
  167. if _, err = io.Copy(out, in); err != nil {
  168. return
  169. }
  170. err = out.Sync()
  171. return
  172. }
  173. var execExts map[string]bool
  174. func init() {
  175. // PATHEXT contains a list of executable file extensions, on Windows
  176. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  177. // We want the extensions in execExts to be lower case
  178. execExts = make(map[string]bool, len(pathext))
  179. for _, ext := range pathext {
  180. execExts[strings.ToLower(ext)] = true
  181. }
  182. }
  183. // IsWindowsExecutable returns true if the given path has an extension that is
  184. // in the list of executable extensions.
  185. func IsWindowsExecutable(path string) bool {
  186. return execExts[strings.ToLower(filepath.Ext(path))]
  187. }