osutil.go 6.3 KB

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