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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
//! Support for RFC 8181 Publication Messages

use std::fmt;
use std::io;
use std::str::FromStr;
use std::sync::Arc;

use bytes::Bytes;
use log::error;
use serde::{
    Deserialize, Deserializer, Serialize, Serializer
};

use crate::crypto::PublicKey;
use crate::repository::Cert;
use crate::repository::Crl;
use crate::repository::Manifest;
use crate::repository::Roa;
use crate::repository::aspa::Aspa;
use crate::crypto::Signer;
use crate::crypto::SigningError;
use crate::repository::error::ValidationError;
use crate::repository::x509::{Time, Validity};
use crate::rrdp;
use crate::uri;
use crate::util::base64;
use crate::xml;
use crate::xml::decode::{
    Content, Error as XmlError
};
use crate::xml::encode;

use super::sigmsg::SignedMessage;

// Constants for the RFC 8183 XML
const VERSION: &str = "4";
const NS: &[u8] = b"http://www.hactrn.net/uris/rpki/publication-spec/";

const MSG: &[u8] = b"msg";
const LIST: &[u8] = b"list";
const SUCCESS: &[u8] = b"success";
const PUBLISH: &[u8] = b"publish";
const WITHDRAW: &[u8] = b"withdraw";
const REPORT_ERROR: &[u8] = b"report_error";
const ERROR_TEXT: &[u8] = b"error_text";
const FAILED_PDU: &[u8] = b"failed_pdu";

// Content-type for HTTP(s) exchanges
pub const CONTENT_TYPE: &str = "application/rpki-publication";

//------------ PublicationCms ------------------------------------------------

// This type represents a created, or parsed, RFC 8181 CMS object.
#[derive(Clone, Debug)]
pub struct PublicationCms {
    signed_msg: SignedMessage,
    message: Message,
}

impl PublicationCms {
    /// Creates a publication CMS for the given content and signing (ID) key.
    /// This will use a validity time of five minutes before and after 'now'
    /// in order to allow for some NTP drift as well as processing delay
    /// between generating this CMS, sending it, and letting the receiver
    /// validate it.
    pub fn create<S: Signer>(
        message: Message,
        issuing_key_id: &S::KeyId,
        signer: &S,
    ) -> Result<Self, SigningError<S::Error>> {
        let data = message.to_xml_bytes();
        let validity = Validity::new(
            Time::five_minutes_ago(),
            Time::five_minutes_from_now()
        );

        let signed_msg = SignedMessage::create(
            data,
            validity,
            issuing_key_id,
            signer
        )?;

        Ok(PublicationCms { signed_msg, message})
    }

    /// Unpack into its SignedMessage and Message
    pub fn unpack(self) -> (SignedMessage, Message) {
        (self.signed_msg, self.message)
    }

    pub fn into_message(self) -> Message {
        self.message
    }

    /// Encode this to Bytes
    pub fn to_bytes(&self) -> Bytes {
        self.signed_msg.to_captured().into_bytes()
    }

    /// Decodes the CMS and enclosed publication Message from the source.
    pub fn decode(
        bytes: &[u8]
    ) -> Result<Self, Error> {
        let signed_msg = SignedMessage::decode(bytes, false)
            .map_err(|e| Error::CmsDecode(e.to_string()))?;

        let content = signed_msg.content().to_bytes();
        let message = Message::decode(content.as_ref())?;

        Ok(PublicationCms { signed_msg, message })
    }

    pub fn validate(&self, issuer_key: &PublicKey) -> Result<(), Error> {
        self.signed_msg.validate(issuer_key).map_err(|e| e.into())
    }

    pub fn validate_at(
        &self, issuer_key: &PublicKey, when: Time
    ) -> Result<(), Error> {
        self.signed_msg.validate_at(issuer_key, when).map_err(|e| e.into())
    }
}


//------------ Message -------------------------------------------------------

/// This type represents all Publication Messages defined in RFC8181
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Message {
    Query(Query),
    Reply(Reply),
}

/// Constructing
///
impl Message {
    pub fn list_query() -> Self {
        Message::Query(Query::List)
    }

    pub fn list_reply(reply: ListReply) -> Self {
        Message::Reply(Reply::List(reply))
    }

    pub fn delta(delta: PublishDelta) -> Self {
        Message::Query(Query::Delta(delta))
    }

    pub fn success() -> Self {
        Message::Reply(Reply::Success)
    }

    pub fn error(error: ErrorReply) -> Self {
        Message::Reply(Reply::ErrorReply(error))
    }
}

/// # Access
/// 
impl Message {
    pub fn as_reply(self) -> Result<Reply, Error> {
        match self {
            Message::Query(_) => Err(Error::NotReply),
            Message::Reply(reply) => Ok(reply)
        }
    }

    pub fn as_query(self) -> Result<Query, Error> {
        match self {
            Message::Query(query) => Ok(query),
            Message::Reply(_) => Err(Error::NotQuery),
        }
    }
}

/// # Encoding to XML
/// 
impl Message {
    /// Writes the Message's XML representation.
    pub fn write_xml(
        &self, writer: &mut impl io::Write
    ) -> Result<(), io::Error> {
        let mut writer = xml::encode::Writer::new(writer);

        let type_value = match self {
            Message::Query(_) => "query",
            Message::Reply(_) => "reply",
        };

        writer.element(MSG.into())?
            .attr("xmlns", NS)?
            .attr("version", VERSION)?
            .attr("type", type_value)?
            .content(|content|{
                match self {
                    Message::Query(msg) => msg.write_xml(content),
                    Message::Reply(msg) => msg.write_xml(content)
                }
            })?;
        writer.done()
    }

    /// Writes the Message's XML representation to a new String.
    pub fn to_xml_string(&self) -> String {
        let bytes = self.to_xml_bytes();
        
        std::str::from_utf8(&bytes)
            .unwrap() // safe
            .to_string()
    }

    /// Writes the Message's XML representation to a new Bytes
    pub fn to_xml_bytes(&self) -> Bytes {
        let mut vec = vec![];
        self.write_xml(&mut vec).unwrap(); // safe
        
        Bytes::from(vec)
    }
}

/// # Decoding from XML
/// 
impl Message {
    /// Parses an RFC 8181 <msg />
    pub fn decode<R: io::BufRead>(reader: R) -> Result<Self, Error> {
        let mut reader = xml::decode::Reader::new(reader);

        let mut kind: Option<MessageKind> = None;

        let mut outer = reader.start(|element| {
            if element.name().local() != MSG {
                return Err(XmlError::Malformed)
            }
            
            element.attributes(|name, value| match name {
                b"version" => {
                    if value.ascii_into::<String>()? != VERSION {
                        return Err(XmlError::Malformed)
                    }
                    Ok(())
                }
                b"type" => {
                    kind = Some(match value.ascii_into::<String>()?.as_str() {
                        "query" => Ok(MessageKind::Query),
                        "reply" => Ok(MessageKind::Reply),
                        _ => Err(XmlError::Malformed)
                    }?);
                    Ok(())
                }
                _ => Err(XmlError::Malformed)
            })
        })?;

        // Dispatch to message kind for content parsing
        let msg = match kind.ok_or(XmlError::Malformed)? {
            MessageKind::Query => Message::Query(
                Query::decode(&mut outer, &mut reader)?
            ),
            MessageKind::Reply => Message::Reply(
                Reply::decode(&mut outer, &mut reader)?
            )
        };

        // Check that there is no additional stuff
        outer.take_end(&mut reader)?;
        reader.end()?;

        Ok(msg)
    }
}


//------------ MessageKind ---------------------------------------------------

/// This type represents all Publication Messages defined in RFC8181
#[derive(Clone, Debug, Eq, PartialEq)]
enum MessageKind {
    Query,
    Reply
}

//------------ QueryMessage --------------------------------------------------

/// This type represents query type Publication Messages defined in RFC8181
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Query {
    List,
    Delta(PublishDelta),
}


/// # Decoding from XML
/// 
impl Query {
    /// Decodes the content of an RFC 8181 query type message
    //
    // See https://datatracker.ietf.org/doc/html/rfc8181#section-2.1
    //
    // The content of a 'query' type 'msg' can be zero or more PDUs
    // of the following types:
    //  - <list />
    //  - <publish />
    //  - <withdraw />
    //
    // If this is a 'list' type query then there MUST be one only one PDU
    // present - of type <list />. This cannot me mixed with other types.
    //
    // If this is a 'publication/withdraw' type query then there can be zero
    // PDUs (although it would not make sense to send an empty update, this is
    // allowed), or 1 for a single change, or many for a multi-element query,
    // i.e. an atomic delta. All PDUs must be of type <publish /> or
    // <withdraw />.
    //
    // So, in short we need to do a bit of probing below to figure out which
    // kind of query we're actually dealing with.
    fn decode<R: io::BufRead>(
        content: &mut Content,
        reader: &mut xml::decode::Reader<R>,
    ) -> Result<Self, Error> {
        
        // First parse *all* PDUs, then we can decide what query type we had
        let mut pdus: Vec<QueryPdu> = vec![];
        loop {

            match QueryPdu::decode_opt(content, reader)? {
                None => break,
                Some(pdu) => {
                    if !pdus.is_empty() && pdu == QueryPdu::List {
                        error!("Found list pdu in multi-element query");
                        return Err(Error::XmlError(XmlError::Malformed));
                    }
                    pdus.push(pdu);
                }
            }
        }

        if pdus.first() == Some(&QueryPdu::List) {
            Ok(Query::List)
        } else {
            let mut delta = PublishDelta::default();
            for pdu in pdus.into_iter() {
                match pdu {
                    QueryPdu::List => {} // should be unreachable,
                    QueryPdu::PublishDeltaElement(el) => delta.0.push(el)
                }
            }
            Ok(Query::Delta(delta))
        }
    }
}


/// # Encoding to XML
/// 
impl Query {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        match self {
            Query::List => {
                content.element(LIST.into())?;
            },
            Query::Delta(delta) => {
                for el in &delta.0 {
                    el.write_xml(content)?;
                }
            }
        }

        Ok(())
    }
}


//------------ QueryPduType --------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum QueryPduType {
    List,
    Publish,
    Withdraw,
}

//------------ QueryPdu ------------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum QueryPdu {
    List,
    PublishDeltaElement(PublishDeltaElement)
}

impl QueryPdu {
    // Decodes an optional query PDU
    fn decode_opt<R: io::BufRead>(
        content: &mut Content,
        reader: &mut xml::decode::Reader<R>,
    ) -> Result<Option<Self>, Error> {
        let mut pdu_type = None;

        // We need to do a two step analysis of elements. First we need
        // to determine which type of element we are dealing with, and
        // then we can evaluate the content. For <publish /> and
        // <withdraw /> elements we will need to parse information from
        // the element attributes *before* we can use the reader and
        // inspect the content of a <publish /> element.

        // possible attributes
        let mut tag: Option<String> = None;
        let mut uri: Option<uri::Rsync> = None;
        let mut hash: Option<rrdp::Hash> = None;

        let pdu_element = content.take_opt_element(reader, |element| {
            // Determine the PDU type
            pdu_type = Some(match element.name().local() {
                LIST => Ok(QueryPduType::List),
                PUBLISH => Ok(QueryPduType::Publish),
                WITHDRAW => Ok(QueryPduType::Withdraw),
                _ => Err(XmlError::Malformed)
            }?);

            // parse element attributes - we treat them as optional
            // at this point so it does not matter that not all attributes
            // are applicable to all element types.
            element.attributes(|name, value| match name {
                b"tag" => {
                    tag = Some(value.ascii_into()?);
                    Ok(())
                }
                b"hash" => {
                    let hex: String = value.ascii_into()?;
                    if let Ok(hash_value) =rrdp::Hash::from_str(&hex) {
                        hash = Some(hash_value);
                        Ok(())
                    } else {
                        Err(XmlError::Malformed)
                    }
                }
                b"uri" => {
                    uri = Some(value.ascii_into()?);
                    Ok(())
                }
                _ => {
                    Err(XmlError::Malformed)
                }
            })

        })?;

        // Break out of loop if we got no element, get the
        // actual element if we can.
        let mut pdu_element = match pdu_element {
            Some(inner) => inner,
            None => return Ok(None)
        };
        
        // We had an element so we can unwrap the type.
        let pdu_type = pdu_type.unwrap(); 

        
        let pdu: Result<QueryPdu, Error> = match pdu_type {
            QueryPduType::List => {
                Ok(QueryPdu::List)
            },
            QueryPduType::Publish => {
                let uri = uri.ok_or(XmlError::Malformed)?;
                
                // even though we store the base64 as [`Base64`] which
                // uses an inner `Arc<str>`, we decode it first to ensure
                // that it can be parsed.
                let bytes = pdu_element.take_text(reader, |text| {
                    text.base64_decode()
                })?;
                
                let content = Base64::from_content(&bytes);
                
                match hash {
                    None => {
                        Ok(QueryPdu::PublishDeltaElement(
                            PublishDeltaElement::Publish(
                                Publish {
                                    tag,
                                    uri,
                                    content,
                                }
                            )
                        ))
                    },
                    Some(hash) => {
                        Ok(QueryPdu::PublishDeltaElement(
                            PublishDeltaElement::Update(
                                Update {
                                    tag,
                                    uri,
                                    content,
                                    hash,
                                }
                            )
                        ))
                    }
                }
            }
            QueryPduType::Withdraw => {
                let uri = uri.ok_or(XmlError::Malformed)?;
                let hash = hash.ok_or(XmlError::Malformed)?;

                Ok(QueryPdu::PublishDeltaElement(
                    PublishDeltaElement::Withdraw(
                        Withdraw { tag, uri, hash }
                    )
                ))
            }
        };

        let pdu = pdu?;

        pdu_element.take_end(reader)?;

        Ok(Some(pdu))
    }

    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        match self {
            QueryPdu::List => {
                content.element(LIST.into())?;
                Ok(())
            }
            QueryPdu::PublishDeltaElement(el) => el.write_xml(content)
        }
    }

}


//------------ PublishDelta ------------------------------------------------

/// This type represents a multi element query as described in
/// https://tools.ietf.org/html/rfc8181#section-3.7
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct PublishDelta(Vec<PublishDeltaElement>);

impl PublishDelta {
    pub fn empty() -> Self {
        Self::default()
    }

    pub fn add_publish(&mut self, publish: Publish) {
        self.0.push(PublishDeltaElement::Publish(publish));
    }

    pub fn add_update(&mut self, update: Update) {
        self.0.push(PublishDeltaElement::Update(update));
    }

    pub fn add_withdraw(&mut self, withdraw: Withdraw) {
        self.0.push(PublishDeltaElement::Withdraw(withdraw));
    }

    pub fn into_elements(self) -> Vec<PublishDeltaElement> {
        self.0
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }
    
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl std::ops::Add for PublishDelta {
    
    type Output = PublishDelta;

    fn add(mut self, mut other: Self) -> Self::Output {
        self.0.append(&mut other.0);
        self
    }
}


//------------ PublishDeltaElement -------------------------------------------

/// Represents the available options for publish elements that can occur in
/// a delta.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum PublishDeltaElement {
    Publish(Publish),
    Update(Update),
    Withdraw(Withdraw),
}

/// # Encode to XML
/// 
impl PublishDeltaElement {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        match self {
            PublishDeltaElement::Publish(p) => p.write_xml(content),
            PublishDeltaElement::Update(u) => u.write_xml(content),
            PublishDeltaElement::Withdraw(w) => w.write_xml(content)
        }
    }
}

//------------ Publish -------------------------------------------------------

/// Represents a publish element, that does not update any existing object.
/// See: https://tools.ietf.org/html/rfc8181#section-3.1
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Publish {
    tag: Option<String>,
    uri: uri::Rsync,
    content: Base64,
}

/// # Data and Access
/// 
impl Publish {
    pub fn new(
        tag: Option<String>,
        uri: uri::Rsync,
        content: Base64
    ) -> Self {
        Publish { tag, uri, content }
    }

    pub fn with_hash_tag(uri: uri::Rsync, content: Base64) -> Self {
        let tag = Some(content.to_hash().to_string());
        Publish { tag, uri, content }
    }

    pub fn tag(&self) -> Option<&String> {
        self.tag.as_ref()
    }

    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }

    pub fn content(&self) -> &Base64 {
        &self.content
    }

    pub fn unpack(self) -> (Option<String>, uri::Rsync, Base64) {
        (self.tag, self.uri, self.content)
    }
}

/// # Encode to XML
/// 
impl Publish {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        content
            .element(PUBLISH.into())?
            .attr("tag", self.tag_for_xml())?
            .attr("uri", &self.uri)?
            .content(|content| content.raw(&self.content))?;

        Ok(())
    }

    fn tag_for_xml(&self) -> &str {
        self.tag.as_deref().unwrap_or("")
    }
}


//------------ Update --------------------------------------------------------

/// Represents a publish element, that replaces an existing object.
/// See: https://tools.ietf.org/html/rfc8181#section-3.2
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Update {
    tag: Option<String>,
    uri: uri::Rsync,
    content: Base64,
    hash: rrdp::Hash,
}

/// # Data and Access
/// 
impl Update {
    pub fn new(
        tag: Option<String>,
        uri: uri::Rsync,
        content: Base64,
        old_hash: rrdp::Hash
    ) -> Self {
        Update {
            tag,
            uri,
            content,
            hash: old_hash,
        }
    }

    pub fn with_hash_tag(
        uri: uri::Rsync,
        content: Base64,
        old_hash: rrdp::Hash
    ) -> Self {
        let tag = Some(content.to_hash().to_string());
        Update {
            tag,
            uri,
            content,
            hash: old_hash,
        }
    }

    pub fn tag(&self) -> Option<&String> {
        self.tag.as_ref()
    }

    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }

    pub fn content(&self) -> &Base64 {
        &self.content
    }

    pub fn hash(&self) -> &rrdp::Hash {
        &self.hash
    }

    pub fn unpack(self) -> (Option<String>, uri::Rsync, Base64, rrdp::Hash) {
        (self.tag, self.uri, self.content, self.hash)
    }
}

/// # Encode to XML
/// 
impl Update {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        content
            .element(PUBLISH.into())?
            .attr("tag", self.tag_for_xml())?
            .attr("uri", &self.uri)?
            .attr("hash", &self.hash)?
            .content(|content| content.raw(&self.content))?;

        Ok(())
    }

    fn tag_for_xml(&self) -> &str {
        self.tag.as_deref().unwrap_or("")
    }
}


//------------ Withdraw ------------------------------------------------------

/// Represents a withdraw element that removes an object.
/// See: https://tools.ietf.org/html/rfc8181#section-3.3
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Withdraw {
    tag: Option<String>,
    uri: uri::Rsync,
    hash: rrdp::Hash,
}

/// # Data and Access
/// 
impl Withdraw {
    pub fn new(tag: Option<String>, uri: uri::Rsync, hash: rrdp::Hash) -> Self {
        Withdraw { tag, uri, hash }
    }

    pub fn with_hash_tag(uri: uri::Rsync, hash: rrdp::Hash) -> Self {
        let tag = Some(hash.to_string());
        Withdraw { tag, uri, hash }
    }

    pub fn tag(&self) -> Option<&String> {
        self.tag.as_ref()

    }
    
    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }

    pub fn hash(&self) -> &rrdp::Hash {
        &self.hash
    }

    pub fn unpack(self) -> (Option<String>, uri::Rsync, rrdp::Hash) {
        (self.tag, self.uri, self.hash)
    }
}

/// # Encode to XML
/// 
impl Withdraw {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        content.element(WITHDRAW.into())?
            .attr("tag", self.tag_for_xml())?
            .attr("uri", &self.uri)?
            .attr("hash", &self.hash)?;
        
        Ok(())
    }


    fn tag_for_xml(&self) -> &str {
        self.tag.as_deref().unwrap_or("")
    }
}


//------------ ReplyMessage --------------------------------------------------

/// This type represents query type Publication Messages defined in RFC8181
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Reply {
    List(ListReply),
    Success,
    ErrorReply(ErrorReply),
}

impl Reply {
    /// Decoded the content of an RFC 8181 reply type message.
    //
    // See https://datatracker.ietf.org/doc/html/rfc8181#section-2.1
    //
    // The content of a 'reply' type 'msg' can be zero or more PDUs
    // of the following types:
    //  - <list />
    //  - <success />
    //  - <report_error />
    //
    // If this is a 'success' type reply then there MUST be one only one PDU
    // present - of type <success />.
    //
    // If this is a 'report_error' type reply then there MUST be one or more
    // PDU presents - of type <report_error />. There can be no other PDU
    // types.
    //
    // If this is a 'list' type reply then there can be zero or more <list />
    // PDUs for each currently published object. There can be no other PDU
    // types.
    //
    // So, in short we need to do a bit of probing of elements to figure out
    // which kind of reply we're actually dealing with. We need to parse ALL
    // PDUs and then figure out if the message was correct at all, and which
    // type it is.
    fn decode<R: io::BufRead>(
        content: &mut Content,
        reader: &mut xml::decode::Reader<R>,
    ) -> Result<Self, Error> {
        
        // First parse *all* PDUs, then we can decide what reply type we had
        let mut pdus: Vec<ReplyPdu> = vec![];
        loop {
            let mut pdu_type = None;

            // We need to do a two step analysis of elements. First we need
            // to determine which type of element we are dealing with, and
            // then we can evaluate the content. For <list /> and
            // <error_report /> elements we will need to parse information
            // from the element attributes. We need to do this *before* we
            // can use the reader to inspect the content of an element.

            // possible attributes
            let mut uri: Option<uri::Rsync> = None;
            let mut hash: Option<rrdp::Hash> = None;
            let mut tag: Option<String> = None;
            let mut error_code: Option<ReportErrorCode> = None;

            let pdu_element = content.take_opt_element(reader, |element| {
                // Determine the PDU type
                pdu_type = Some(match element.name().local() {
                    LIST => Ok(ReplyPduType::List),
                    SUCCESS => Ok(ReplyPduType::Success),
                    REPORT_ERROR => Ok(ReplyPduType::Error),
                    _ => Err(XmlError::Malformed)
                }?);

                // parse element attributes - we treat them as optional
                // at this point so it does not matter that not all attributes
                // are applicable to all element types.
                element.attributes(|name, value| match name {
                    b"hash" => {
                        let hex: String = value.ascii_into()?;
                        if let Ok(hash_value) =rrdp::Hash::from_str(&hex) {
                            hash = Some(hash_value);
                            Ok(())
                        } else {
                            Err(XmlError::Malformed)
                        }
                    }
                    b"uri" => {
                        uri = Some(value.ascii_into()?);
                        Ok(())
                    }
                    b"tag" => {
                        tag = Some(value.ascii_into()?);
                        Ok(())
                    }
                    b"error_code" => {
                        // let error_code_str = value.ascii_into()?;
                        error_code = Some(value.ascii_into()?);
                        Ok(())
                    }
                    _ => {
                        Err(XmlError::Malformed)
                    }
                })
            })?;

            // Break out of loop if we got no element, get the
            // actual element if we can.
            let mut pdu_element = match pdu_element {
                Some(inner) => inner,
                None => break
            };
            
            // We had an element so we can unwrap the type.
            let pdu_type = pdu_type.unwrap(); 

            match pdu_type {
                ReplyPduType::List => {
                    let uri = uri.ok_or(XmlError::Malformed)?;
                    let hash = hash.ok_or(XmlError::Malformed)?;

                    pdus.push(ReplyPdu::List(ListElement { uri, hash } ));
                }
                ReplyPduType::Success => {
                    if pdus.is_empty() {
                        pdus.push(ReplyPdu::Success)
                    } else {
                        error!("Found success pdu in multi-element reply");
                        return Err(Error::XmlError(XmlError::Malformed))
                    }
                }
                ReplyPduType::Error => {
                    if pdus.iter().any(|existing| {
                        existing.kind() != ReplyPduType::Error
                    }) {
                        error!("Found error report in non-error reply");
                        return Err(Error::XmlError(XmlError::Malformed));
                    } else {
                        let error = ReportError::decode_inner(
                            error_code.ok_or(XmlError::Malformed)?,
                            tag,
                            &mut pdu_element,
                            reader
                        )?;
                        
                        pdus.push(ReplyPdu::Error(error));
                    }
                }
            }

            // close the processed PDU
            pdu_element.take_end(reader)?;
        }

        let reply_kind = match pdus.first() {
            Some(el) => el.kind(),
            None => ReplyPduType::List
        };

        match reply_kind {
            ReplyPduType::Success => Ok(Reply::Success),
            ReplyPduType::List => {
                let mut list = ListReply::default();
                for pdu in pdus.into_iter() {
                    if let ReplyPdu::List(el) = pdu {
                        list.elements.push(el);
                    }
                }
                Ok(Reply::List(list))
            }
            ReplyPduType::Error => {
                let mut errors  = ErrorReply::default();
                for pdu in pdus.into_iter() {
                    if let ReplyPdu::Error(err) = pdu {
                        errors.errors.push(err);
                    }
                }
                Ok(Reply::ErrorReply(errors))
            }
        }
    }
}

/// # Encode to XML
/// 
impl Reply {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        match self {
            Reply::List(list) => {
                for el in &list.elements {
                    el.write_xml(content)?;
                }
            }
            Reply::Success => {
                content.element(SUCCESS.into())?;
            }
            Reply::ErrorReply(errors) => {
                for err in &errors.errors {
                    err.write_xml(content)?;
                }
            }
        }
        Ok(())
    }
}

//------------ ReplyPduType --------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReplyPduType {
    List,
    Success,
    Error,
}


//------------ ReplyPdu ------------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReplyPdu {
    List(ListElement),
    Success,
    Error(ReportError),
}

impl ReplyPdu {
    fn kind(&self) -> ReplyPduType {
        match self {
            ReplyPdu::List(_) => ReplyPduType::List,
            ReplyPdu::Success => ReplyPduType::Success,
            ReplyPdu::Error(_) => ReplyPduType::Error
        }
    }
}


//------------ ListReply -----------------------------------------------------

/// This type represents the list reply as described in
/// https://tools.ietf.org/html/rfc8181#section-2.3
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ListReply {
    elements: Vec<ListElement>,
}

impl ListReply {
    pub fn empty() -> Self {
        Self::default()
    }

    pub fn new(elements: Vec<ListElement>) -> Self {
        ListReply { elements }
    }

    pub fn add_element(&mut self, element: ListElement) {
        self.elements.push(element);
    }

    pub fn elements(&self) -> &Vec<ListElement> {
        &self.elements
    }

    pub fn into_elements(self) -> Vec<ListElement> {
        self.elements
    }

    pub fn into_withdraw_delta(self) -> PublishDelta {
        let mut delta = PublishDelta::empty();

        for el in self.elements.into_iter() {
            let (uri, hash) = el.unpack();
            let withdraw = Withdraw::with_hash_tag(uri, hash);
            delta.add_withdraw(withdraw);

        }

        delta
    }
}


//------------ ListElement ---------------------------------------------------

/// This type represents a single object that is published at a publication
/// server.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ListElement {
    uri: uri::Rsync,
    hash: rrdp::Hash,
}

/// # Data and Access
/// 
impl ListElement {
    pub fn new(
        uri: uri::Rsync,
        hash: rrdp::Hash
    ) -> Self {
        ListElement { uri, hash }
    }

    pub fn uri(&self) -> &uri::Rsync {
        &self.uri
    }

    pub fn hash(&self) -> &rrdp::Hash {
        &self.hash
    }

    pub fn unpack(self) -> (uri::Rsync, rrdp::Hash) {
        (self.uri, self.hash)
    }
}

/// # Encoding to XML
/// 
impl ListElement {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        content
            .element(LIST.into())?
            .attr("uri", &self.uri)?
            .attr("hash", &self.hash)?;

        Ok(())
    }
}

//------------ ErrorReply ----------------------------------------------------

/// This type represents the error report as described in
/// https://tools.ietf.org/html/rfc8181#section-3.5 and 3.6
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ErrorReply {
    errors: Vec<ReportError>,
}

/// # Data and Access
/// 
impl ErrorReply {
    pub fn empty() -> Self {
        Self::default()
    }

    pub fn for_error(error: ReportError) -> Self {
        ErrorReply { errors: vec![error] }
    }

    pub fn add_error(&mut self, error: ReportError) {
        self.errors.push(error)
    }

    pub fn errors(&self) -> &Vec<ReportError> {
        &self.errors
    }
}

impl fmt::Display for ErrorReply {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "error reply including: ")?;
        for err in &self.errors {
            match &err.error_text {
                None => write!(f, "error code: {} ", err.error_code)?,
                Some(text) => write!(f, "error code: {}, text: {} ", err.error_code, text)?,
            }
        }
        Ok(())
    }
}

//------------ ReportError ---------------------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReportError {
    error_code: ReportErrorCode,
    tag: Option<String>,
    error_text: Option<String>,
    failed_pdu: Option<QueryPdu>,
}

/// # Construct
/// 
impl ReportError {

    /// Creates an entry to include in an ErrorReply.
    pub fn with_code(
        error_code: ReportErrorCode,
    ) -> Self {
        let error_text = Some(error_code.to_text().to_string());

        ReportError {
            error_code,
            tag: None,
            error_text,
            failed_pdu: None,
        }
    }
}

/// # Encode to XML
/// 
impl ReportError {
    fn write_xml<W: io::Write>(
        &self,
        content: &mut encode::Content<W>
    ) -> Result<(), io::Error> {
        content
            .element(REPORT_ERROR.into())?
            .attr("error_code", &self.error_code)?
            .attr_opt("tag", self.tag.as_ref())?
            .content(|content| {
                content
                    .element(ERROR_TEXT.into())?
                    .content(|error_text_content|
                        error_text_content.raw(self.error_text_or_default())
                    )?;

                content
                    .element_opt(
                        self.failed_pdu.as_ref(),
                        FAILED_PDU.into(),
                        |pdu, el| {
                            el.content(|content| pdu.write_xml(content))?;
                            Ok(())
                        }
                    )?;
                
                Ok(())
            })?;

        Ok(())
    }

    fn error_text_or_default(&self) -> &str {
        self.error_text.as_deref()
                .unwrap_or_else(|| self.error_code.to_text())
    }
}

/// Decode from XML support
/// 
impl ReportError {
    /// Decodes the inner elements nested inside <report_error>.
    // 
    // Expects the error_code and tag to be supplied because those are
    // attributes on the <report_error> element.
    fn decode_inner<R: io::BufRead>(
        error_code: ReportErrorCode,
        tag: Option<String>,
        report_error_element: &mut Content,
        reader: &mut xml::decode::Reader<R>,
    ) -> Result<Self, Error> {
        let mut error_text: Option<String> = None;
        let mut failed_pdu: Option<QueryPdu> = None;
        
        // if only we could look ahead to see if/what elements
        // are present then this would be easier..
        loop {
            let mut error_text_found = false;
            let mut failed_pdu_found = false;
            
            let error_element = report_error_element.take_opt_element(
                reader,
                |error_element| {
                    match error_element.name().local() {
                        ERROR_TEXT => {
                            error_text_found = true;
                            Ok(())
                        }
                        FAILED_PDU => {
                            failed_pdu_found = true;
                            Ok(())
                        }
                        _ => {
                            Err(XmlError::Malformed)
                        }
                    }
                }
            )?;
            
            // get the element, break if there was none
            let mut el = match error_element {
                Some(el) => el,
                None => break
            };
            
            if error_text_found {
                let text = el.take_text( reader, |text| {
                    text.to_ascii().map(|t| t.to_string())
                })?;
                
                error_text = Some(text);
            }
            
            if failed_pdu_found {
                failed_pdu = QueryPdu::decode_opt(&mut el, reader)?;
            }

            // close element
            el.take_end(reader)?;
        }

        Ok(ReportError { error_code, tag, error_text, failed_pdu })
    }
}

//------------ ReportErrorCodes ----------------------------------------------

/// The allowed error codes defined in RFC8181 section 2.5
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReportErrorCode {
    XmlError,
    PermissionFailure,
    BadCmsSignature,
    ObjectAlreadyPresent,
    NoObjectPresent,
    NoObjectMatchingHash,
    ConsistencyProblem,
    OtherError,
}

impl fmt::Display for ReportErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ReportErrorCode::XmlError => write!(f, "xml_error"),
            ReportErrorCode::PermissionFailure => write!(f, "permission_failure"),
            ReportErrorCode::BadCmsSignature => write!(f, "bad_cms_signature"),
            ReportErrorCode::ObjectAlreadyPresent => write!(f, "object_already_present"),
            ReportErrorCode::NoObjectPresent => write!(f, "no_object_present"),
            ReportErrorCode::NoObjectMatchingHash => write!(f, "no_object_matching_hash"),
            ReportErrorCode::ConsistencyProblem => write!(f, "consistency_problem"),
            ReportErrorCode::OtherError => write!(f, "other_error"),
        }
    }
}

impl FromStr for ReportErrorCode {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "xml_error" => Ok(ReportErrorCode::XmlError),
            "permission_failure" => Ok(ReportErrorCode::PermissionFailure),
            "bad_cms_signature" => Ok(ReportErrorCode::BadCmsSignature),
            "object_already_present" => Ok(ReportErrorCode::ObjectAlreadyPresent),
            "no_object_present" => Ok(ReportErrorCode::NoObjectPresent),
            "no_object_matching_hash" => Ok(ReportErrorCode::NoObjectMatchingHash),
            "consistency_problem" => Ok(ReportErrorCode::ConsistencyProblem),
            "other_error" => Ok(ReportErrorCode::OtherError),
            _ => Err(Error::InvalidErrorCode(s.to_string())),
        }
    }
}

impl ReportErrorCode {
    /// Provides default texts for error codes (taken from RFC).
    fn to_text(&self) -> &str {
        match self {
            ReportErrorCode::XmlError => "Encountered an XML problem.",
            ReportErrorCode::PermissionFailure => "Client does not have permission to update this URI.",
            ReportErrorCode::BadCmsSignature => "Encountered bad CMS signature.",
            ReportErrorCode::ObjectAlreadyPresent => "An object is already present at this URI, yet a \"hash\" attribute was not specified.",
            ReportErrorCode::NoObjectPresent => "There is no object present at this URI, yet a \"hash\" attribute was specified.",
            ReportErrorCode::NoObjectMatchingHash => "The \"hash\" attribute supplied does not match the \"hash\" attribute of the object at this URI.",
            ReportErrorCode::ConsistencyProblem => "Server detected an update that looks like it will cause a consistency problem (e.g., an object was deleted, but the manifest was not updated).",
            ReportErrorCode::OtherError => "Found some other issue."
        }
    }
}


//------------ Base64 --------------------------------------------------------

/// This type contains a base64 encoded structure. The publication protocol
/// deals with objects in their base64 encoded form.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Base64(Arc<str>);

impl Base64 {
    pub fn from_content(content: &[u8]) -> Self {
        Base64(base64::Xml.encode(content).into())
    }

    /// Decodes into bytes (e.g. for saving to disk for rsync)
    pub fn to_bytes(&self) -> Bytes {
        Bytes::from(base64::Xml.decode(self.0.as_ref()).unwrap())
    }

    /// Generates the rrdp::Hash for the base64 encoded content
    pub fn to_hash(&self) -> rrdp::Hash {
        rrdp::Hash::from_data(self.to_bytes().as_ref())
    }

    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }

    /// An approximation of the of the size of the encoded bytes.
    /// 
    /// To get the exact number of bytes we would have to decode first,
    /// and this is possibly costly. We should not be far off though..
    pub fn size_approx(&self) -> usize {
        // Each char represents 6 bits, which are use to make 8 bit bytes:
        // - multiply by 6 and divide by 8; or
        // - divide by 8 and multiply by 6; or
        // - divide by 4 and multiply by 3; or
        // - right shift 2 and multiply by 3
        //
        // We can be off by up to 3 bytes this way.
        (self.as_str().len() >> 2) * 3
    }
}

impl fmt::Display for Base64 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Serialize for Base64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.as_str().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Base64 {
    fn deserialize<D>(deserializer: D) -> Result<Base64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        Ok(Base64(string.into()))
    }
}

impl From<&Cert> for Base64 {
    fn from(cert: &Cert) -> Self {
        Base64::from_content(&cert.to_captured().into_bytes())
    }
}

impl From<&Roa> for Base64 {
    fn from(roa: &Roa) -> Self {
        Base64::from_content(&roa.to_captured().into_bytes())
    }
}

impl From<&Aspa> for Base64 {
    fn from(aspa: &Aspa) -> Self {
        Base64::from_content(&aspa.to_captured().into_bytes())
    }
}

impl From<&Manifest> for Base64 {
    fn from(mft: &Manifest) -> Self {
        Base64::from_content(&mft.to_captured().into_bytes())
    }
}

impl From<&Crl> for Base64 {
    fn from(crl: &Crl) -> Self {
        Base64::from_content(&crl.to_captured().into_bytes())
    }
}

//------------ PublicationMessageError ---------------------------------------

#[derive(Debug)]
pub enum Error {
    InvalidVersion,
    XmlError(XmlError),
    InvalidErrorCode(String),
    CmsDecode(String),
    Validation(ValidationError),
    NotQuery,
    NotReply
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::InvalidVersion => write!(f, "Invalid version"),
            Error::XmlError(e) => e.fmt(f),
            Error::InvalidErrorCode(code) => {
                write!(f, "Invalid error code: {}", code)
            }
            Error::CmsDecode(msg) => {
                write!(f, "Could not decode CMS: {}", msg)
            }
            Error::Validation(e) => {
                write!(f, "CMS is not valid: {}", e)
            }
            Error::NotQuery => {
                write!(f, "was not a query message")
            }
            Error::NotReply => {
                write!(f, "was not a reply message")
            }
        }
    }
}

impl From<XmlError> for Error {
    fn from(e: XmlError) -> Self {
        Error::XmlError(e)
    }
}

impl From<ValidationError> for Error {
    fn from(e: ValidationError) -> Self {
        Error::Validation(e)
    }
}

//------------ Tests ---------------------------------------------------------

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn parse_and_encode_list_query() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/list.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_encode_publish_multi_query() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/publish-multi.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_encode_publish_single_query() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/publish-single.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_encode_publish_empty_query() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/publish-empty.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_encode_publish_empty_short_query() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/publish-empty-short.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_list_reply() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/list-reply.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_list_reply_single() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/list-reply-single.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_list_reply_empty() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/list-reply-empty.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_list_reply_empty_short() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/list-reply-empty-short.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_success_reply() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/success-reply.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }

    #[test]
    fn parse_and_error_reply() {
        let xml = include_bytes!("../../test-data/ca/rfc8181/error-reply.xml");
        let msg = Message::decode(xml.as_ref()).unwrap();

        let re_encoded = msg.to_xml_string();
        let re_decoded = Message::decode(re_encoded.as_bytes()).unwrap();

        assert_eq!(msg, re_decoded);
    }
}


#[cfg(all(test, feature="softkeys"))]
mod signer_test {

    use super::*;

    use crate::{
        ca::idcert::IdCert,
        crypto::{softsigner::{OpenSslSigner, KeyId}, PublicKeyFormat}
    };

    fn sign_and_validate_msg(
        signer: &OpenSslSigner,
        signing_key: KeyId,
        validation_key: &PublicKey,
        message: Message
    ) {
        let cms = PublicationCms::create(
            message.clone(),
            &signing_key,
            signer
        ).unwrap();

        let bytes = cms.to_bytes();

        let decoded = PublicationCms::decode(&bytes).unwrap();
        decoded.validate(validation_key).unwrap();

        let decoded_message = decoded.into_message();

        assert_eq!(message, decoded_message);
    }

    fn element(uri: &str, content: &[u8]) -> ListElement {
        let uri = uri::Rsync::from_str(uri).unwrap();
        let hash = Base64::from_content(content).to_hash();

        ListElement::new(uri, hash)
    }

    fn publish(uri: &str, content: &[u8]) -> Publish {
        let uri = uri::Rsync::from_str(uri).unwrap();
        let content = Base64::from_content(content);

        Publish::with_hash_tag(uri, content)
    }

    fn update(uri: &str, content: &[u8], old_content: &[u8]) -> Update {
        let uri = uri::Rsync::from_str(uri).unwrap();
        let content = Base64::from_content(content);

        let hash = Base64::from_content(old_content).to_hash();

        Update::with_hash_tag(uri, content, hash)
    }

    fn withdraw(uri: &str, content: &[u8]) -> Withdraw {
        let uri = uri::Rsync::from_str(uri).unwrap();
        let hash = Base64::from_content(content).to_hash();

        Withdraw::with_hash_tag(uri, hash)
    }

    #[test]
    fn sign_and_validate() {
        let signer = OpenSslSigner::new();

        let key = signer.create_key(PublicKeyFormat::Rsa).unwrap();
        let cert = IdCert::new_ta(
            Validity::from_secs(60),
            &key,
            &signer
        ).unwrap();

        sign_and_validate_msg(&signer, key, cert.public_key(), Message::list_query());

        let mut rpl = ListReply::empty();
        rpl.add_element(element("rsync://localhost/ca/f1.txt", b"a"));
        rpl.add_element(element("rsync://localhost/ca/f2.txt", b"b"));
        rpl.add_element(element("rsync://localhost/ca/f3.txt", b"c"));
        sign_and_validate_msg(&signer, key, cert.public_key(), Message::list_reply(rpl));

        let mut delta = PublishDelta::empty();
        delta.add_publish(publish("rsync://localhost/ca/f1.txt", b"a"));
        delta.add_update(update("rsync://localhost/ca/f2.txt", b"b", b"c"));
        delta.add_withdraw(withdraw("rsync://localhost/ca/f3.txt", b"d"));
        sign_and_validate_msg(&signer, key, cert.public_key(), Message::delta(delta));

        sign_and_validate_msg(&signer, key, cert.public_key(), Message::success());

        let mut error_reply = ErrorReply::empty();
        let error = ReportError::with_code(ReportErrorCode::PermissionFailure);
        error_reply.add_error(error);
        sign_and_validate_msg(&signer, key, cert.public_key(), Message::error(error_reply));
    }

    #[test]
    fn base_64_size() {

        fn random_bytes(size: usize) -> Vec<u8> {
            let mut bytes = [0; 65535];
            openssl::rand::rand_bytes(&mut bytes).unwrap();
            Vec::from(&bytes[0..size])
        }

        let sizes = &[0, 10, 16, 256, 1024, 1025, 12322];

        for size in sizes {
            let buf = random_bytes(*size);
            let base64 = Base64::from_content(&buf);

            assert!(base64.size_approx() - buf.len() < 4);
        }

    }
}