file_windows.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package loggerutils
  2. import (
  3. "os"
  4. "path/filepath"
  5. "syscall"
  6. "unsafe"
  7. )
  8. func open(name string) (*os.File, error) {
  9. return openFile(name, os.O_RDONLY, 0)
  10. }
  11. func openFile(name string, flag int, perm os.FileMode) (*os.File, error) {
  12. if name == "" {
  13. return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT}
  14. }
  15. h, err := syscallOpen(fixLongPath(name), flag|syscall.O_CLOEXEC, syscallMode(perm))
  16. if err != nil {
  17. return nil, &os.PathError{Op: "open", Path: name, Err: err}
  18. }
  19. return os.NewFile(uintptr(h), name), nil
  20. }
  21. // syscallOpen is copied from syscall.Open but is modified to
  22. // always open a file with FILE_SHARE_DELETE
  23. func syscallOpen(path string, mode int, perm uint32) (fd syscall.Handle, err error) {
  24. if len(path) == 0 {
  25. return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND
  26. }
  27. pathp, err := syscall.UTF16PtrFromString(path)
  28. if err != nil {
  29. return syscall.InvalidHandle, err
  30. }
  31. var access uint32
  32. switch mode & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) {
  33. case syscall.O_RDONLY:
  34. access = syscall.GENERIC_READ
  35. case syscall.O_WRONLY:
  36. access = syscall.GENERIC_WRITE
  37. case syscall.O_RDWR:
  38. access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
  39. }
  40. if mode&syscall.O_CREAT != 0 {
  41. access |= syscall.GENERIC_WRITE
  42. }
  43. if mode&syscall.O_APPEND != 0 {
  44. access &^= syscall.GENERIC_WRITE
  45. access |= syscall.FILE_APPEND_DATA
  46. }
  47. sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE)
  48. var sa *syscall.SecurityAttributes
  49. if mode&syscall.O_CLOEXEC == 0 {
  50. sa = makeInheritSa()
  51. }
  52. var createmode uint32
  53. switch {
  54. case mode&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL):
  55. createmode = syscall.CREATE_NEW
  56. case mode&(syscall.O_CREAT|syscall.O_TRUNC) == (syscall.O_CREAT | syscall.O_TRUNC):
  57. createmode = syscall.CREATE_ALWAYS
  58. case mode&syscall.O_CREAT == syscall.O_CREAT:
  59. createmode = syscall.OPEN_ALWAYS
  60. case mode&syscall.O_TRUNC == syscall.O_TRUNC:
  61. createmode = syscall.TRUNCATE_EXISTING
  62. default:
  63. createmode = syscall.OPEN_EXISTING
  64. }
  65. h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0)
  66. return h, e
  67. }
  68. func makeInheritSa() *syscall.SecurityAttributes {
  69. var sa syscall.SecurityAttributes
  70. sa.Length = uint32(unsafe.Sizeof(sa))
  71. sa.InheritHandle = 1
  72. return &sa
  73. }
  74. // fixLongPath returns the extended-length (\\?\-prefixed) form of
  75. // path when needed, in order to avoid the default 260 character file
  76. // path limit imposed by Windows. If path is not easily converted to
  77. // the extended-length form (for example, if path is a relative path
  78. // or contains .. elements), or is short enough, fixLongPath returns
  79. // path unmodified.
  80. //
  81. // See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
  82. //
  83. // Copied from os.OpenFile
  84. func fixLongPath(path string) string {
  85. // Do nothing (and don't allocate) if the path is "short".
  86. // Empirically (at least on the Windows Server 2013 builder),
  87. // the kernel is arbitrarily okay with < 248 bytes. That
  88. // matches what the docs above say:
  89. // "When using an API to create a directory, the specified
  90. // path cannot be so long that you cannot append an 8.3 file
  91. // name (that is, the directory name cannot exceed MAX_PATH
  92. // minus 12)." Since MAX_PATH is 260, 260 - 12 = 248.
  93. //
  94. // The MSDN docs appear to say that a normal path that is 248 bytes long
  95. // will work; empirically the path must be less then 248 bytes long.
  96. if len(path) < 248 {
  97. // Don't fix. (This is how Go 1.7 and earlier worked,
  98. // not automatically generating the \\?\ form)
  99. return path
  100. }
  101. // The extended form begins with \\?\, as in
  102. // \\?\c:\windows\foo.txt or \\?\UNC\server\share\foo.txt.
  103. // The extended form disables evaluation of . and .. path
  104. // elements and disables the interpretation of / as equivalent
  105. // to \. The conversion here rewrites / to \ and elides
  106. // . elements as well as trailing or duplicate separators. For
  107. // simplicity it avoids the conversion entirely for relative
  108. // paths or paths containing .. elements. For now,
  109. // \\server\share paths are not converted to
  110. // \\?\UNC\server\share paths because the rules for doing so
  111. // are less well-specified.
  112. if len(path) >= 2 && path[:2] == `\\` {
  113. // Don't canonicalize UNC paths.
  114. return path
  115. }
  116. if !isAbs(path) {
  117. // Relative path
  118. return path
  119. }
  120. const prefix = `\\?`
  121. pathbuf := make([]byte, len(prefix)+len(path)+len(`\`))
  122. copy(pathbuf, prefix)
  123. n := len(path)
  124. r, w := 0, len(prefix)
  125. for r < n {
  126. switch {
  127. case os.IsPathSeparator(path[r]):
  128. // empty block
  129. r++
  130. case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])):
  131. // /./
  132. r++
  133. case r+1 < n && path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])):
  134. // /../ is currently unhandled
  135. return path
  136. default:
  137. pathbuf[w] = '\\'
  138. w++
  139. for ; r < n && !os.IsPathSeparator(path[r]); r++ {
  140. pathbuf[w] = path[r]
  141. w++
  142. }
  143. }
  144. }
  145. // A drive's root directory needs a trailing \
  146. if w == len(`\\?\c:`) {
  147. pathbuf[w] = '\\'
  148. w++
  149. }
  150. return string(pathbuf[:w])
  151. }
  152. // copied from os package for os.OpenFile
  153. func syscallMode(i os.FileMode) (o uint32) {
  154. o |= uint32(i.Perm())
  155. if i&os.ModeSetuid != 0 {
  156. o |= syscall.S_ISUID
  157. }
  158. if i&os.ModeSetgid != 0 {
  159. o |= syscall.S_ISGID
  160. }
  161. if i&os.ModeSticky != 0 {
  162. o |= syscall.S_ISVTX
  163. }
  164. // No mapping for Go's ModeTemporary (plan9 only).
  165. return
  166. }
  167. func isAbs(path string) (b bool) {
  168. v := volumeName(path)
  169. if v == "" {
  170. return false
  171. }
  172. path = path[len(v):]
  173. if path == "" {
  174. return false
  175. }
  176. return os.IsPathSeparator(path[0])
  177. }
  178. func volumeName(path string) (v string) {
  179. if len(path) < 2 {
  180. return ""
  181. }
  182. // with drive letter
  183. c := path[0]
  184. if path[1] == ':' &&
  185. ('0' <= c && c <= '9' || 'a' <= c && c <= 'z' ||
  186. 'A' <= c && c <= 'Z') {
  187. return path[:2]
  188. }
  189. // is it UNC
  190. if l := len(path); l >= 5 && os.IsPathSeparator(path[0]) && os.IsPathSeparator(path[1]) &&
  191. !os.IsPathSeparator(path[2]) && path[2] != '.' {
  192. // first, leading `\\` and next shouldn't be `\`. its server name.
  193. for n := 3; n < l-1; n++ {
  194. // second, next '\' shouldn't be repeated.
  195. if os.IsPathSeparator(path[n]) {
  196. n++
  197. // third, following something characters. its share name.
  198. if !os.IsPathSeparator(path[n]) {
  199. if path[n] == '.' {
  200. break
  201. }
  202. for ; n < l; n++ {
  203. if os.IsPathSeparator(path[n]) {
  204. break
  205. }
  206. }
  207. return path[:n]
  208. }
  209. break
  210. }
  211. }
  212. }
  213. return ""
  214. }
  215. func unlink(name string) error {
  216. // Rename the file before deleting it so that the original name is freed
  217. // up to be reused, even while there are still open FILE_SHARE_DELETE
  218. // file handles. Emulate POSIX unlink() semantics, essentially.
  219. name, err := filepath.Abs(name)
  220. if err != nil {
  221. return err
  222. }
  223. dir, fname := filepath.Split(name)
  224. f, err := os.CreateTemp(dir, fname+".*.deleted")
  225. if err != nil {
  226. return err
  227. }
  228. tmpname := f.Name()
  229. if err := f.Close(); err != nil {
  230. return err
  231. }
  232. err = os.Rename(name, tmpname)
  233. rmErr := os.Remove(tmpname)
  234. if err != nil {
  235. return err
  236. }
  237. return rmErr
  238. }