osutil.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. "net"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "time"
  19. "github.com/calmh/du"
  20. "github.com/syncthing/syncthing/lib/sync"
  21. )
  22. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  23. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  24. // often enough that there is any contention on this lock.
  25. var renameLock = sync.NewMutex()
  26. // TryRename renames a file, leaving source file intact in case of failure.
  27. // Tries hard to succeed on various systems by temporarily tweaking directory
  28. // permissions and removing the destination file when necessary.
  29. func TryRename(from, to string) error {
  30. renameLock.Lock()
  31. defer renameLock.Unlock()
  32. return withPreparedTarget(from, to, func() error {
  33. return os.Rename(from, to)
  34. })
  35. }
  36. // Rename moves a temporary file to it's final place.
  37. // Will make sure to delete the from file if the operation fails, so use only
  38. // for situations like committing a temp file to it's final location.
  39. // Tries hard to succeed on various systems by temporarily tweaking directory
  40. // permissions and removing the destination file when necessary.
  41. func Rename(from, to string) error {
  42. // Don't leave a dangling temp file in case of rename error
  43. if !(runtime.GOOS == "windows" && strings.EqualFold(from, to)) {
  44. defer os.Remove(from)
  45. }
  46. return TryRename(from, to)
  47. }
  48. // Copy copies the file content from source to destination.
  49. // Tries hard to succeed on various systems by temporarily tweaking directory
  50. // permissions and removing the destination file when necessary.
  51. func Copy(from, to string) (err error) {
  52. return withPreparedTarget(from, to, func() error {
  53. return copyFileContents(from, to)
  54. })
  55. }
  56. // InWritableDir calls fn(path), while making sure that the directory
  57. // containing `path` is writable for the duration of the call.
  58. func InWritableDir(fn func(string) error, path string) error {
  59. dir := filepath.Dir(path)
  60. info, err := os.Stat(dir)
  61. if err != nil {
  62. return err
  63. }
  64. if !info.IsDir() {
  65. return errors.New("Not a directory: " + path)
  66. }
  67. if info.Mode()&0200 == 0 {
  68. // A non-writeable directory (for this user; we assume that's the
  69. // relevant part). Temporarily change the mode so we can delete the
  70. // file or directory inside it.
  71. err = os.Chmod(dir, 0755)
  72. if err == nil {
  73. defer func() {
  74. err = os.Chmod(dir, info.Mode())
  75. if err != nil {
  76. // We managed to change the permission bits like a
  77. // millisecond ago, so it'd be bizarre if we couldn't
  78. // change it back.
  79. panic(err)
  80. }
  81. }()
  82. }
  83. }
  84. return fn(path)
  85. }
  86. // Remove removes the given path. On Windows, removes the read-only attribute
  87. // from the target prior to deletion.
  88. func Remove(path string) error {
  89. if runtime.GOOS == "windows" {
  90. info, err := os.Stat(path)
  91. if err != nil {
  92. return err
  93. }
  94. if info.Mode()&0200 == 0 {
  95. os.Chmod(path, 0700)
  96. }
  97. }
  98. return os.Remove(path)
  99. }
  100. func ExpandTilde(path string) (string, error) {
  101. if path == "~" {
  102. return getHomeDir()
  103. }
  104. path = filepath.FromSlash(path)
  105. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  106. return path, nil
  107. }
  108. home, err := getHomeDir()
  109. if err != nil {
  110. return "", err
  111. }
  112. return filepath.Join(home, path[2:]), nil
  113. }
  114. func getHomeDir() (string, error) {
  115. var home string
  116. switch runtime.GOOS {
  117. case "windows":
  118. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  119. if home == "" {
  120. home = os.Getenv("UserProfile")
  121. }
  122. default:
  123. home = os.Getenv("HOME")
  124. }
  125. if home == "" {
  126. return "", ErrNoHome
  127. }
  128. return home, nil
  129. }
  130. // Tries hard to succeed on various systems by temporarily tweaking directory
  131. // permissions and removing the destination file when necessary.
  132. func withPreparedTarget(from, to string, f func() error) error {
  133. // Make sure the destination directory is writeable
  134. toDir := filepath.Dir(to)
  135. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  136. os.Chmod(toDir, 0755)
  137. defer os.Chmod(toDir, info.Mode())
  138. }
  139. // On Windows, make sure the destination file is writeable (or we can't delete it)
  140. if runtime.GOOS == "windows" {
  141. os.Chmod(to, 0666)
  142. if !strings.EqualFold(from, to) {
  143. err := os.Remove(to)
  144. if err != nil && !os.IsNotExist(err) {
  145. return err
  146. }
  147. }
  148. }
  149. return f()
  150. }
  151. // copyFileContents copies the contents of the file named src to the file named
  152. // by dst. The file will be created if it does not already exist. If the
  153. // destination file exists, all it's contents will be replaced by the contents
  154. // of the source file.
  155. func copyFileContents(src, dst string) (err error) {
  156. in, err := os.Open(src)
  157. if err != nil {
  158. return
  159. }
  160. defer in.Close()
  161. out, err := os.Create(dst)
  162. if err != nil {
  163. return
  164. }
  165. defer func() {
  166. cerr := out.Close()
  167. if err == nil {
  168. err = cerr
  169. }
  170. }()
  171. if _, err = io.Copy(out, in); err != nil {
  172. return
  173. }
  174. err = out.Sync()
  175. return
  176. }
  177. var execExts map[string]bool
  178. func init() {
  179. // PATHEXT contains a list of executable file extensions, on Windows
  180. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  181. // We want the extensions in execExts to be lower case
  182. execExts = make(map[string]bool, len(pathext))
  183. for _, ext := range pathext {
  184. execExts[strings.ToLower(ext)] = true
  185. }
  186. }
  187. // IsWindowsExecutable returns true if the given path has an extension that is
  188. // in the list of executable extensions.
  189. func IsWindowsExecutable(path string) bool {
  190. return execExts[strings.ToLower(filepath.Ext(path))]
  191. }
  192. func DiskFreeBytes(path string) (free int64, err error) {
  193. u, err := du.Get(path)
  194. return u.FreeBytes, err
  195. }
  196. func DiskFreePercentage(path string) (freePct float64, err error) {
  197. u, err := du.Get(path)
  198. return (float64(u.FreeBytes) / float64(u.TotalBytes)) * 100, err
  199. }
  200. // SetTCPOptions sets syncthings default TCP options on a TCP connection
  201. func SetTCPOptions(conn *net.TCPConn) error {
  202. var err error
  203. if err = conn.SetLinger(0); err != nil {
  204. return err
  205. }
  206. if err = conn.SetNoDelay(false); err != nil {
  207. return err
  208. }
  209. if err = conn.SetKeepAlivePeriod(60 * time.Second); err != nil {
  210. return err
  211. }
  212. if err = conn.SetKeepAlive(true); err != nil {
  213. return err
  214. }
  215. return nil
  216. }
  217. // The CachedCaseSensitiveStat provides an Lstat() method similar to
  218. // os.Lstat(), but that is always case sensitive regardless of underlying file
  219. // system semantics. The "Cached" part refers to the fact that it lists the
  220. // contents of a directory the first time it's needed and then retains this
  221. // information for the duration. It's expected that instances of this type are
  222. // fairly short lived.
  223. //
  224. // There's some song and dance to check directories that are parents to the
  225. // checked path as well, that is we want to catch the situation that someone
  226. // calls Lstat("foo/BAR/baz") when the actual path is "foo/bar/baz" and return
  227. // NotExist appropriately. But we don't want to do this check too high up, as
  228. // the user may have told us the folder path is ~/Sync while it is actually
  229. // ~/sync and this *should* work properly... Sigh. Hence the "base" parameter.
  230. type CachedCaseSensitiveStat struct {
  231. base string // base directory, we should not check stuff above this
  232. results map[string][]os.FileInfo // directory path => list of children
  233. }
  234. func NewCachedCaseSensitiveStat(base string) *CachedCaseSensitiveStat {
  235. return &CachedCaseSensitiveStat{
  236. base: strings.ToLower(base),
  237. results: make(map[string][]os.FileInfo),
  238. }
  239. }
  240. func (c *CachedCaseSensitiveStat) Lstat(name string) (os.FileInfo, error) {
  241. dir := filepath.Dir(name)
  242. base := filepath.Base(name)
  243. if !strings.HasPrefix(strings.ToLower(dir), c.base) {
  244. // We only validate things within the base directory, which we need to
  245. // compare case insensitively against.
  246. return nil, os.ErrInvalid
  247. }
  248. // If we don't already have a list of directory entries for this
  249. // directory, try to list it. Return error if this fails.
  250. l, ok := c.results[dir]
  251. if !ok {
  252. if len(dir) > len(c.base) {
  253. // We are checking in a subdirectory of base. Must make sure *it*
  254. // exists with the specified casing, up to the base directory.
  255. if _, err := c.Lstat(dir); err != nil {
  256. return nil, err
  257. }
  258. }
  259. fd, err := os.Open(dir)
  260. if err != nil {
  261. return nil, err
  262. }
  263. defer fd.Close()
  264. l, err = fd.Readdir(-1)
  265. if err != nil {
  266. return nil, err
  267. }
  268. sort.Sort(fileInfoList(l))
  269. c.results[dir] = l
  270. }
  271. // Get the index of the first entry with name >= base using binary search.
  272. idx := sort.Search(len(l), func(i int) bool {
  273. return l[i].Name() >= base
  274. })
  275. if idx >= len(l) || l[idx].Name() != base {
  276. // The search didn't find any such entry
  277. return nil, os.ErrNotExist
  278. }
  279. return l[idx], nil
  280. }
  281. type fileInfoList []os.FileInfo
  282. func (l fileInfoList) Len() int {
  283. return len(l)
  284. }
  285. func (l fileInfoList) Swap(a, b int) {
  286. l[a], l[b] = l[b], l[a]
  287. }
  288. func (l fileInfoList) Less(a, b int) bool {
  289. return l[a].Name() < l[b].Name()
  290. }