| 1 | package clipboardfiles |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/sylvinus/agent-vm/internal/host" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | type CachedSelection struct { |
| 19 | ID string `json:"cache_id"` |
| 20 | Paths []string `json:"paths"` |
| 21 | } |
| 22 | |
| 23 | type cacheRecord struct { |
| 24 | CachedSelection |
| 25 | Directory string `json:"directory"` |
| 26 | Marker string `json:"marker"` |
| 27 | Owner int `json:"owner"` |
| 28 | Published bool `json:"published"` |
| 29 | Pending bool `json:"pending,omitempty"` |
| 30 | Producer int `json:"producer,omitempty"` |
| 31 | } |
| 32 | |
| 33 | type CacheStore struct{ Directory string } |
| 34 | |
| 35 | type CacheRequest struct { |
| 36 | Action string `json:"action"` |
| 37 | ID string `json:"cache_id,omitempty"` |
| 38 | } |
| 39 | |
| 40 | func (store CacheStore) lock() (func(), error) { |
| 41 | if err := host.EnsurePrivateDir(store.Directory); err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | file, err := os.OpenFile(filepath.Join(store.Directory, ".lock"), os.O_CREATE|os.O_RDWR, 0600) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | unlock, err := lockCacheStore(file) |
| 49 | if err != nil { |
| 50 | file.Close() |
| 51 | return nil, err |
| 52 | } |
| 53 | return func() { unlock(); file.Close() }, nil |
| 54 | } |
| 55 | |
| 56 | func (store CacheStore) Control(request CacheRequest) (map[string]any, error) { |
| 57 | if request.Action == "list" { |
| 58 | selections, err := store.List() |
| 59 | return map[string]any{"selections": selections}, err |
| 60 | } |
| 61 | var err error |
| 62 | switch request.Action { |
| 63 | case "publish": |
| 64 | err = store.Publish(request.ID) |
| 65 | case "release": |
| 66 | err = store.Release(request.ID) |
| 67 | default: |
| 68 | err = errors.New("invalid clipboard cache operation") |
| 69 | } |
| 70 | return map[string]any{"ok": err == nil}, err |
| 71 | } |
| 72 | |
| 73 | func (store CacheStore) recordPath(id string) (string, error) { |
| 74 | if decoded, err := hex.DecodeString(id); err != nil || len(decoded) != 16 { |
| 75 | return "", errors.New("invalid clipboard cache identity") |
| 76 | } |
| 77 | return filepath.Join(store.Directory, id+".json"), nil |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | func (store CacheStore) Register(paths []string) (CachedSelection, error) { |
| 83 | return store.register(paths, false) |
| 84 | } |
| 85 | |
| 86 | func (store CacheStore) register(paths []string, pending bool) (CachedSelection, error) { |
| 87 | var empty CachedSelection |
| 88 | if len(paths) == 0 || len(paths) > SelectionLimit { |
| 89 | return empty, errors.New("invalid clipboard cache selection") |
| 90 | } |
| 91 | directory := filepath.Dir(paths[0]) |
| 92 | for _, path := range paths { |
| 93 | if !filepath.IsAbs(path) || filepath.Clean(path) != path || filepath.Dir(path) != directory { |
| 94 | return empty, errors.New("invalid clipboard cache directory") |
| 95 | } |
| 96 | } |
| 97 | unlock, err := store.lock() |
| 98 | if err != nil { |
| 99 | return empty, err |
| 100 | } |
| 101 | defer unlock() |
| 102 | var token [16]byte |
| 103 | if _, err := rand.Read(token[:]); err != nil { |
| 104 | return empty, err |
| 105 | } |
| 106 | selection := CachedSelection{ID: hex.EncodeToString(token[:]), Paths: append([]string(nil), paths...)} |
| 107 | marker, err := os.CreateTemp(directory, ".cage-clipboard-owner-") |
| 108 | if err != nil { |
| 109 | return empty, err |
| 110 | } |
| 111 | _, writeErr := marker.WriteString(selection.ID) |
| 112 | err = errors.Join(writeErr, marker.Close()) |
| 113 | if err != nil { |
| 114 | _ = os.Remove(marker.Name()) |
| 115 | return empty, err |
| 116 | } |
| 117 | record := cacheRecord{CachedSelection: selection, Directory: directory, Marker: filepath.Base(marker.Name()), Owner: os.Getppid(), Pending: pending, Producer: os.Getpid()} |
| 118 | if err := store.save(record); err != nil { |
| 119 | _ = os.Remove(marker.Name()) |
| 120 | return empty, err |
| 121 | } |
| 122 | return selection, nil |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | func (store CacheStore) create(operation func(func() (string, error)) ([]string, error)) (result CachedSelection, err error) { |
| 128 | var created CachedSelection |
| 129 | defer func() { |
| 130 | if err != nil && created.ID != "" { |
| 131 | _ = store.Release(created.ID) |
| 132 | } |
| 133 | }() |
| 134 | paths, err := operation(func() (string, error) { |
| 135 | root, err := temporaryDirectory() |
| 136 | if err != nil { |
| 137 | return "", err |
| 138 | } |
| 139 | created, err = store.register([]string{filepath.Join(root, ".pending")}, true) |
| 140 | if err != nil { |
| 141 | _ = os.RemoveAll(root) |
| 142 | } |
| 143 | return root, err |
| 144 | }) |
| 145 | if err != nil { |
| 146 | return result, err |
| 147 | } |
| 148 | unlock, err := store.lock() |
| 149 | if err != nil { |
| 150 | return result, err |
| 151 | } |
| 152 | defer unlock() |
| 153 | record, err := store.load(created.ID) |
| 154 | if err != nil { |
| 155 | return result, err |
| 156 | } |
| 157 | record.Paths = paths |
| 158 | record.Pending = false |
| 159 | if err := store.save(record); err != nil { |
| 160 | return result, err |
| 161 | } |
| 162 | return record.CachedSelection, nil |
| 163 | } |
| 164 | |
| 165 | func (store CacheStore) Read(input io.Reader) (CachedSelection, error) { |
| 166 | return store.create(func(directory func() (string, error)) ([]string, error) { return read(input, directory) }) |
| 167 | } |
| 168 | |
| 169 | func (store CacheStore) Copy(paths []string) (CachedSelection, error) { |
| 170 | return store.create(func(directory func() (string, error)) ([]string, error) { return copyFiles(paths, directory) }) |
| 171 | } |
| 172 | |
| 173 | func (store CacheStore) Save(input io.Reader, name string) (CachedSelection, error) { |
| 174 | return store.create(func(directory func() (string, error)) ([]string, error) { |
| 175 | path, err := save(input, name, directory) |
| 176 | return []string{path}, err |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | func (store CacheStore) LinkCachedFiles(paths []string) (CachedSelection, error) { |
| 181 | return store.create(func(directory func() (string, error)) ([]string, error) { return linkCachedFiles(paths, directory) }) |
| 182 | } |
| 183 | |
| 184 | func (store CacheStore) save(record cacheRecord) error { |
| 185 | path, err := store.recordPath(record.ID) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | file, err := os.CreateTemp(store.Directory, ".clipboard-record-") |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | defer os.Remove(file.Name()) |
| 194 | if err := json.NewEncoder(file).Encode(record); err != nil { |
| 195 | _ = file.Close() |
| 196 | return err |
| 197 | } |
| 198 | if err := file.Close(); err != nil { |
| 199 | return err |
| 200 | } |
| 201 | return os.Rename(file.Name(), path) |
| 202 | } |
| 203 | |
| 204 | func (store CacheStore) load(id string) (cacheRecord, error) { |
| 205 | var record cacheRecord |
| 206 | path, err := store.recordPath(id) |
| 207 | if err != nil { |
| 208 | return record, err |
| 209 | } |
| 210 | data, err := os.ReadFile(path) |
| 211 | if err != nil { |
| 212 | return record, err |
| 213 | } |
| 214 | if json.Unmarshal(data, &record) != nil || record.ID != id || len(record.Paths) == 0 || |
| 215 | !filepath.IsAbs(record.Directory) || filepath.Clean(record.Directory) != record.Directory || |
| 216 | !validName(record.Marker) || record.Owner < 1 || record.Pending && record.Producer < 1 { |
| 217 | return record, errors.New("invalid clipboard cache record") |
| 218 | } |
| 219 | for _, path := range record.Paths { |
| 220 | if filepath.Dir(path) != record.Directory || filepath.Clean(path) != path { |
| 221 | return record, errors.New("invalid clipboard cache paths") |
| 222 | } |
| 223 | } |
| 224 | return record, nil |
| 225 | } |
| 226 | |
| 227 | func (store CacheStore) Publish(id string) error { |
| 228 | unlock, err := store.lock() |
| 229 | if err != nil { |
| 230 | return err |
| 231 | } |
| 232 | defer unlock() |
| 233 | record, err := store.load(id) |
| 234 | if err != nil { |
| 235 | return err |
| 236 | } |
| 237 | record.Published = true |
| 238 | return store.save(record) |
| 239 | } |
| 240 | |
| 241 | |
| 242 | |
| 243 | func (store CacheStore) List() ([]CachedSelection, error) { |
| 244 | unlock, err := store.lock() |
| 245 | if err != nil { |
| 246 | return nil, err |
| 247 | } |
| 248 | defer unlock() |
| 249 | entries, err := os.ReadDir(store.Directory) |
| 250 | if errors.Is(err, os.ErrNotExist) { |
| 251 | return []CachedSelection{}, nil |
| 252 | } |
| 253 | if err != nil { |
| 254 | return nil, err |
| 255 | } |
| 256 | selections := []CachedSelection{} |
| 257 | for _, entry := range entries { |
| 258 | if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") { |
| 259 | continue |
| 260 | } |
| 261 | record, err := store.load(strings.TrimSuffix(entry.Name(), ".json")) |
| 262 | if err != nil { |
| 263 | return nil, err |
| 264 | } |
| 265 | if record.Pending && !cacheOwnerAlive(record.Producer) || !record.Pending && |
| 266 | (record.Published && record.Owner == os.Getppid() || !cacheOwnerAlive(record.Owner)) { |
| 267 | selections = append(selections, record.CachedSelection) |
| 268 | } |
| 269 | } |
| 270 | return selections, nil |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | func (store CacheStore) Release(id string) error { |
| 276 | unlock, err := store.lock() |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | defer unlock() |
| 281 | record, err := store.load(id) |
| 282 | if errors.Is(err, os.ErrNotExist) { |
| 283 | return nil |
| 284 | } |
| 285 | if err != nil { |
| 286 | return err |
| 287 | } |
| 288 | path, _ := store.recordPath(id) |
| 289 | root, err := os.OpenRoot(record.Directory) |
| 290 | if errors.Is(err, os.ErrNotExist) { |
| 291 | return os.Remove(path) |
| 292 | } |
| 293 | if err != nil { |
| 294 | return err |
| 295 | } |
| 296 | defer root.Close() |
| 297 | marker, err := root.ReadFile(record.Marker) |
| 298 | if err != nil || string(marker) != id { |
| 299 | return errors.New("clipboard cache creation record no longer matches") |
| 300 | } |
| 301 | directory, err := root.Open(".") |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | entries, readErr := directory.ReadDir(-1) |
| 306 | err = errors.Join(readErr, directory.Close()) |
| 307 | if err != nil { |
| 308 | return err |
| 309 | } |
| 310 | for _, entry := range entries { |
| 311 | if entry.Name() != record.Marker { |
| 312 | if err := root.RemoveAll(entry.Name()); err != nil { |
| 313 | return err |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | if err := removeCacheDirectory(root, record); err != nil { |
| 318 | return err |
| 319 | } |
| 320 | return os.Remove(path) |
| 321 | } |
| 322 | |
| 323 | func UserCacheStore() (CacheStore, error) { |
| 324 | directory, err := os.UserCacheDir() |
| 325 | return CacheStore{Directory: filepath.Join(directory, "cage", "clipboard-ownership")}, err |
| 326 | } |