40 lines
1.2 KiB
Go
40 lines
1.2 KiB
Go
package host
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"syscall"
|
|
)
|
|
|
|
// OpenFileSharedRead opens a file for reading without blocking Windows log rotation.
|
|
func OpenFileSharedRead(path string) (*os.File, error) {
|
|
extendedPath := toExtendedLengthPath(path)
|
|
name, err := syscall.UTF16PtrFromString(extendedPath)
|
|
if err != nil {
|
|
return nil, &os.PathError{Op: "open", Path: path, Err: err}
|
|
}
|
|
handle, err := syscall.CreateFile(name, syscall.GENERIC_READ,
|
|
syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
|
|
nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
|
|
if err != nil {
|
|
return nil, &os.PathError{Op: "open", Path: path, Err: err}
|
|
}
|
|
return os.NewFile(uintptr(handle), path), nil
|
|
}
|
|
|
|
func toExtendedLengthPath(path string) string {
|
|
if len(path) < 248 || !filepath.IsAbs(path) {
|
|
return path
|
|
}
|
|
normalized := strings.ReplaceAll(path, "/", `\`)
|
|
if strings.HasPrefix(normalized, `\\?\`) || strings.HasPrefix(normalized, `\??\`) || strings.HasPrefix(normalized, `\\.\`) {
|
|
return path
|
|
}
|
|
normalized = filepath.Clean(normalized)
|
|
if strings.HasPrefix(normalized, `\\`) {
|
|
return `\\?\UNC\` + normalized[2:]
|
|
}
|
|
return `\\?\` + normalized
|
|
}
|