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
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920

use std::error::Error;
use std::{error, fmt, io};
use std::collections::HashSet;
use std::io::Read;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use log::{error, warn};
use reqwest::StatusCode;
use ring::digest;
use rpki::{rrdp, uri};
use rpki::rrdp::{DeltaInfo, NotificationFile, ProcessDelta, ProcessSnapshot};
use uuid::Uuid;
use crate::error::{Failed, RunFailed};
use crate::log::LogBookWriter;
use crate::metrics::RrdpRepositoryMetrics;
use crate::utils::archive::{ArchiveError, PublishError};
use super::archive::{
    AccessError, FallbackTime, RepositoryState, RrdpArchive,
    SnapshotRrdpArchive,
};
use super::base::Collector;
use super::http::{HttpClient, HttpResponse, HttpStatus};


//------------ Notification --------------------------------------------------

/// The notification file of an RRDP repository.
pub struct Notification {
    /// The URI of the notification file.
    uri: uri::Https,

    /// The content of the file.
    content: NotificationFile,

    /// The Etag value if provided.
    etag: Option<Bytes>,

    /// The Last-Modified value if provided,
    last_modified: Option<DateTime<Utc>>,
}

impl Notification {
    /// Requests, parses, and returns the given RRDP notification file.
    ///
    /// The value referred to by `status` will be updated to the received
    /// status code or `HttpStatus::Error` if the request failed.
    ///
    /// Returns the notification file on success. Returns `Ok(None)` if a
    /// response was received successfully but indicated that the
    /// notification file was not updated.
    pub fn get(
        http: &HttpClient,
        uri: &uri::Https,
        state: Option<&RepositoryState>,
        status: &mut HttpStatus,
        delta_list_limit: usize,
        log: &mut LogBookWriter,
    ) -> Result<Option<Self>, Failed> {
        let response = match http.conditional_response(
            uri,
            state.and_then(|state| state.etag.as_ref()),
            state.and_then(|state| state.last_modified()),
        ) {
            Ok(response) => {
                *status = response.status().into();
                response
            }
            Err(err) => {
                if let Some(source) = err.source() {
                    log.warn(format_args!("{err} ({source})"));
                } else {
                    log.warn(format_args!("{err}"));
                }
                *status = HttpStatus::Error;
                return Err(Failed)
            }
        };

        if response.status() == StatusCode::NOT_MODIFIED {
            Ok(None)
        }
        else if response.status() != StatusCode::OK {
            log.warn(format_args!(
                "Getting notification file failed with status {}",
                response.status()
            ));
            Err(Failed)
        }
        else {
            Notification::from_response(
                uri.clone(), response, delta_list_limit, log,
            ).map(Some)
        }
    }


    /// Creates a new notification from a successful HTTP response.
    ///
    /// Assumes that the response status was 200 OK.
    fn from_response(
        uri: uri::Https,
        response: HttpResponse,
        delta_list_limit: usize,
        log: &mut LogBookWriter,
    ) -> Result<Self, Failed> {
        let etag = response.etag();
        let last_modified = response.last_modified();
        let mut content = NotificationFile::parse_limited(
            io::BufReader::new(response), delta_list_limit
        ).map_err(|err| {
            log.warn(format_args!("{err}"));
            Failed
        })?;
        if !content.has_matching_origins(&uri) {
            log.warn(format_args!(
                "snapshot or delta files with different origin"
            ));
            return Err(Failed)
        }
        content.sort_deltas();
        Ok(Notification { uri, content, etag, last_modified })
    }

    /// Returns a reference to the content of the notification file.
    pub fn content(&self) -> &NotificationFile {
        &self.content
    }

    /// Creates repository state for this notification.
    pub fn to_repository_state(
        &self, fallback: FallbackTime,
    ) -> RepositoryState {
        RepositoryState {
            rpki_notify: self.uri.clone(),
            session: self.content.session_id(),
            serial: self.content.serial(),
            updated_ts: Utc::now().timestamp(),
            best_before_ts: fallback.best_before().timestamp(),
            last_modified_ts: self.last_modified.map(|x| x.timestamp()),
            etag: self.etag.clone(),
            delta_state: self.content.deltas().iter().map(|delta| {
                (delta.serial(), delta.hash())
            }).collect(),
        }
    }

    /// Checks that the deltas match those present in `state`.
    ///
    /// Ensures that for delta serial numbers present both in the notification
    /// and the state the hash values match.
    pub fn check_deltas(
        &self, state: &RepositoryState
    ) -> Result<(), SnapshotReason> {
        for delta in self.content().deltas() {
            if let Some(state_hash) = state.delta_state.get(&delta.serial()) {
                if delta.hash() != *state_hash {
                    return Err(SnapshotReason::DeltaMutation)
                }
            }
        }
        Ok(())
    }
}


//------------ SnapshotUpdate ------------------------------------------------

/// An update to a repository performed from a snapshot file.
///
/// For this type of update, we collect all the published objects in the
/// repository’s temp directory and move it over to the object directory upon
/// success.
pub struct SnapshotUpdate<'a> {
    /// The collector.
    collector: &'a Collector,

    /// The archive to store the snapshot into.
    archive: &'a mut SnapshotRrdpArchive,

    /// The notification file pointing to the snapshot.
    notify: &'a Notification,

    /// The metrics for the update.
    metrics: &'a mut RrdpRepositoryMetrics,
}

impl<'a> SnapshotUpdate<'a> {
    pub fn new(
        collector: &'a Collector,
        archive: &'a mut SnapshotRrdpArchive,
        notify: &'a Notification,
        metrics: &'a mut RrdpRepositoryMetrics,
    ) -> Self {
        SnapshotUpdate { collector, archive, notify, metrics }
    }

    pub fn try_update(mut self) -> Result<(), SnapshotError> {
        let response = match self.collector.http().response(
            self.notify.content.snapshot().uri()
        ) {
            Ok(response) => {
                self.metrics.payload_status = Some(response.status().into());
                if response.status() != StatusCode::OK {
                    return Err(response.status().into())
                }
                else {
                    response
                }
            }
            Err(err) => {
                self.metrics.payload_status = Some(HttpStatus::Error);
                return Err(err.into())
            }
        };

        let mut reader = io::BufReader::new(HashRead::new(response));
        self.process(&mut reader)?;
        reader.into_inner().verify_hash(
            self.notify.content.snapshot().hash()
        )?;
        self.archive.publish_state(
            &self.notify.to_repository_state(
                self.collector.config().fallback_time
            )
        )?;
        self.archive.finalize()?;
        Ok(())
    }
}

impl ProcessSnapshot for SnapshotUpdate<'_> {
    type Err = SnapshotError;

    fn meta(
        &mut self,
        session_id: Uuid,
        serial: u64,
    ) -> Result<(), Self::Err> {
        if session_id != self.notify.content.session_id() {
            return Err(SnapshotError::SessionMismatch {
                expected: self.notify.content.session_id(),
                received: session_id
            })
        }
        if serial != self.notify.content.serial() {
            return Err(SnapshotError::SerialMismatch {
                expected: self.notify.content.serial(),
                received: serial
            })
        }
        Ok(())
    }

    fn publish(
        &mut self,
        uri: uri::Rsync,
        data: &mut rrdp::ObjectReader,
    ) -> Result<(), Self::Err> {
        let content = RrdpDataRead::new(
            data, &uri, self.collector.config().max_object_size,
        ).read_all()?;
        self.archive.publish_object(&uri, &content).map_err(|err| match err {
            PublishError::AlreadyExists => {
                SnapshotError::DuplicateObject(uri.clone())
            }
            PublishError::Archive(ArchiveError::Corrupt(_)) => {
                warn!(
                    "Temporary RRDP repository file {} became corrupt.",
                    self.archive.path().display(),
                );
                SnapshotError::RunFailed(RunFailed::retry())
            }
            PublishError::Archive(ArchiveError::Io(err)) => {
                error!(
                    "Fatal: Failed to write to temporary RRDP repository file \
                     {}: {}",
                     self.archive.path().display(), err,
                );
                SnapshotError::RunFailed(RunFailed::fatal())
            }
        })
    }
}


//------------ DeltaUpdate ---------------------------------------------------

/// An update to a repository performed from a delta file.
///
/// For this kind of update, we collect newly published and updated objects in
/// the repository’s temp directory and remember them as well as all deleted
/// objects and if everything is okay, copy files over to and delete files in
/// the object directory.
pub struct DeltaUpdate<'a> {
    /// The collector.
    collector: &'a Collector,

    /// The archive the repository is stored in.
    archive: &'a mut RrdpArchive,

    /// The session ID of the RRDP session.
    session_id: Uuid,

    /// Information about the delta file.
    info: &'a DeltaInfo,

    /// The metrics for the update.
    metrics: &'a mut RrdpRepositoryMetrics,

    /// The URIs we’ve already seen in this delta.
    ///
    /// This is so we can error out if a URI was touched more than once.
    seen: HashSet<uri::Rsync>,
}

impl<'a> DeltaUpdate<'a> {
    /// Creates a new delta update.
    pub fn new(
        collector: &'a Collector,
        archive: &'a mut RrdpArchive,
        session_id: Uuid,
        info: &'a DeltaInfo,
        metrics: &'a mut RrdpRepositoryMetrics,
    ) -> Self {
        DeltaUpdate {
            collector, archive, session_id, info, metrics,
            seen: Default::default(),
        }
    }

    pub fn try_update(mut self) -> Result<(), DeltaError> {
        let response = match self.collector.http().response(
            self.info.uri()
        ) {
            Ok(response) => {
                self.metrics.payload_status = Some(response.status().into());
                if response.status() != StatusCode::OK {
                    return Err(response.status().into())
                }
                else {
                    response
                }
            }
            Err(err) => {
                self.metrics.payload_status = Some(HttpStatus::Error);
                return Err(err.into())
            }
        };

        let mut reader = io::BufReader::new(HashRead::new(response));
        self.process(&mut reader)?;
        reader.into_inner().verify_hash(self.info.hash())?;
        Ok(())
    }
}

impl ProcessDelta for DeltaUpdate<'_> {
    type Err = DeltaError;

    fn meta(
        &mut self, session_id: Uuid, serial: u64
    ) -> Result<(), Self::Err> {
        if session_id != self.session_id {
            return Err(DeltaError::SessionMismatch {
                expected: self.session_id,
                received: session_id
            })
        }
        if serial != self.info.serial() {
            return Err(DeltaError::SerialMismatch {
                expected: self.info.serial(),
                received: serial
            })
        }
        Ok(())
    }

    fn publish(
        &mut self,
        uri: uri::Rsync,
        hash: Option<rrdp::Hash>,
        data: &mut rrdp::ObjectReader<'_>
    ) -> Result<(), Self::Err> {
        if !self.seen.insert(uri.clone()) {
            return Err(DeltaError::ObjectRepeated { uri })
        }
        let content = RrdpDataRead::new(
            data, &uri, self.collector.config().max_object_size
        ).read_all()?;
        match hash {
            Some(hash) => {
                self.archive.update_object(
                    &uri, hash, &content
                ).map_err(|err| match err {
                    AccessError::NotFound => {
                        DeltaError::MissingObject { uri: uri.clone() }
                    }
                    AccessError::HashMismatch => {
                        DeltaError::ObjectHashMismatch { uri: uri.clone() }
                    }
                    AccessError::Archive(err) => DeltaError::Archive(err),
                })
            }
            None => {
                self.archive.publish_object(&uri, &content).map_err(|err| {
                    match err {
                        PublishError::AlreadyExists => {
                            DeltaError::ObjectAlreadyPresent {
                                uri: uri.clone()
                            }
                        }
                        PublishError::Archive(err) => {
                            DeltaError::Archive(err)
                        }
                    }
                })
            }
        }
    }

    fn withdraw(
        &mut self,
        uri: uri::Rsync,
        hash: rrdp::Hash
    ) -> Result<(), Self::Err> {
        if !self.seen.insert(uri.clone()) {
            return Err(DeltaError::ObjectRepeated { uri })
        }
        self.archive.delete_object(&uri, hash).map_err(|err| match err {
            AccessError::NotFound => {
                DeltaError::MissingObject { uri: uri.clone() }
            }
            AccessError::HashMismatch => {
                DeltaError::ObjectHashMismatch { uri: uri.clone() }
            }
            AccessError::Archive(err) => DeltaError::Archive(err),
        })
    }
}


//------------ HashRead ------------------------------------------------------

/// A reader wrapper that calculates the SHA-256 hash of all read data.
struct HashRead<R> {
    /// The wrapped reader.
    reader: R,

    /// The context for hash calculation.
    context: digest::Context,
}

impl<R> HashRead<R> {
    /// Creates a new hash reader.
    pub fn new(reader: R) -> Self {
        HashRead {
            reader,
            context: digest::Context::new(&digest::SHA256)
        }
    }

    /// Checks that the hash matches the provided hash.
    pub fn verify_hash(
        self, expected: rrdp::Hash
    ) -> Result<(), HashMismatch> {
        if self.context.finish().as_ref() != expected.as_ref() {
            Err(HashMismatch)
        }
        else {
            Ok(())
        }
    }
}


impl<R: io::Read> io::Read for HashRead<R> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
        let res = self.reader.read(buf)?;
        self.context.update(&buf[..res]);
        Ok(res)
    }
}


//------------ RrdpDataRead --------------------------------------------------

/// A reader that reads the data of objects in a snapshot or delta.
///
/// The type ensures the size limit of objects and allows treating read errors
/// differently than write errors by storing any error and making it available
/// after the fact.
struct RrdpDataRead<'a, R> {
    /// The wrapped reader.
    reader: R,

    /// The URI of the object we are reading.
    uri: &'a uri::Rsync,

    /// The number of bytes left to read.
    ///
    /// If this is `None` we are allowed to read an unlimited amount.
    left: Option<u64>,

    /// The last error that happend.
    err: Option<RrdpDataReadError>,
}

impl<'a, R> RrdpDataRead<'a, R> {
    /// Creates a new read from necessary information.
    ///
    /// The returned value will wrap `reader`. The `uri` should be the rsync
    /// URI of the published object. It is only used for generating meaningful
    /// error messages. If `max_size` is some value, the size of the object
    /// will be limited to that value in bytes. Larger objects lead to an
    /// error.
    pub fn new(reader: R, uri: &'a uri::Rsync, max_size: Option<u64>) -> Self {
        RrdpDataRead { reader, uri, left: max_size, err: None }
    }

    /// Returns a stored error if available.
    ///
    /// If it returns some error, that error happened during reading before
    /// an `io::Error` was returned.
    ///
    /// The method takes the stored error and replaces it internally with
    /// `None`.
    pub fn take_err(&mut self) -> Option<RrdpDataReadError> {
        self.err.take()
    }
}

impl<R: io::Read> RrdpDataRead<'_, R> {
    /// Reads the data into a vec.
    pub fn read_all(mut self) -> Result<Vec<u8>, RrdpDataReadError> {
        let mut content = Vec::new();
        if let Err(io_err) = self.read_to_end(&mut content) {
            return Err(
                match self.take_err() {
                    Some(data_err) => data_err,
                    None => RrdpDataReadError::Read(io_err),
                }
            )
        }
        Ok(content)
    }
}

impl<R: io::Read> io::Read for RrdpDataRead<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
        let res = match self.reader.read(buf) {
            Ok(res) => res,
            Err(err) => {
                self.err = Some(RrdpDataReadError::Read(err));
                return Err(io::Error::other("reading data failed"))
            }
        };
        if let Some(left) = self.left {
            let res64 = match u64::try_from(res) {
                Ok(res) => res,
                Err(_) => {
                    // If the usize doesn’t fit into a u64, things are
                    // definitely way too big.
                    self.left = Some(0);
                    self.err = Some(
                        RrdpDataReadError::LargeObject(self.uri.clone())
                    );
                    return Err(io::Error::other("size limit exceeded"))
                }
            };
            if res64 > left {
                self.left = Some(0);
                self.err = Some(
                    RrdpDataReadError::LargeObject(self.uri.clone())
                );
                Err(io::Error::other("size limit exceeded"))
            }
            else {
                self.left = Some(left - res64);
                Ok(res)
            }
        }
        else {
            Ok(res)
        }
    }
}


//------------ SnapshotReason ------------------------------------------------

/// The reason why a snapshot was used.
#[derive(Clone, Copy, Debug)]
pub enum SnapshotReason {
    /// The respository is new.
    NewRepository,

    /// A new session was encountered.
    NewSession,

    /// The delta set in the notification file is inconsistent.
    BadDeltaSet,

    /// The delta set in the notification file was too large.
    LargeDeltaSet,

    /// At least one delta hash has changed from a previous update.
    DeltaMutation,

    /// A larger-than-supported serial number was encountered.
    LargeSerial,

    /// The local copy is outdated and cannot be updated via deltas.
    OutdatedLocal,

    /// A delta file was conflicting with locally stored data.
    ConflictingDelta,

    /// There were too many deltas to process.
    TooManyDeltas,

    /// The local copy was corrupt.
    CorruptArchive,
}

impl SnapshotReason {
    /// Returns a shorthand code for the reason.
    pub fn code(self) -> &'static str {
        use SnapshotReason::*;

        match self {
            NewRepository => "new-repository",
            NewSession => "new-session",
            BadDeltaSet => "inconsistent-delta-set",
            LargeDeltaSet => "large-delta-set",
            DeltaMutation => "delta-mutation",
            LargeSerial => "large-serial",
            OutdatedLocal => "outdate-local",
            ConflictingDelta => "conflicting-delta",
            TooManyDeltas => "too-many-deltas",
            CorruptArchive => "corrupt-local-copy",
        }
    }
}


//============ Errors ========================================================

//------------ RrdpDataReadError ---------------------------------------------

/// An error happened while reading object data.
///
/// This covers both the case where the maximum allowed file size was
/// exhausted as well as where reading data failed. Neither of them is fatal,
/// so we need to process them separately.
#[derive(Debug)]
enum RrdpDataReadError {
    LargeObject(uri::Rsync),
    Read(io::Error),
}


//------------ HashMismatch --------------------------------------------------

/// The hash of a snapshot or delta didn’t match the expected value.
struct HashMismatch;


//------------ SnapshotError -------------------------------------------------

/// An error happened during snapshot processing.
///
/// This is an internal error type only necessary for error handling during
/// RRDP processing. Values will be logged and converted into failures or
/// negative results as necessary.
#[derive(Debug)]
pub enum SnapshotError {
    Http(reqwest::Error),
    HttpStatus(StatusCode),
    Rrdp(rrdp::ProcessError),
    SessionMismatch {
        expected: Uuid,
        received: Uuid
    },
    SerialMismatch {
        expected: u64,
        received: u64,
    },
    DuplicateObject(uri::Rsync),
    HashMismatch,
    LargeObject(uri::Rsync),
    RunFailed(RunFailed),
}

impl From<reqwest::Error> for SnapshotError {
    fn from(err: reqwest::Error) -> Self {
        SnapshotError::Http(err)
    }
}

impl From<StatusCode> for SnapshotError {
    fn from(code: StatusCode) -> Self {
        SnapshotError::HttpStatus(code)
    }
}

impl From<rrdp::ProcessError> for SnapshotError {
    fn from(err: rrdp::ProcessError) -> Self {
        SnapshotError::Rrdp(err)
    }
}

impl From<io::Error> for SnapshotError {
    fn from(err: io::Error) -> Self {
        SnapshotError::Rrdp(err.into())
    }
}

impl From<RunFailed> for SnapshotError {
    fn from(err: RunFailed) -> Self {
        SnapshotError::RunFailed(err)
    }
}

impl From<RrdpDataReadError> for SnapshotError {
    fn from(err: RrdpDataReadError) -> Self {
        match err {
            RrdpDataReadError::LargeObject(uri) => {
                SnapshotError::LargeObject(uri)
            }
            RrdpDataReadError::Read(err) => {
                SnapshotError::Rrdp(err.into())
            }
        }
    }
}

impl From<HashMismatch> for SnapshotError {
    fn from(_: HashMismatch) -> Self {
        Self::HashMismatch
    }
}

impl fmt::Display for SnapshotError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SnapshotError::Http(ref err) => err.fmt(f),
            SnapshotError::HttpStatus(status) => {
                write!(f, "HTTP {status}")
            }
            SnapshotError::Rrdp(ref err) => err.fmt(f),
            SnapshotError::SessionMismatch { ref expected, ref received } => {
                write!(
                    f,
                    "session ID mismatch (notification_file: {expected}, \
                     snapshot file: {received}"
                )
            }
            SnapshotError::SerialMismatch { ref expected, ref received } => {
                write!(
                    f,
                    "serial number mismatch (notification_file: {expected}, \
                     snapshot file: {received}"
                )
            }
            SnapshotError::DuplicateObject(ref uri) => {
                write!(f, "duplicate object: {uri}")
            }
            SnapshotError::HashMismatch => {
                write!(f, "hash value mismatch")
            }
            SnapshotError::LargeObject(ref uri) => {
                write!(f, "object exceeds size limit: {uri}")
            }
            SnapshotError::RunFailed(_) => Ok(()),
        }
    }
}

impl error::Error for SnapshotError { }


//------------ DeltaError ----------------------------------------------------

/// An error happened during delta processing.
///
/// This is an internal error type only necessary for error handling during
/// RRDP processing. Values will be logged and converted into failures or
/// negative results as necessary.
#[derive(Debug)]
pub enum DeltaError {
    Http(reqwest::Error),
    HttpStatus(StatusCode),
    Rrdp(rrdp::ProcessError),
    SessionMismatch {
        expected: Uuid,
        received: Uuid
    },
    SerialMismatch {
        expected: u64,
        received: u64,
    },
    MissingObject {
        uri: uri::Rsync,
    },
    ObjectAlreadyPresent {
        uri: uri::Rsync,
    },
    ObjectHashMismatch {
        uri: uri::Rsync,
    },
    ObjectRepeated {
        uri: uri::Rsync,
    },
    DeltaHashMismatch,
    LargeObject(uri::Rsync),
    Archive(ArchiveError),
}

impl From<reqwest::Error> for DeltaError {
    fn from(err: reqwest::Error) -> Self {
        DeltaError::Http(err)
    }
}

impl From<StatusCode> for DeltaError {
    fn from(code: StatusCode) -> Self {
        DeltaError::HttpStatus(code)
    }
}

impl From<rrdp::ProcessError> for DeltaError {
    fn from(err: rrdp::ProcessError) -> Self {
        DeltaError::Rrdp(err)
    }
}

impl From<io::Error> for DeltaError {
    fn from(err: io::Error) -> Self {
        DeltaError::Rrdp(err.into())
    }
}

impl From<RrdpDataReadError> for DeltaError {
    fn from(err: RrdpDataReadError) -> Self {
        match err {
            RrdpDataReadError::LargeObject(uri) => {
                DeltaError::LargeObject(uri)
            }
            RrdpDataReadError::Read(err) => {
                DeltaError::Rrdp(err.into())
            }
        }
    }
}

impl From<HashMismatch> for DeltaError {
    fn from(_: HashMismatch) -> Self {
        Self::DeltaHashMismatch
    }
}

impl fmt::Display for DeltaError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DeltaError::Http(ref err) => err.fmt(f),
            DeltaError::HttpStatus(status) => {
                write!(f, "HTTP {status}")
            }
            DeltaError::Rrdp(ref err) => err.fmt(f),
            DeltaError::SessionMismatch { ref expected, ref received } => {
                write!(
                    f,
                    "session ID mismatch (notification_file: {expected}, \
                     snapshot file: {received}"
                )
            }
            DeltaError::SerialMismatch { ref expected, ref received } => {
                write!(
                    f,
                    "serial number mismatch (notification_file: {expected}, \
                     snapshot file: {received}"
                )
            }
            DeltaError::MissingObject { ref uri } => {
                write!(
                    f,
                    "reference to missing object {uri}"
                )
            }
            DeltaError::ObjectAlreadyPresent { ref uri } => {
                write!(
                    f,
                    "attempt to add already present object {uri}"
                )
            }
            DeltaError::ObjectHashMismatch { ref uri } => {
                write!(
                    f,
                    "local object {uri} has different hash"
                )
            }
            DeltaError::ObjectRepeated { ref uri } => {
                write!(f, "object appears multiple times: {uri}")
            }
            DeltaError::LargeObject(ref uri) => {
                write!(f, "object exceeds size limit: {uri}")
            }
            DeltaError::DeltaHashMismatch => {
                write!(f, "delta file hash value mismatch")
            }
            DeltaError::Archive(ref err) => {
                write!(f, "archive error: {err}")
            }
        }
    }
}

impl error::Error for DeltaError { }