1// Copyright 2009 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package os 6 7import ( 8 "errors" 9 "internal/filepathlite" 10 "internal/godebug" 11 "internal/poll" 12 "internal/syscall/windows" 13 "runtime" 14 "sync" 15 "sync/atomic" 16 "syscall" 17 "unsafe" 18) 19 20// This matches the value in syscall/syscall_windows.go. 21const _UTIME_OMIT = -1 22 23// file is the real representation of *File. 24// The extra level of indirection ensures that no clients of os 25// can overwrite this data, which could cause the finalizer 26// to close the wrong file descriptor. 27type file struct { 28 pfd poll.FD 29 name string 30 dirinfo atomic.Pointer[dirInfo] // nil unless directory being read 31 appendMode bool // whether file is opened for appending 32} 33 34// Fd returns the Windows handle referencing the open file. 35// If f is closed, the file descriptor becomes invalid. 36// If f is garbage collected, a finalizer may close the file descriptor, 37// making it invalid; see [runtime.SetFinalizer] for more information on when 38// a finalizer might be run. On Unix systems this will cause the [File.SetDeadline] 39// methods to stop working. 40func (file *File) Fd() uintptr { 41 if file == nil { 42 return uintptr(syscall.InvalidHandle) 43 } 44 return uintptr(file.pfd.Sysfd) 45} 46 47// newFile returns a new File with the given file handle and name. 48// Unlike NewFile, it does not check that h is syscall.InvalidHandle. 49func newFile(h syscall.Handle, name string, kind string) *File { 50 if kind == "file" { 51 var m uint32 52 if syscall.GetConsoleMode(h, &m) == nil { 53 kind = "console" 54 } 55 if t, err := syscall.GetFileType(h); err == nil && t == syscall.FILE_TYPE_PIPE { 56 kind = "pipe" 57 } 58 } 59 60 f := &File{&file{ 61 pfd: poll.FD{ 62 Sysfd: h, 63 IsStream: true, 64 ZeroReadIsEOF: true, 65 }, 66 name: name, 67 }} 68 runtime.SetFinalizer(f.file, (*file).close) 69 70 // Ignore initialization errors. 71 // Assume any problems will show up in later I/O. 72 f.pfd.Init(kind, false) 73 74 return f 75} 76 77// newConsoleFile creates new File that will be used as console. 78func newConsoleFile(h syscall.Handle, name string) *File { 79 return newFile(h, name, "console") 80} 81 82// NewFile returns a new File with the given file descriptor and 83// name. The returned value will be nil if fd is not a valid file 84// descriptor. 85func NewFile(fd uintptr, name string) *File { 86 h := syscall.Handle(fd) 87 if h == syscall.InvalidHandle { 88 return nil 89 } 90 return newFile(h, name, "file") 91} 92 93func epipecheck(file *File, e error) { 94} 95 96// DevNull is the name of the operating system's “null device.” 97// On Unix-like systems, it is "/dev/null"; on Windows, "NUL". 98const DevNull = "NUL" 99 100// openFileNolog is the Windows implementation of OpenFile. 101func openFileNolog(name string, flag int, perm FileMode) (*File, error) { 102 if name == "" { 103 return nil, &PathError{Op: "open", Path: name, Err: syscall.ENOENT} 104 } 105 path := fixLongPath(name) 106 r, e := syscall.Open(path, flag|syscall.O_CLOEXEC, syscallMode(perm)) 107 if e != nil { 108 // We should return EISDIR when we are trying to open a directory with write access. 109 if e == syscall.ERROR_ACCESS_DENIED && (flag&O_WRONLY != 0 || flag&O_RDWR != 0) { 110 pathp, e1 := syscall.UTF16PtrFromString(path) 111 if e1 == nil { 112 var fa syscall.Win32FileAttributeData 113 e1 = syscall.GetFileAttributesEx(pathp, syscall.GetFileExInfoStandard, (*byte)(unsafe.Pointer(&fa))) 114 if e1 == nil && fa.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { 115 e = syscall.EISDIR 116 } 117 } 118 } 119 return nil, &PathError{Op: "open", Path: name, Err: e} 120 } 121 return newFile(r, name, "file"), nil 122} 123 124func openDirNolog(name string) (*File, error) { 125 return openFileNolog(name, O_RDONLY, 0) 126} 127 128func (file *file) close() error { 129 if file == nil { 130 return syscall.EINVAL 131 } 132 if info := file.dirinfo.Swap(nil); info != nil { 133 info.close() 134 } 135 var err error 136 if e := file.pfd.Close(); e != nil { 137 if e == poll.ErrFileClosing { 138 e = ErrClosed 139 } 140 err = &PathError{Op: "close", Path: file.name, Err: e} 141 } 142 143 // no need for a finalizer anymore 144 runtime.SetFinalizer(file, nil) 145 return err 146} 147 148// seek sets the offset for the next Read or Write on file to offset, interpreted 149// according to whence: 0 means relative to the origin of the file, 1 means 150// relative to the current offset, and 2 means relative to the end. 151// It returns the new offset and an error, if any. 152func (f *File) seek(offset int64, whence int) (ret int64, err error) { 153 if info := f.dirinfo.Swap(nil); info != nil { 154 // Free cached dirinfo, so we allocate a new one if we 155 // access this file as a directory again. See #35767 and #37161. 156 info.close() 157 } 158 ret, err = f.pfd.Seek(offset, whence) 159 runtime.KeepAlive(f) 160 return ret, err 161} 162 163// Truncate changes the size of the named file. 164// If the file is a symbolic link, it changes the size of the link's target. 165func Truncate(name string, size int64) error { 166 f, e := OpenFile(name, O_WRONLY, 0666) 167 if e != nil { 168 return e 169 } 170 defer f.Close() 171 e1 := f.Truncate(size) 172 if e1 != nil { 173 return e1 174 } 175 return nil 176} 177 178// Remove removes the named file or directory. 179// If there is an error, it will be of type *PathError. 180func Remove(name string) error { 181 p, e := syscall.UTF16PtrFromString(fixLongPath(name)) 182 if e != nil { 183 return &PathError{Op: "remove", Path: name, Err: e} 184 } 185 186 // Go file interface forces us to know whether 187 // name is a file or directory. Try both. 188 e = syscall.DeleteFile(p) 189 if e == nil { 190 return nil 191 } 192 e1 := syscall.RemoveDirectory(p) 193 if e1 == nil { 194 return nil 195 } 196 197 // Both failed: figure out which error to return. 198 if e1 != e { 199 a, e2 := syscall.GetFileAttributes(p) 200 if e2 != nil { 201 e = e2 202 } else { 203 if a&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { 204 e = e1 205 } else if a&syscall.FILE_ATTRIBUTE_READONLY != 0 { 206 if e1 = syscall.SetFileAttributes(p, a&^syscall.FILE_ATTRIBUTE_READONLY); e1 == nil { 207 if e = syscall.DeleteFile(p); e == nil { 208 return nil 209 } 210 } 211 } 212 } 213 } 214 return &PathError{Op: "remove", Path: name, Err: e} 215} 216 217func rename(oldname, newname string) error { 218 e := windows.Rename(fixLongPath(oldname), fixLongPath(newname)) 219 if e != nil { 220 return &LinkError{"rename", oldname, newname, e} 221 } 222 return nil 223} 224 225// Pipe returns a connected pair of Files; reads from r return bytes written to w. 226// It returns the files and an error, if any. The Windows handles underlying 227// the returned files are marked as inheritable by child processes. 228func Pipe() (r *File, w *File, err error) { 229 var p [2]syscall.Handle 230 e := syscall.Pipe(p[:]) 231 if e != nil { 232 return nil, nil, NewSyscallError("pipe", e) 233 } 234 return newFile(p[0], "|0", "pipe"), newFile(p[1], "|1", "pipe"), nil 235} 236 237var ( 238 useGetTempPath2Once sync.Once 239 useGetTempPath2 bool 240) 241 242func tempDir() string { 243 useGetTempPath2Once.Do(func() { 244 useGetTempPath2 = (windows.ErrorLoadingGetTempPath2() == nil) 245 }) 246 getTempPath := syscall.GetTempPath 247 if useGetTempPath2 { 248 getTempPath = windows.GetTempPath2 249 } 250 n := uint32(syscall.MAX_PATH) 251 for { 252 b := make([]uint16, n) 253 n, _ = getTempPath(uint32(len(b)), &b[0]) 254 if n > uint32(len(b)) { 255 continue 256 } 257 if n == 3 && b[1] == ':' && b[2] == '\\' { 258 // Do nothing for path, like C:\. 259 } else if n > 0 && b[n-1] == '\\' { 260 // Otherwise remove terminating \. 261 n-- 262 } 263 return syscall.UTF16ToString(b[:n]) 264 } 265} 266 267// Link creates newname as a hard link to the oldname file. 268// If there is an error, it will be of type *LinkError. 269func Link(oldname, newname string) error { 270 n, err := syscall.UTF16PtrFromString(fixLongPath(newname)) 271 if err != nil { 272 return &LinkError{"link", oldname, newname, err} 273 } 274 o, err := syscall.UTF16PtrFromString(fixLongPath(oldname)) 275 if err != nil { 276 return &LinkError{"link", oldname, newname, err} 277 } 278 err = syscall.CreateHardLink(n, o, 0) 279 if err != nil { 280 return &LinkError{"link", oldname, newname, err} 281 } 282 return nil 283} 284 285// Symlink creates newname as a symbolic link to oldname. 286// On Windows, a symlink to a non-existent oldname creates a file symlink; 287// if oldname is later created as a directory the symlink will not work. 288// If there is an error, it will be of type *LinkError. 289func Symlink(oldname, newname string) error { 290 // '/' does not work in link's content 291 oldname = filepathlite.FromSlash(oldname) 292 293 // need the exact location of the oldname when it's relative to determine if it's a directory 294 destpath := oldname 295 if v := filepathlite.VolumeName(oldname); v == "" { 296 if len(oldname) > 0 && IsPathSeparator(oldname[0]) { 297 // oldname is relative to the volume containing newname. 298 if v = filepathlite.VolumeName(newname); v != "" { 299 // Prepend the volume explicitly, because it may be different from the 300 // volume of the current working directory. 301 destpath = v + oldname 302 } 303 } else { 304 // oldname is relative to newname. 305 destpath = dirname(newname) + `\` + oldname 306 } 307 } 308 309 fi, err := Stat(destpath) 310 isdir := err == nil && fi.IsDir() 311 312 n, err := syscall.UTF16PtrFromString(fixLongPath(newname)) 313 if err != nil { 314 return &LinkError{"symlink", oldname, newname, err} 315 } 316 var o *uint16 317 if filepathlite.IsAbs(oldname) { 318 o, err = syscall.UTF16PtrFromString(fixLongPath(oldname)) 319 } else { 320 // Do not use fixLongPath on oldname for relative symlinks, 321 // as it would turn the name into an absolute path thus making 322 // an absolute symlink instead. 323 // Notice that CreateSymbolicLinkW does not fail for relative 324 // symlinks beyond MAX_PATH, so this does not prevent the 325 // creation of an arbitrary long path name. 326 o, err = syscall.UTF16PtrFromString(oldname) 327 } 328 if err != nil { 329 return &LinkError{"symlink", oldname, newname, err} 330 } 331 332 var flags uint32 = windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 333 if isdir { 334 flags |= syscall.SYMBOLIC_LINK_FLAG_DIRECTORY 335 } 336 err = syscall.CreateSymbolicLink(n, o, flags) 337 if err != nil { 338 // the unprivileged create flag is unsupported 339 // below Windows 10 (1703, v10.0.14972). retry without it. 340 flags &^= windows.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 341 err = syscall.CreateSymbolicLink(n, o, flags) 342 if err != nil { 343 return &LinkError{"symlink", oldname, newname, err} 344 } 345 } 346 return nil 347} 348 349// openSymlink calls CreateFile Windows API with FILE_FLAG_OPEN_REPARSE_POINT 350// parameter, so that Windows does not follow symlink, if path is a symlink. 351// openSymlink returns opened file handle. 352func openSymlink(path string) (syscall.Handle, error) { 353 p, err := syscall.UTF16PtrFromString(path) 354 if err != nil { 355 return 0, err 356 } 357 attrs := uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS) 358 // Use FILE_FLAG_OPEN_REPARSE_POINT, otherwise CreateFile will follow symlink. 359 // See https://docs.microsoft.com/en-us/windows/desktop/FileIO/symbolic-link-effects-on-file-systems-functions#createfile-and-createfiletransacted 360 attrs |= syscall.FILE_FLAG_OPEN_REPARSE_POINT 361 h, err := syscall.CreateFile(p, 0, 0, nil, syscall.OPEN_EXISTING, attrs, 0) 362 if err != nil { 363 return 0, err 364 } 365 return h, nil 366} 367 368var winreadlinkvolume = godebug.New("winreadlinkvolume") 369 370// normaliseLinkPath converts absolute paths returned by 371// DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, ...) 372// into paths acceptable by all Windows APIs. 373// For example, it converts 374// 375// \??\C:\foo\bar into C:\foo\bar 376// \??\UNC\foo\bar into \\foo\bar 377// \??\Volume{abc}\ into \\?\Volume{abc}\ 378func normaliseLinkPath(path string) (string, error) { 379 if len(path) < 4 || path[:4] != `\??\` { 380 // unexpected path, return it as is 381 return path, nil 382 } 383 // we have path that start with \??\ 384 s := path[4:] 385 switch { 386 case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar 387 return s, nil 388 case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar 389 return `\\` + s[4:], nil 390 } 391 392 // \??\Volume{abc}\ 393 if winreadlinkvolume.Value() != "0" { 394 return `\\?\` + path[4:], nil 395 } 396 winreadlinkvolume.IncNonDefault() 397 398 h, err := openSymlink(path) 399 if err != nil { 400 return "", err 401 } 402 defer syscall.CloseHandle(h) 403 404 buf := make([]uint16, 100) 405 for { 406 n, err := windows.GetFinalPathNameByHandle(h, &buf[0], uint32(len(buf)), windows.VOLUME_NAME_DOS) 407 if err != nil { 408 return "", err 409 } 410 if n < uint32(len(buf)) { 411 break 412 } 413 buf = make([]uint16, n) 414 } 415 s = syscall.UTF16ToString(buf) 416 if len(s) > 4 && s[:4] == `\\?\` { 417 s = s[4:] 418 if len(s) > 3 && s[:3] == `UNC` { 419 // return path like \\server\share\... 420 return `\` + s[3:], nil 421 } 422 return s, nil 423 } 424 return "", errors.New("GetFinalPathNameByHandle returned unexpected path: " + s) 425} 426 427func readReparseLink(path string) (string, error) { 428 h, err := openSymlink(path) 429 if err != nil { 430 return "", err 431 } 432 defer syscall.CloseHandle(h) 433 434 rdbbuf := make([]byte, syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE) 435 var bytesReturned uint32 436 err = syscall.DeviceIoControl(h, syscall.FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) 437 if err != nil { 438 return "", err 439 } 440 441 rdb := (*windows.REPARSE_DATA_BUFFER)(unsafe.Pointer(&rdbbuf[0])) 442 switch rdb.ReparseTag { 443 case syscall.IO_REPARSE_TAG_SYMLINK: 444 rb := (*windows.SymbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.DUMMYUNIONNAME)) 445 s := rb.Path() 446 if rb.Flags&windows.SYMLINK_FLAG_RELATIVE != 0 { 447 return s, nil 448 } 449 return normaliseLinkPath(s) 450 case windows.IO_REPARSE_TAG_MOUNT_POINT: 451 return normaliseLinkPath((*windows.MountPointReparseBuffer)(unsafe.Pointer(&rdb.DUMMYUNIONNAME)).Path()) 452 default: 453 // the path is not a symlink or junction but another type of reparse 454 // point 455 return "", syscall.ENOENT 456 } 457} 458 459func readlink(name string) (string, error) { 460 s, err := readReparseLink(fixLongPath(name)) 461 if err != nil { 462 return "", &PathError{Op: "readlink", Path: name, Err: err} 463 } 464 return s, nil 465} 466