routinator 0.10.2

An RPKI relying party software.
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Local repository copy synchronized with rsync.
//!
//! The rsync collector works as follows:
//!
//! Data is kept in the directory given via the cache_dir attribute using the
//! rsync URI without the scheme as the path. We assume that data is published
//! in rsync modules identified by the first two components of this path. This
//! corresponds to the way the rsync daemon works.
//!
//! During a valiation run, we keep track of the modules we already have
//! updated. When access to a module that has not yet been updated is
//! requested, we spawn rsync and block until it returns. If during that time
//! another thread requests access to the same module, that thread is blocked,
//! too.

use std::{fmt, fs, io, ops};
use std::borrow::{Borrow, Cow, ToOwned};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Command as StdCommand, ExitStatus, Stdio};
use std::str::FromStr;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, SystemTime};
use bytes::Bytes;
use futures::TryFutureExt;
use log::{debug, error, info, warn};
use rpki::uri;
use tokio::process::Command as AsyncCommand;
use crate::config::Config;
use crate::error::Failed;
use crate::metrics::{Metrics, RsyncModuleMetrics};
use crate::utils::fatal;
use crate::utils::uri::UriExt;


//------------ Collector -----------------------------------------------------

/// A local copy of repositories synchronized via rsync.
#[derive(Debug)]
pub struct Collector {
    /// The base directory of the collector.
    working_dir: WorkingDir,

    /// The command for running rsync.
    ///
    /// If this is `None` actual rsyncing has been disabled and data
    /// present will be used as is.
    command: Option<RsyncCommand>,

    /// Whether to filter dubious authorities in rsync URIs.
    filter_dubious: bool,
}
 

impl Collector {
    /// Initializes the rsync collector without creating a value.
    ///
    /// This function is called implicitely by [`new`][Collector::new].
    pub fn init(config: &Config) -> Result<(), Failed> {
        let _ = Self::create_working_dir(config)?;
        Ok(())
    }

    /// Creates the working dir and returns its path.
    fn create_working_dir(config: &Config) -> Result<PathBuf, Failed> {
        let working_dir = config.cache_dir.join("rsync");

        if config.fresh {
            if let Err(err) = fs::remove_dir_all(&working_dir) {
                if err.kind() != io::ErrorKind::NotFound {
                    error!(
                        "Failed to delete rsync working directory at {}: {}",
                        working_dir.display(), err
                    );
                    return Err(Failed)
                }
            }
        }

        if let Err(err) = fs::create_dir_all(&working_dir) {
            error!(
                "Failed to create rsync working directory {}: {}.",
                working_dir.display(), err
            );
            return Err(Failed);
        }
        Ok(working_dir)
    }

    /// Creates a new rsync collector.
    ///
    /// If use of rsync is disabled via the config, returns `Ok(None)`.
    pub fn new(config: &Config) -> Result<Option<Self>, Failed> {
        if config.disable_rsync {
            Ok(None)
        }
        else {
            Ok(Some(Collector {
                working_dir: WorkingDir::new(
                    Self::create_working_dir(config)?
                ),
                command: Some(RsyncCommand::new(config)?),
                filter_dubious: !config.allow_dubious_hosts
            }))
        }
    }

    /// Prepares the collector for use in a validation run.
    pub fn ignite(&mut self) -> Result<(), Failed> {
        // We don’t need to do anything. But just in case we later will,
        // let’s keep the method around.
        Ok(())
    }

    /// Start a validation run on the collector.
    pub fn start(&self) -> Run {
        Run::new(self)
    }

    /// Dumps the content of the rsync collector.
    pub fn dump(&self, dir: &Path) -> Result<(), Failed> {
        let target = dir.join("rsync");
        debug!("Dumping rsync collector content to {}", target.display());

        if let Err(err) = fs::remove_dir_all(&target) {
            if err.kind() != io::ErrorKind::NotFound {
                error!(
                    "Failed to delete directory {}: {}",
                    dir.display(), err
                );
                return Err(Failed)
            }
        }
        self.dump_dir(&self.working_dir.base, &target)?;
        debug!("Rsync collector dump complete.");
        Ok(())
    }

    /// Recursively copies the content of `source` to `target`.
    fn dump_dir(&self, source: &Path, target: &Path) -> Result<(), Failed> {
        let read_dir = match fs::read_dir(source) {
            Ok(read_dir) => read_dir,
            Err(err) => {
                error!(
                    "Failed to open directory {}: {}", source.display(), err
                );
                return Err(Failed)
            }
        };
        for item in read_dir {
            let item = match item {
                Ok(item) => item,
                Err(err) => {
                    error!(
                        "Failed to read directory {}: {}",
                        source.display(), err
                    );
                    return Err(Failed)
                }
            };
            let file_type = match item.file_type() {
                Ok(file_type) => file_type,
                Err(err) => {
                    error!(
                        "Failed to file type for {}: {}",
                        item.path().display(), err
                    );
                    return Err(Failed)
                }
            };

            if file_type.is_dir() {
                let target = target.join(item.file_name());
                if let Err(err) = fs::create_dir_all(&target) {
                    error!(
                        "Failed to create directory {}: {}",
                        target.display(), err
                    );
                    return Err(Failed);
                }
                self.dump_dir(&item.path(), &target)?;
            }
            else if file_type.is_file() {
                let target = target.join(item.file_name());
                if let Err(err) = fs::copy( &item.path(), &target) {
                    error!(
                        "Failed to copy {} to {}: {}",
                        item.path().display(), target.display(), err
                    );
                    return Err(Failed)
                }
            }
        }
        Ok(())
    }
}


//------------ Run -----------------------------------------------------------

/// Using the rsync collector during a validation run.
#[derive(Debug)]
pub struct Run<'a> {
    /// A reference to the underlying collector.
    collector: &'a Collector,

    /// The set of modules that have been updated already.
    updated: RwLock<HashSet<OwnedModule>>,

    /// The modules that are currently being updated.
    ///
    /// The value in the map is a mutex that is used to synchronize competing
    /// attempts to update the module. Only the thread that has the mutex is
    /// allowed to actually run rsync.
    running: RwLock<HashMap<OwnedModule, Arc<Mutex<()>>>>,

    /// The metrics for updated rsync modules.
    metrics: Mutex<Vec<RsyncModuleMetrics>>,
}


impl<'a> Run<'a> {
    /// Creates a new runner from a collector.
    fn new(collector: &'a Collector) -> Self {
        Run {
            collector,
            updated: Default::default(),
            running: Default::default(),
            metrics: Default::default(),
        }
    }

    /// Returns whether the module for the given URI has been updated yet.
    ///
    /// This does not mean the module is actually up-to-date or even available
    /// as an update may have failed.
    pub fn was_updated(&self, uri: &uri::Rsync) -> bool {
        self.updated.read().unwrap().contains(Module::from_uri(uri).as_ref())
    }

    /// Tries to update the module for the given URI.
    ///
    /// If the module has not yet been updated, may block until an update
    /// finished. This update may not be successful and files in the module
    /// may be outdated or missing completely.
    pub fn load_module(&self, uri: &uri::Rsync) {
        let command = match self.collector.command.as_ref() {
            Some(command) => command,
            None => return,
        };
        let module = Module::from_uri(uri);

        // If it is already up-to-date, return.
        if self.updated.read().unwrap().contains(module.as_ref()) {
            return
        }

        // Get a clone of the (arc-ed) mutex. Make a new one if there isn’t
        // yet.
        let mutex = {
            self.running.write().unwrap()
            .entry(module.clone().into_owned()).or_default()
            .clone()
        };
        
        // Acquire the mutex. Once we have it, see if the module is up-to-date
        // which happens if someone else had it first.
        let _lock = mutex.lock().unwrap();
        if self.updated.read().unwrap().contains(module.as_ref()) {
            return
        }

        // Check if the module name is dubious. If so, skip updating.
        if self.collector.filter_dubious && uri.has_dubious_authority() {
            warn!(
                "{}: Dubious host name. Skipping update.",
                module
            )
        }
        else {
            // Run the actual update.
            let metrics = command.update(
                module.as_ref(),
                &self.collector.working_dir.module_path(module.as_ref())
            );

            // Insert into updated map and metrics.
            self.metrics.lock().unwrap().push(metrics);
        }

        // Remove from running.
        self.running.write().unwrap().remove(module.as_ref());

        // Insert into updated map no matter what.
        self.updated.write().unwrap().insert(module.into_owned());
    }

    /// Loads the file for the given URI.
    ///
    /// Does _not_ attempt to update the corresponding module first. You need
    /// to explicitely call [`load_module`][Run::load_module] for that.
    ///
    /// If the file is missing, returns `None`.
    pub fn load_file(
        &self,
        uri: &uri::Rsync,
    ) -> Option<Bytes> {
        let path = self.collector.working_dir.uri_path(uri);
        match fs::File::open(&path) {
            Ok(mut file) => {
                let mut data = Vec::new();
                if let Err(err) = io::Read::read_to_end(&mut file, &mut data) {
                    error!(
                        "Failed to read file '{}': {}",
                        path.display(),
                        err
                    );
                    None
                }
                else {
                    Some(data.into())
                }
            }
            Err(err) => {
                if err.kind() == io::ErrorKind::NotFound {
                    info!("{}: not found in local repository", uri);
                } else {
                    error!(
                        "Failed to open file '{}': {}",
                        path.display(), err
                    );
                }
                None
            }
        }
    }

    /// Cleans the collector only keeping the modules included in `retain`.
    //
    //  This currently is super agressive, deleting everyting that it doesn’t
    //  like.
    pub fn cleanup(&self, retain: &mut ModuleSet) -> Result<(), Failed> {
        if self.collector.command.is_none() {
            return Ok(())
        }

        // Add all modules we’ve used during this run to retain.
        for module in self.updated.read().unwrap().iter() {
            retain.add_from_uri(&module.to_uri());
        }

        for entry in fatal::read_dir(
            &self.collector.working_dir.base
        )? {
            let entry = entry?;
            let keep = match entry.file_name().to_str() {
                Some(name) => {
                    match retain.authorities.get(name) {
                        Some(modules) => self.cleanup_host(&entry, modules)?,
                        None => false,
                    }
                }
                None => false
            };

            if !keep {
                fatal::remove_dir_all(entry.path())?;
            }
        }

        Ok(())
    }

    /// Removes all modules from the directory that are not in `retain`.
    ///
    /// Returns whether the host directory should be kept or can be deleted,
    /// too.
    fn cleanup_host(
        &self, entry: &fatal::DirEntry, retain: &HashSet<String>
    ) -> Result<bool, Failed> {
        if entry.is_file() {
            fatal::remove_file(entry.path())?;
            return Ok(false)
        }
        else if !entry.is_dir() {
            return Ok(false)
        }

        let mut keep_host = false;
        for entry in fatal::read_dir(entry.path())? {
            let entry = entry?;
            let keep = match entry.file_name().to_str() {
                Some(name) => retain.contains(name),
                None => false
            };

            if !keep {
                fatal::remove_dir_all(entry.path())?;
            }
            else {
                keep_host = true;
            }
        }

        Ok(keep_host)
    }

    /// Finishes the validation run.
    ///
    /// Updates `metrics` with the collector run’s metrics.
    ///
    /// If you are not interested in the metrics, you can simple drop the
    /// value, instead.
    pub fn done(self, metrics: &mut Metrics) {
        metrics.rsync = self.metrics.into_inner().unwrap();
    }
}


//------------ RsyncCommand --------------------------------------------------

/// The command to run rsync.
#[derive(Debug)]
struct RsyncCommand {
    /// The actual command.
    command: String,

    /// The list of additional arguments.
    ///
    /// We will always add a few more when actually running.
    args: Vec<String>,

    /// The rsync timeout.
    timeout: Duration,
}

impl RsyncCommand {
    /// Creates a new rsync command from the config.
    pub fn new(config: &Config) -> Result<Self, Failed> {
        let command = config.rsync_command.clone();
        let output = match StdCommand::new(&command).arg("-h").output() {
            Ok(output) => output,
            Err(err) => {
                error!(
                    "Failed to run rsync: {}",
                    err
                );
                return Err(Failed)
            }
        };
        if !output.status.success() {
            error!(
                "Running rsync failed with output: \n{}",
                String::from_utf8_lossy(&output.stderr)
            );
            return Err(Failed);
        }
        let args = match config.rsync_args {
            Some(ref args) => args.clone(),
            None => {
                let mut args = Vec::new();
                let has_contimeout =
                   output.stdout.windows(12)
                   .any(|window| window == b"--contimeout");
                if has_contimeout {
                    args.push("--contimeout=10".into());
                }
                if let Some(max_size) = config.max_object_size {
                    args.push(format!("--max-size={}", max_size));
                }
                args
            }
        };
        Ok(RsyncCommand {
            command,
            args,
            timeout: config.rsync_timeout,
        })
    }

    /// Updates a module by running rsync.
    pub fn update(
        &self,
        source: &Module,
        destination: &Path
    ) -> RsyncModuleMetrics {
        let start = SystemTime::now();
        let status = self.command(
            source, destination
        ).and_then(|cmd| self.run(source, cmd));
        RsyncModuleMetrics {
            module: source.to_uri(),
            status,
            duration: SystemTime::now().duration_since(start),
        }
    }

    /// Actually runs the rsync command.
    fn run(
        &self,
        source: &Module,
        mut command: AsyncCommand
    ) -> Result<ExitStatus, io::Error> {
        // Because we can’t have a timeout on a child process with just std,
        // we resort to Tokio here: We fire up a current-thread runtime and
        // use Tokio’s async process handling.

        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .enable_time()
            .build()?;

        runtime.block_on(async {
            command.stdout(Stdio::piped());
            command.stderr(Stdio::piped());
            command.kill_on_drop(true);
            let mut child = command.spawn()?;
            let stdout = child.stdout.take();
            let stderr = child.stderr.take();
            let (status, stdout, stderr) = tokio::try_join!(
                tokio::time::timeout(
                    self.timeout, child.wait()
                ).map_err(|_| {
                    warn!("{}: timed out.", source);
                    io::Error::new(
                        io::ErrorKind::TimedOut,
                        "rsync process reached time out"
                    )
                }),
                async {
                    let mut target = Vec::new();
                    if let Some(mut stdout) = stdout {
                        tokio::io::copy(&mut stdout, &mut target).await?;
                    }
                    Ok(target)
                },
                async {
                    let mut target = Vec::new();
                    if let Some(mut stderr) = stderr {
                        tokio::io::copy(&mut stderr, &mut target).await?;
                    }
                    Ok(target)
                },
            )?;
            if !stderr.is_empty() {
                String::from_utf8_lossy(&stderr).lines().for_each(|l| {
                    warn!("{}: {}", source, l);
                })
            }
            if !stdout.is_empty() {
                String::from_utf8_lossy(&stdout).lines().for_each(|l| {
                    info!("{}: {}", source, l);
                })
            }
            if let Err(ref err) = status {
                warn!("{}: {}", source, err);
            }
            status
        })
    }

    /// Creates the rsync command.
    fn command(
        &self,
        source: &Module,
        destination: &Path
    ) -> Result<AsyncCommand, io::Error> {
        info!("rsyncing from {}.", source);
        fs::create_dir_all(destination)?;
        let destination = match Self::format_destination(destination) {
            Ok(some) => some,
            Err(_) => {
                error!(
                    "rsync: illegal destination path {}.",
                    destination.display()
                );
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "illegal destination path"
                ));
            }
        };
        let mut cmd = AsyncCommand::new(&self.command);
        for item in &self.args {
            cmd.arg(item);
        }
        cmd.arg("-rltz")
           .arg("--delete")
           .arg(source.to_string())
           .arg(destination);
        debug!("{}: Running command {:?}", source, cmd);
        Ok(cmd)
    }

    /// Formats the destination path for inclusion in the command.
    #[cfg(not(windows))]
    #[allow(clippy::unnecessary_wraps)]
    fn format_destination(path: &Path) -> Result<String, Failed> {
        // Make sure the path ends in a slash or strange things happen.
        let mut destination = format!("{}", path.display());
        if !destination.ends_with('/') {
            destination.push('/')
        }
        Ok(destination)
    }

    /// Formats the destination path for inclusion in the command.
    #[cfg(windows)]
    fn format_destination(path: &Path) -> Result<String, Failed> {
        // On Windows we are using Cygwin rsync which requires Unix-style
        // paths. In particular, the drive parameter needs to be turned
        // from e.g. `C:` into `/cygdrive/c` and all backslashes should
        // become slashes.
        use std::path::{Component, Prefix};

        let mut destination = String::new();
        for component in path.components() {
            match component {
                Component::Prefix(prefix) => {
                    // We only accept UNC and Disk prefixes. Everything else
                    // causes an error.
                    match prefix.kind() {
                        Prefix::UNC(server, share) => {
                            let (server, share) = match (server.to_str(),
                                                         share.to_str()) {
                                (Some(srv), Some(shr)) => (srv, shr),
                                _ => return Err(Failed)
                            };
                            destination.push_str(server);
                            destination.push('/');
                            destination.push_str(share);
                        }
                        Prefix::Disk(disk) => {
                            let disk = if disk.is_ascii() {
                                (disk as char).to_ascii_lowercase()
                            }
                            else {
                                return Err(Failed)
                            };
                            destination.push_str("/cygdrive/");
                            destination.push(disk);
                        }
                        _ => return Err(Failed)
                    }
                }
                Component::CurDir | Component::RootDir => {
                    continue
                }
                Component::ParentDir => {
                    destination.push_str("..");
                }
                Component::Normal(s) => {
                    match s.to_str() {
                        Some(s) => destination.push_str(s),
                        None => return Err(Failed)
                    }
                }
            }
            destination.push('/');
        }
        Ok(destination)
    }
}


//------------ WorkingDir ----------------------------------------------------

/// The working directory of the rsync collector.
#[derive(Clone, Debug)]
struct WorkingDir {
    /// The base path.
    base: PathBuf
}

impl WorkingDir {
    /// Creates a new value.
    ///
    /// Does not actually create the directory on disk.
    pub fn new(base: PathBuf) -> Self {
        WorkingDir { base }
    }

    /// Returns the absolute path for the given module.
    pub fn module_path(&self, module: &Module) -> PathBuf {
        let mut res = self.base.clone();
        res.push(&module.0[8..]);
        res
    }

    /// Returns the absolute path for the given URI.
    fn uri_path(&self, uri: &uri::Rsync) -> PathBuf {
        let mut res = self.base.clone();
        res.push(uri.canonical_authority().as_ref());
        res.push(uri.module_name());
        res.push(uri.path());
        res
    }
}


//------------ Module --------------------------------------------------------

/// The module portion of an rsync URI.
///
/// This is an unsized object – essentially a wrapped `str`.
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct Module(str);

impl Module {
    /// Creates a new module without checking the underlying string.
    unsafe fn from_str(s: &str) -> &Module {
        &*(s as *const str as *const Module)
    }

    /// Returns a module reference for a reference to an rsync URI.
    ///
    /// Because the authority portion of a URI is case insensitive, the
    /// function may have to convert upper ASCII case letters into lower case
    /// to create a canonical value. If this has to happen, an [`OwnedModule`]
    /// is returned via the cow.
    pub fn from_uri(uri: &uri::Rsync) -> Cow<Module> {
        match uri.canonical_module() {
            Cow::Borrowed(s) => {
                Cow::Borrowed(unsafe { Module::from_str(s) })
            }
            Cow::Owned(s) => Cow::Owned(OwnedModule(s))
        }
    }

    /// Converts a module reference into its rsync URI.
    pub fn to_uri(&self) -> uri::Rsync {
        uri::Rsync::from_str(&self.0).unwrap()
    }
}


//--- ToOwned

impl ToOwned for Module {
    type Owned = OwnedModule;

    fn to_owned(&self) -> Self::Owned {
        OwnedModule(self.0.to_owned())
    }
}


//--- Display

impl fmt::Display for Module {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}


//------------ OwnedModule ---------------------------------------------------

/// An owned version of the module portion of an rsync URI.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct OwnedModule(String);


//--- Deref, AsRef, Borrow

impl ops::Deref for OwnedModule {
    type Target = Module;

    fn deref(&self) -> &Module {
        self.as_ref()
    }
}

impl AsRef<Module> for OwnedModule {
    fn as_ref(&self) -> &Module {
        unsafe { Module::from_str(self.0.as_str()) }
    }
}

impl Borrow<Module> for OwnedModule {
    fn borrow(&self) -> &Module {
        self.as_ref()
    }
}


//--- Display

impl fmt::Display for OwnedModule {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        self.0.fmt(f)
    }
}


//------------ ModuleSet -----------------------------------------------------

/// A set of rsync modules.
///
/// This is used in cleanup.
#[derive(Clone, Debug, Default)]
pub struct ModuleSet {
    /// The modules under each authority.
    authorities: HashMap<String, HashSet<String>>,
}

impl ModuleSet {
    /// Adds a the module from a URI to the set.
    ///
    /// Returns whether the module was new to the set.
    pub fn add_from_uri(&mut self, uri: &uri::Rsync) -> bool {
        self.with_authority(uri, |auth| {
            let module_name = uri.module_name();
            if auth.contains(module_name) {
                false
            }
            else {
                auth.insert(module_name.to_string());
                true
            }
        })
    }

    fn with_authority<F: FnOnce(&mut HashSet<String>) -> R, R>(
        &mut self, uri: &uri::Rsync, op: F,
    ) -> R {
        // If uri.canonical_authority returns a borrowed str, we avoid an
        // allocation at the price of a double lookup for a missing
        // authority. Given that the map should be relatively small, this
        // should be faster.
        let auth = uri.canonical_authority();
        if let Cow::Borrowed(auth) = auth {
            if let Some(value) = self.authorities.get_mut(auth) {
                return op(value)
            }
        }
        op(self.authorities.entry(auth.into_owned()).or_default())
    }
}