routinator 0.15.1

An RPKI relying party software.
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
//! Utilities for dealing with the file system.
//!
//! This module contains variations on some of the functions provided by
//! `std::fs` that instead of returning `std::io::Error` log that error and
//! return our own [`Failed`] instead.

use std::{fmt, fs, io};
use std::ffi::{OsStr, OsString};
use std::fs::{File, Metadata};
use std::path::{Path, PathBuf};
use log::error;
use crate::error::Failed;


//------------ DirEntry ------------------------------------------------------

/// A version of `DirEntry` that has all its components resolved.
#[derive(Clone, Debug)]
pub struct DirEntry {
    path: PathBuf,
    metadata: Metadata,
    file_name: OsString,
}

impl DirEntry {
    /// Returns a reference to the path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Converts the entry into the path.
    pub fn into_path(self) -> PathBuf {
        self.path
    }

    /// Returns a reference to metadata.
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Returns a reference to the file name.
    pub fn file_name(&self) -> &OsStr {
        &self.file_name
    }

    /// Converts the entry into the file name.
    pub fn into_file_name(self) -> OsString {
        self.file_name
    }

    /// Converts the entry into file name and path.
    pub fn into_name_and_path(self) -> (OsString, PathBuf) {
        (self.file_name, self.path)
    }

    /// Returns whether the entry is a file.
    pub fn is_file(&self) -> bool {
        self.metadata.is_file()
    }

    /// Returns whether the entry is a directory.
    pub fn is_dir(&self) -> bool {
        self.metadata.is_dir()
    }

    /// Returns the size of the underlying file.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> u64 {
        self.metadata.len()
    }
}


//------------ ReadDir -------------------------------------------------------

/// A version of `ReadDir` that logs on error.
#[derive(Debug)]
pub struct ReadDir<'a> {
    path: &'a Path,
    iter: fs::ReadDir,
}

impl Iterator for ReadDir<'_> {
    type Item = Result<DirEntry, Failed>;

    fn next(&mut self) -> Option<Self::Item> {
        let entry = match self.iter.next()? {
            Ok(entry) => entry,
            Err(err) => {
                error!(
                    "Fatal: failed to read directory {}: {}",
                    self.path.display(), IoErrorDisplay(err)
                );
                return Some(Err(Failed))
            }
        };
        let metadata = match entry.metadata() {
            Ok(metadata) => metadata,
            Err(err) => {
                error!(
                    "Fatal: failed to read directory {}: {}",
                    self.path.display(), IoErrorDisplay(err)
                );
                return Some(Err(Failed))
            }
        };
        Some(Ok(DirEntry {
            path: entry.path(),
            metadata,
            file_name: entry.file_name()
        }))
    }
}


//------------ read_dir ------------------------------------------------------

/// Returns an iterator over a directory, logging fatal errors on any error.
pub fn read_dir(path: &Path) -> Result<ReadDir<'_>, Failed> {
    match fs::read_dir(path) {
        Ok(iter) => Ok(ReadDir { path, iter }),
        Err(err) => {
            error!(
                "Fatal: failed to open directory {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            Err(Failed)
        }
    }
}


//------------ read_existing_dir ---------------------------------------------

/// Returns an iterator over an existing directory.
///
/// Returns `None` if the repository doesn’t exist.
pub fn read_existing_dir(path: &Path) -> Result<Option<ReadDir<'_>>, Failed> {
    match fs::read_dir(path) {
        Ok(iter) => Ok(Some(ReadDir { path, iter })),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(err) => {
            error!(
                "Fatal: failed to open directory {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            Err(Failed)
        }
    }
}


//------------ create_dir_all ------------------------------------------------

/// Creates all directories leading to the given directory or logs an error.
pub fn create_dir_all(path: &Path) -> Result<(), Failed> {
    fs::create_dir_all(path).map_err(|err| {
        error!(
            "Fatal: failed to create directory {}: {}",
            path.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ create_parent_all ---------------------------------------------

/// Creates all directories leading necessary to create a file.
pub fn create_parent_all(path: &Path) -> Result<(), Failed> {
    if let Some(path) = path.parent() {
        fs::create_dir_all(path).map_err(|err| {
            error!(
                "Fatal: failed to create directory {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            Failed
        })?
    }
    Ok(())
}


//------------ remove_dir_all ------------------------------------------------

/// Removes a directory tree.
pub fn remove_dir_all(path: &Path) -> Result<(), Failed> {
    if let Err(err) = fs::remove_dir_all(path) {
        if err.kind() != io::ErrorKind::NotFound {
            error!(
                "Fatal: failed to remove directory tree {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            return Err(Failed)
        }
    }
    Ok(())
}


//------------ remove_file ---------------------------------------------------

/// Removes a file.
///
/// Ignores if the file doesn’t exist.
pub fn remove_file(path: &Path) -> Result<(), Failed> {
    if let Err(err) = fs::remove_file(path) {
        if err.kind() != io::ErrorKind::NotFound {
            error!(
                "Fatal: failed to remove file {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            return Err(Failed)
        }
    }
    Ok(())
}


//------------ remove_all ----------------------------------------------------

/// Removes a file or a directory tree.
pub fn remove_all(path: &Path) -> Result<(), Failed> {
    if path.is_dir() {
        remove_dir_all(path)
    }
    else {
        remove_file(path)
    }
}


//------------ rename --------------------------------------------------------

/// Renames a file or directory.
///
/// See ´std::fs::rename`` for the various ramifications.
pub fn rename(source: &Path, target: &Path) -> Result<(), Failed> {
    fs::rename(source, target).map_err(|err| {
        error!(
            "Fatal: failed to move {} to {}: {}",
            source.display(), target.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ open_file -----------------------------------------------------

/// Opens a file.
///
/// Errors out if the file doesn’t exist.
pub fn open_file(path: &Path) -> Result<File, Failed> {
    File::open(path).map_err(|err| {
        error!(
            "Fatal: failed to open file {}: {}",
            path.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ open_existing_file --------------------------------------------

/// Opens a file if it exists.
pub fn open_existing_file(path: &Path) -> Result<Option<File>, Failed> {
    match File::open(path) {
        Ok(file) => Ok(Some(file)),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(err) => {
            error!(
                "Fatal: failed to open file {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            Err(Failed)
        }
    }
}


//------------ create_file ---------------------------------------------------

/// Opens a file in write-only mode.
///
/// Create a file if it does not exist, and truncates it if it does.
pub fn create_file(path: &Path) -> Result<File, Failed> {
    File::create(path).map_err(|err| {
        error!(
            "Fatal: failed to open file {}: {}",
            path.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ read_file -----------------------------------------------------

/// Reads a file’s entire content into a vec.
///
/// Errors out if the file cannot be opened for reading or reading fails.
pub fn read_file(path: &Path) -> Result<Vec<u8>, Failed> {
    fs::read(path).map_err(|err| {
        error!(
            "Fatal: failed to read file {}: {}",
            path.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ read_existing_file --------------------------------------------

/// Reads an existing file’s entire content into a vec.
///
/// Returns `Ok(None)` if the file doesn’t exist.  Errors out if the file
/// fails to be opened for reading or reading fails.
pub fn read_existing_file(path: &Path) -> Result<Option<Vec<u8>>, Failed> {
    match fs::read(path) {
        Ok(some) => Ok(Some(some)),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(err) => {
            error!(
                "Fatal: failed to read file {}: {}",
                path.display(), IoErrorDisplay(err)
            );
            Err(Failed)
        }
    }
}


//------------ write_file ----------------------------------------------------

/// Writes a slice to a file.
///
/// Errors out if the file cannot be opened for writing or writing fails.
/// If the file exists, overwrites the current content.
pub fn write_file(path: &Path, contents: &[u8]) -> Result<(), Failed> {
    fs::write(path, contents).map_err(|err| {
        error!(
            "Fatal: failed to write file {}: {}",
            path.display(), IoErrorDisplay(err)
        );
        Failed
    })
}


//------------ copy_dir_all --------------------------------------------------

/// Copies the content of a directory if it exists.
///
/// Creates the target directory with `create_dir_all`.  Errors out if
/// anything goes wrong.
///
/// If the source directory does not exist, does nothing.
pub fn copy_existing_dir_all(
    source: &Path, target: &Path
) -> Result<(), Failed> {
    let source_dir = match read_existing_dir(source)? {
        Some(entry) => entry,
        None => return Ok(()),
    };
    create_dir_all(target)?;
    for entry in source_dir {
        let entry = entry?;
        if entry.is_file() {
            if let Err(err) = fs::copy(
                entry.path(), target.join(entry.file_name())
            ) {
                error!(
                    "Fatal: failed to copy {}: {}",
                    entry.path().display(), IoErrorDisplay(err)
                );
                return Err(Failed)
            }
        }
        else if entry.is_dir() {
            copy_existing_dir_all(
                entry.path(),
                &target.join(entry.file_name())
            )?;
        }
    }
    Ok(())
}


//------------ IoErrorDisplay ------------------------------------------------

struct IoErrorDisplay(io::Error);

#[cfg(unix)]
impl fmt::Display for IoErrorDisplay {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use nix::errno::Errno;

        if matches!(
            self.0.raw_os_error().map(Errno::from_raw),
            Some(Errno::ENOSPC)
        ) {
            f.write_str("No space or inodes left on device")
        }
        else {
            self.0.fmt(f)
        }
    }
}


#[cfg(not(unix))]
impl fmt::Display for IoErrorDisplay {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}