osutil.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. "syscall"
  17. "github.com/calmh/du"
  18. "github.com/syncthing/syncthing/lib/sync"
  19. )
  20. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  21. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  22. // often enough that there is any contention on this lock.
  23. var renameLock = sync.NewMutex()
  24. // TryRename renames a file, leaving source file intact in case of failure.
  25. // Tries hard to succeed on various systems by temporarily tweaking directory
  26. // permissions and removing the destination file when necessary.
  27. func TryRename(from, to string) error {
  28. renameLock.Lock()
  29. defer renameLock.Unlock()
  30. return withPreparedTarget(from, to, func() error {
  31. return os.Rename(from, to)
  32. })
  33. }
  34. // Rename moves a temporary file to it's final place.
  35. // Will make sure to delete the from file if the operation fails, so use only
  36. // for situations like committing a temp file to it's final location.
  37. // Tries hard to succeed on various systems by temporarily tweaking directory
  38. // permissions and removing the destination file when necessary.
  39. func Rename(from, to string) error {
  40. // Don't leave a dangling temp file in case of rename error
  41. if !(runtime.GOOS == "windows" && strings.EqualFold(from, to)) {
  42. defer os.Remove(from)
  43. }
  44. return TryRename(from, to)
  45. }
  46. // Copy copies the file content from source to destination.
  47. // Tries hard to succeed on various systems by temporarily tweaking directory
  48. // permissions and removing the destination file when necessary.
  49. func Copy(from, to string) (err error) {
  50. return withPreparedTarget(from, to, func() error {
  51. return copyFileContents(from, to)
  52. })
  53. }
  54. // InWritableDir calls fn(path), while making sure that the directory
  55. // containing `path` is writable for the duration of the call.
  56. func InWritableDir(fn func(string) error, path string) error {
  57. dir := filepath.Dir(path)
  58. info, err := os.Stat(dir)
  59. if err != nil {
  60. return err
  61. }
  62. if !info.IsDir() {
  63. return errors.New("Not a directory: " + path)
  64. }
  65. if info.Mode()&0200 == 0 {
  66. // A non-writeable directory (for this user; we assume that's the
  67. // relevant part). Temporarily change the mode so we can delete the
  68. // file or directory inside it.
  69. err = os.Chmod(dir, 0755)
  70. if err == nil {
  71. defer func() {
  72. err = os.Chmod(dir, info.Mode())
  73. if err != nil {
  74. // We managed to change the permission bits like a
  75. // millisecond ago, so it'd be bizarre if we couldn't
  76. // change it back.
  77. panic(err)
  78. }
  79. }()
  80. }
  81. }
  82. return fn(path)
  83. }
  84. // Remove removes the given path. On Windows, removes the read-only attribute
  85. // from the target prior to deletion.
  86. func Remove(path string) error {
  87. if runtime.GOOS == "windows" {
  88. info, err := os.Stat(path)
  89. if err != nil {
  90. return err
  91. }
  92. if info.Mode()&0200 == 0 {
  93. os.Chmod(path, 0700)
  94. }
  95. }
  96. return os.Remove(path)
  97. }
  98. // RemoveAll is a copy of os.RemoveAll, but uses osutil.Remove.
  99. // RemoveAll removes path and any children it contains.
  100. // It removes everything it can but returns the first error
  101. // it encounters. If the path does not exist, RemoveAll
  102. // returns nil (no error).
  103. func RemoveAll(path string) error {
  104. // Simple case: if Remove works, we're done.
  105. err := Remove(path)
  106. if err == nil || os.IsNotExist(err) {
  107. return nil
  108. }
  109. // Otherwise, is this a directory we need to recurse into?
  110. dir, serr := os.Lstat(path)
  111. if serr != nil {
  112. if serr, ok := serr.(*os.PathError); ok && (os.IsNotExist(serr.Err) || serr.Err == syscall.ENOTDIR) {
  113. return nil
  114. }
  115. return serr
  116. }
  117. if !dir.IsDir() {
  118. // Not a directory; return the error from Remove.
  119. return err
  120. }
  121. // Directory.
  122. fd, err := os.Open(path)
  123. if err != nil {
  124. if os.IsNotExist(err) {
  125. // Race. It was deleted between the Lstat and Open.
  126. // Return nil per RemoveAll's docs.
  127. return nil
  128. }
  129. return err
  130. }
  131. // Remove contents & return first error.
  132. err = nil
  133. for {
  134. names, err1 := fd.Readdirnames(100)
  135. for _, name := range names {
  136. err1 := RemoveAll(path + string(os.PathSeparator) + name)
  137. if err == nil {
  138. err = err1
  139. }
  140. }
  141. if err1 == io.EOF {
  142. break
  143. }
  144. // If Readdirnames returned an error, use it.
  145. if err == nil {
  146. err = err1
  147. }
  148. if len(names) == 0 {
  149. break
  150. }
  151. }
  152. // Close directory, because windows won't remove opened directory.
  153. fd.Close()
  154. // Remove directory.
  155. err1 := Remove(path)
  156. if err1 == nil || os.IsNotExist(err1) {
  157. return nil
  158. }
  159. if err == nil {
  160. err = err1
  161. }
  162. return err
  163. }
  164. func ExpandTilde(path string) (string, error) {
  165. if path == "~" {
  166. return getHomeDir()
  167. }
  168. path = filepath.FromSlash(path)
  169. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  170. return path, nil
  171. }
  172. home, err := getHomeDir()
  173. if err != nil {
  174. return "", err
  175. }
  176. return filepath.Join(home, path[2:]), nil
  177. }
  178. func getHomeDir() (string, error) {
  179. var home string
  180. switch runtime.GOOS {
  181. case "windows":
  182. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  183. if home == "" {
  184. home = os.Getenv("UserProfile")
  185. }
  186. default:
  187. home = os.Getenv("HOME")
  188. }
  189. if home == "" {
  190. return "", ErrNoHome
  191. }
  192. return home, nil
  193. }
  194. // Tries hard to succeed on various systems by temporarily tweaking directory
  195. // permissions and removing the destination file when necessary.
  196. func withPreparedTarget(from, to string, f func() error) error {
  197. // Make sure the destination directory is writeable
  198. toDir := filepath.Dir(to)
  199. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  200. os.Chmod(toDir, 0755)
  201. defer os.Chmod(toDir, info.Mode())
  202. }
  203. // On Windows, make sure the destination file is writeable (or we can't delete it)
  204. if runtime.GOOS == "windows" {
  205. os.Chmod(to, 0666)
  206. if !strings.EqualFold(from, to) {
  207. err := os.Remove(to)
  208. if err != nil && !os.IsNotExist(err) {
  209. return err
  210. }
  211. }
  212. }
  213. return f()
  214. }
  215. // copyFileContents copies the contents of the file named src to the file named
  216. // by dst. The file will be created if it does not already exist. If the
  217. // destination file exists, all it's contents will be replaced by the contents
  218. // of the source file.
  219. func copyFileContents(src, dst string) (err error) {
  220. in, err := os.Open(src)
  221. if err != nil {
  222. return
  223. }
  224. defer in.Close()
  225. out, err := os.Create(dst)
  226. if err != nil {
  227. return
  228. }
  229. defer func() {
  230. cerr := out.Close()
  231. if err == nil {
  232. err = cerr
  233. }
  234. }()
  235. if _, err = io.Copy(out, in); err != nil {
  236. return
  237. }
  238. err = out.Sync()
  239. return
  240. }
  241. var execExts map[string]bool
  242. func init() {
  243. // PATHEXT contains a list of executable file extensions, on Windows
  244. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  245. // We want the extensions in execExts to be lower case
  246. execExts = make(map[string]bool, len(pathext))
  247. for _, ext := range pathext {
  248. execExts[strings.ToLower(ext)] = true
  249. }
  250. }
  251. // IsWindowsExecutable returns true if the given path has an extension that is
  252. // in the list of executable extensions.
  253. func IsWindowsExecutable(path string) bool {
  254. return execExts[strings.ToLower(filepath.Ext(path))]
  255. }
  256. func DiskFreeBytes(path string) (free int64, err error) {
  257. u, err := du.Get(path)
  258. return u.FreeBytes, err
  259. }
  260. func DiskFreePercentage(path string) (freePct float64, err error) {
  261. u, err := du.Get(path)
  262. return (float64(u.FreeBytes) / float64(u.TotalBytes)) * 100, err
  263. }