| 1 | package clipboardfiles |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | |
| 8 | "golang.org/x/sys/windows" |
| 9 | ) |
| 10 | |
| 11 | func removeCacheDirectory(root *os.Root, record cacheRecord) error { |
| 12 | identity, err := root.Stat(".") |
| 13 | if err != nil { |
| 14 | return err |
| 15 | } |
| 16 | |
| 17 | |
| 18 | if err := root.Close(); err != nil { |
| 19 | return err |
| 20 | } |
| 21 | path, err := windows.UTF16PtrFromString(record.Directory) |
| 22 | if err != nil { |
| 23 | return err |
| 24 | } |
| 25 | handle, err := windows.CreateFile(path, windows.DELETE|windows.FILE_READ_ATTRIBUTES, |
| 26 | windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, |
| 27 | windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) |
| 28 | if err != nil { |
| 29 | return err |
| 30 | } |
| 31 | file := os.NewFile(uintptr(handle), record.Directory) |
| 32 | defer file.Close() |
| 33 | current, err := file.Stat() |
| 34 | if err != nil || !current.IsDir() || current.Mode()&os.ModeSymlink != 0 || !os.SameFile(identity, current) { |
| 35 | return errors.New("clipboard cache directory identity changed") |
| 36 | } |
| 37 | marker := filepath.Join(record.Directory, record.Marker) |
| 38 | contents, err := os.ReadFile(marker) |
| 39 | if err != nil || string(contents) != record.ID { |
| 40 | return errors.New("clipboard cache creation record no longer matches") |
| 41 | } |
| 42 | if err := os.Remove(marker); err != nil { |
| 43 | return err |
| 44 | } |
| 45 | discard := byte(1) |
| 46 | if err := windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1); err != nil { |
| 47 | return errors.Join(err, os.WriteFile(marker, []byte(record.ID), 0600)) |
| 48 | } |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | func lockCacheStore(file *os.File) (func(), error) { |
| 53 | var overlapped windows.Overlapped |
| 54 | if err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &overlapped); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | return func() { _ = windows.UnlockFileEx(windows.Handle(file.Fd()), 0, 1, 0, &overlapped) }, nil |
| 58 | } |
| 59 | |
| 60 | func cacheOwnerAlive(pid int) bool { |
| 61 | handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) |
| 62 | if err != nil { |
| 63 | return err == windows.ERROR_ACCESS_DENIED |
| 64 | } |
| 65 | defer windows.CloseHandle(handle) |
| 66 | status, err := windows.WaitForSingleObject(handle, 0) |
| 67 | return err != nil || status == uint32(windows.WAIT_TIMEOUT) |
| 68 | } |