pkgar 0.2.2

Redox Package Archive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::collections::{BTreeMap, HashMap};
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{symlink, OpenOptionsExt};
use std::path::{Path, PathBuf};

use blake3::Hash;
use pkgar_core::{Entry, Mode, PackageSrc};

use crate::ext::{copy_and_hash, EntryExt, PackageSrcExt};
use crate::{wrap_io_err, Error, READ_WRITE_HASH_BUF_SIZE};

fn file_exists(path: impl AsRef<Path>) -> Result<bool, Error> {
    let path = path.as_ref();
    if let Err(err) = fs::symlink_metadata(path) {
        if err.kind() == io::ErrorKind::NotFound {
            Ok(false)
        } else {
            Err(Error::Io {
                source: err,
                path: Some(path.to_path_buf()),
                context: "Checking file",
            })
        }
    } else {
        Ok(true)
    }
}

/// Determine the temporary path for a file, and create its parent directories.
/// Returns `Err` if the target path has no parent (was `/`).
fn temp_path(target_path: impl AsRef<Path>, entry_hash: Hash) -> Result<PathBuf, Error> {
    let target_path = target_path.as_ref();
    let hash_path = format!(".pkgar.{}", entry_hash.to_hex());
    let parent_dir = target_path
        .parent()
        .ok_or_else(|| Error::InvalidPathComponent {
            invalid: PathBuf::from("/"),
            path: target_path.to_path_buf(),
            entry: None,
        })?;

    let tmp_name = if let Some(filename) = target_path.file_name() {
        let name_path = format!(".pkgar.{}", Path::new(filename).display());

        if file_exists(parent_dir.join(&name_path))? {
            hash_path
        } else {
            name_path
        }
    } else {
        // It's fine to not check the existence of this file, since if the a
        //   file with the same hash already exists, we know what its
        //   contents should be.
        hash_path
    };

    fs::create_dir_all(parent_dir)
        .map_err(wrap_io_err!(parent_dir.to_path_buf(), "Creating dir"))?;
    Ok(parent_dir.join(tmp_name))
}

/// Individual atomic file operation
#[derive(Clone, Debug)]
pub enum Action {
    /// Temp files (`.pkgar.*`) to target files
    Rename(PathBuf, PathBuf),
    Remove(PathBuf),
}

impl Action {
    fn commit(&self) -> Result<(), Error> {
        match self {
            Action::Rename(tmp, target) => {
                fs::rename(tmp, target).map_err(wrap_io_err!(tmp.to_path_buf(), "Renaming file"))
            }
            Action::Remove(target) => {
                fs::remove_file(target).map_err(wrap_io_err!(target.to_path_buf(), "Removing file"))
            }
        }
    }

    fn abort(&self) -> Result<(), Error> {
        match self {
            Action::Rename(tmp, _) => {
                fs::remove_file(tmp).map_err(wrap_io_err!(tmp.to_path_buf(), "Removing tempfile"))
            }
            Action::Remove(_) => Ok(()),
        }
    }

    /// Returns the file path it's targeting into
    pub fn target_file(&self) -> &Path {
        match self {
            Action::Rename(_, path) => path.as_path(),
            Action::Remove(path) => path.as_path(),
        }
    }
}

/// A struct that holds many atomic file operation
pub struct Transaction {
    actions: Vec<Action>,
    committed: usize,
}

impl Transaction {
    fn new(actions: Vec<Action>) -> Self {
        Self {
            actions,
            committed: 0,
        }
    }

    /// Prepare transactions to install from a pkgar file.
    /// Overwrites any existing file (customizable with `install_with_entries`).
    pub fn install<Pkg>(src: &mut Pkg, base_dir: impl AsRef<Path>) -> Result<Self, Error>
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        let entries = src.read_entries()?;
        Self::install_with_entries(src, entries, base_dir, true)
    }

    /// Prepare transactions to install from a pkgar file with filtered or modified entries
    pub fn install_with_entries<Pkg>(
        src: &mut Pkg,
        entries: Vec<Entry>,
        base_dir: impl AsRef<Path>,
        skip_local_check: bool,
    ) -> Result<Self, Error>
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        let mut buf = vec![0; READ_WRITE_HASH_BUF_SIZE];

        let mut actions = Vec::with_capacity(entries.len());

        for entry in &entries {
            let relative_path = entry.check_path()?;

            let target_path = base_dir.as_ref().join(relative_path);
            //HELP: Under what circumstances could this ever fail?
            assert!(
                target_path.starts_with(&base_dir),
                "target path was not in the base path"
            );

            let tmp_path = temp_path(&target_path, entry.blake3())?;

            let mode = entry.mode().map_err(Error::from)?;
            let mut data_reader = src.data_reader(&entry)?;

            let (entry_data_size, entry_data_hash) = match mode.kind() {
                Mode::FILE => {
                    // Tempfiles will be overwritten, users should use MergedTransaction to handle transaction conflicts
                    let mut tmp_file = fs::OpenOptions::new()
                        .write(true)
                        .create(true)
                        .truncate(true)
                        .mode(mode.perm().bits())
                        .open(&tmp_path)
                        .map_err(wrap_io_err!(tmp_path, "Opening tempfile"))?;

                    let (size, hash) = copy_and_hash(&mut data_reader, &mut tmp_file, &mut buf)
                        .map_err(wrap_io_err!(tmp_path, "Copying entry to tempfile"))?;

                    actions.push(Action::Rename(tmp_path, target_path));
                    (size, hash)
                }
                Mode::SYMLINK => {
                    let mut data = Vec::new();
                    let (size, hash) = copy_and_hash(&mut data_reader, &mut data, &mut buf)
                        .map_err(wrap_io_err!(tmp_path, "Copying entry to tempfile"))?;

                    let sym_target = Path::new(OsStr::from_bytes(&data));
                    let mut retried = false;
                    loop {
                        match symlink(sym_target, &tmp_path)
                            .map_err(wrap_io_err!(tmp_path, "Symlinking to tmp"))
                        {
                            Ok(_) => break,
                            Err(e) if retried => return Err(e),
                            Err(_) => {
                                // necessary because symlink can't overwrite
                                fs::remove_file(&tmp_path)
                                    .map_err(wrap_io_err!(tmp_path, "Unlinking old symlink tmp"))?;
                                retried = true
                            }
                        }
                    }
                    actions.push(Action::Rename(tmp_path, target_path));
                    (size, hash)
                }
                _ => {
                    return Err(Error::from(pkgar_core::Error::InvalidMode(mode.bits())));
                }
            };

            entry.verify(entry_data_hash, entry_data_size, &data_reader)?;
            data_reader.finish(src)?;
        }

        if !skip_local_check {
            // Do not overwrite locally modified install.
            let mut allowed_install_actions = Vec::with_capacity(actions.len());
            let mut buf = vec![0; READ_WRITE_HASH_BUF_SIZE];

            for (i, action) in actions.into_iter().enumerate() {
                let target_path = action.target_file();
                if !target_path.is_file() {
                    allowed_install_actions.push(action);
                    continue;
                }
                let mut candidate = File::open(&target_path)
                    .map_err(wrap_io_err!(target_path, "Opening candidate"))?;

                // Ensure that the deletion candidate on disk has not been modified
                let (_, entry_data_hash) = copy_and_hash(&mut candidate, &mut io::sink(), &mut buf)
                    .map_err(wrap_io_err!(target_path, "Hashing file for entry"))?;

                if entry_data_hash == entries[i].blake3() {
                    allowed_install_actions.push(action);
                } else {
                    action.abort()?;
                }
            }
            actions = allowed_install_actions;
        }

        Ok(Transaction::new(actions))
    }

    /// Prepare transactions to replace old files from a pkgar file.
    /// Does not overwrite existing file if the file is not updated between two package.
    /// Does not replace or remove existing file if the file is changed locally (customizable with `replace_with_entries`).
    pub fn replace<Pkg>(
        old: &mut Pkg,
        new: &mut Pkg,
        base_dir: impl AsRef<Path>,
    ) -> Result<Transaction, Error>
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        let old_entries = old.read_entries()?;
        let new_entries = new.read_entries()?;
        Self::replace_with_entries(old_entries, new_entries, new, base_dir, false)
    }

    /// Prepare transactions to replace old files from a pkgar file with filtered or modified entries
    pub fn replace_with_entries<Pkg>(
        old_entries: Vec<Entry>,
        new_entries: Vec<Entry>,
        new: &mut Pkg,
        base_dir: impl AsRef<Path>,
        skip_local_check: bool,
    ) -> Result<Transaction, Error>
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        let mut old_map = HashMap::with_capacity(old_entries.len());
        for entry in old_entries {
            old_map.insert(entry.check_path()?.to_path_buf(), entry);
        }

        let mut entries_to_install = Vec::new();

        for entry in new_entries {
            let path = entry.check_path()?;
            old_map.remove(path);

            match old_map.get(path) {
                Some(old_hash) if old_hash.blake3() == entry.blake3() => {
                    continue;
                }
                _ => {
                    entries_to_install.push(entry);
                }
            }
        }

        let mut entries_to_remove = Vec::new();
        for old_e in old_map.into_values() {
            entries_to_remove.push(old_e);
        }

        let mut trans = Self::install_with_entries(
            new,
            entries_to_install.clone(),
            &base_dir,
            skip_local_check,
        )?;
        let remove_trans =
            Self::remove_with_entries(entries_to_remove, &base_dir, skip_local_check)?;

        trans.actions.extend(remove_trans.actions);

        Ok(trans)
    }

    /// Prepare transactions to remove files from a pkgar file.
    /// Does not remove files with different hash (customizable with `remove_with_entries`)
    pub fn remove<Pkg>(src: &mut Pkg, base_dir: impl AsRef<Path>) -> Result<Self, Error>
    where
        Pkg: PackageSrc<Err = Error>,
    {
        let entries = src.read_entries()?;
        Self::remove_with_entries(entries, base_dir, false)
    }

    /// Prepare transactions to remove files from a pkgar file with filtered or modified entries
    pub fn remove_with_entries(
        entries: Vec<Entry>,
        base_dir: impl AsRef<Path>,
        skip_local_check: bool,
    ) -> Result<Self, Error> {
        let mut buf = vec![0; READ_WRITE_HASH_BUF_SIZE];

        let mut actions = Vec::with_capacity(entries.len());

        for entry in entries {
            let relative_path = entry.check_path()?;

            let target_path = base_dir.as_ref().join(relative_path);
            // Under what circumstances could this ever fail?
            assert!(
                target_path.starts_with(&base_dir),
                "target path was not in the base path"
            );

            let mut candidate = File::open(&target_path)
                .map_err(wrap_io_err!(target_path.clone(), "Opening candidate"))?;

            // Ensure that the deletion candidate on disk has not been modified
            let (_, entry_data_hash) = copy_and_hash(&mut candidate, &mut io::sink(), &mut buf)
                .map_err(wrap_io_err!(target_path.clone(), "Hashing file for entry"))?;

            if skip_local_check || entry_data_hash == entry.blake3() {
                actions.push(Action::Remove(target_path));
            }
        }
        Ok(Transaction::new(actions))
    }

    /// Apply all pending actions from end to start.
    /// This resets the committed counter back to zero.
    /// if failed abort() is needed to clean up pending transaction.
    pub fn commit(&mut self) -> Result<usize, Error> {
        self.reset_committed();
        while self.actions.len() > 0 {
            self.commit_one()?;
        }
        Ok(self.committed)
    }

    /// Apply one last item from actions stack,
    /// returns how many transactions committed since last counter reset.
    pub fn commit_one(&mut self) -> Result<usize, Error> {
        if let Some(action) = self.actions.pop() {
            if let Err(err) = action.commit() {
                // Should be possible to restart a failed transaction
                self.actions.push(action);
                return Err(Error::FailedCommit {
                    source: Box::new(err),
                    changed: self.committed,
                    remaining: self.actions.len(),
                });
            }
            self.committed += 1;
        }
        Ok(self.committed)
    }

    /// Clean up any tmp files referenced by this transaction without committing.
    /// Note that this function will check all actions and only after it has attempted
    /// to abort them all will it return an error with context info. Remaining actions
    /// are left as a part of this transaction to allow for re-runs of this function.
    pub fn abort(&mut self) -> Result<usize, Error> {
        let mut last_failed = false;
        self.reset_committed();
        while self.actions.len() > 0 {
            if let Err(err) = self.abort_one() {
                if last_failed {
                    return Err(err);
                } else {
                    last_failed = true;
                }
            }
        }
        Ok(self.committed)
    }

    /// Abort one last item from actions stack
    pub fn abort_one(&mut self) -> Result<usize, Error> {
        if let Some(action) = self.actions.pop() {
            if let Err(err) = action.abort() {
                // This is inherently inefficent, no biggie
                self.actions.insert(0, action);
                return Err(Error::FailedCommit {
                    source: Box::new(err),
                    changed: self.committed,
                    remaining: self.actions.len(),
                });
            }
            self.committed += 1;
        }
        Ok(self.committed)
    }

    /// Get how much actions are pending
    pub fn pending_commit(&self) -> usize {
        self.actions.len()
    }

    /// Get how much actions committed.
    /// Aborted actions also counts.
    pub fn total_committed(&self) -> usize {
        self.committed
    }

    /// Resets committed counter
    pub fn reset_committed(&mut self) {
        self.committed = 0;
    }

    /// Peek pending actions.
    /// Actions are executed from last item.
    pub fn get_actions(&self) -> &Vec<Action> {
        &self.actions
    }
}

/// A struct that helps merging multiple transaction into one.
/// All transactions are validated to make sure there's no two action holding the same target file.
pub struct MergedTransaction {
    actions: Vec<Action>,
    path_map: BTreeMap<PathBuf, Option<String>>,
    possible_conflicts: Vec<TransactionConflict>,
}

impl MergedTransaction {
    pub fn new() -> Self {
        MergedTransaction {
            actions: Vec::new(),
            path_map: BTreeMap::new(),
            possible_conflicts: Vec::new(),
        }
    }
    fn push_action<Pkg>(&mut self, action: Action, src: Option<&Pkg>)
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        let action_key = action.target_file();
        match self.path_map.entry(action_key.to_path_buf()) {
            std::collections::btree_map::Entry::Vacant(vacant_entry) => {
                vacant_entry.insert(src.map(|s| s.path().to_string()));
                self.actions.push(action);
            }
            std::collections::btree_map::Entry::Occupied(occupied_entry) => {
                // When conflicts happened, it's assumed to be overwritten
                // However the order doesn't matter, so actions is not touched
                self.possible_conflicts.push(TransactionConflict {
                    conflicted_path: action_key.to_path_buf(),
                    former_src: occupied_entry.get().clone(),
                    newer_src: src.map(|s| s.path().to_string()),
                });
            }
        }
    }

    /// Add a newer transaction with their source package for optional conflict identification
    pub fn merge<Pkg>(&mut self, newer: Transaction, src: Option<&Pkg>)
    where
        Pkg: PackageSrc<Err = Error> + PackageSrcExt<File>,
    {
        for action in newer.actions {
            self.push_action(action, src);
        }
    }

    /// Get list of conflicted actions and their sources if given.
    /// The action that is actually used will be the newer one.
    pub fn get_possible_conflicts(&self) -> &Vec<TransactionConflict> {
        &self.possible_conflicts
    }

    /// Peek into held actions
    pub fn get_actions(&self) -> &Vec<Action> {
        &self.actions
    }

    /// Convert into single giant transaction
    pub fn into_transaction(self) -> Transaction {
        Transaction::new(self.actions)
    }
}

pub struct TransactionConflict {
    pub conflicted_path: PathBuf,
    pub former_src: Option<String>,
    pub newer_src: Option<String>,
}