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
//! Reading a message a PEC provider generated: its kind, its certification data and the message it carries.
use mail_parser::{Headers, MessageParser, MessageRef, PartId};
use crate::{
AttachmentCheck, AttachmentHash, CertificationData, Error, Kind, MessageId, MessageKind,
ReceiptKind, TextLineEnds, attachment_hash,
};
/// A receipt, notice or envelope a PEC provider generated, read from its raw bytes.
///
/// The provider's S/MIME signature is not checked here.
#[derive(Debug)]
pub struct Message<'a> {
/// The parsed MIME tree, which owns any transfer-decoded buffer the original message lives in.
parsed: mail_parser::Message<'a>,
/// What the message is.
kind: MessageKind,
/// Whether `X-VerificaSicurezza: errore` is present.
security_error: bool,
/// The length of the subject prefix the kind requires.
prefix_len: usize,
/// The `daticert.xml` attachment, read.
certification: Option<CertificationData>,
/// The `message/rfc822` part holding the original or arrived message.
original: Option<PartId>,
/// This message's `Message-ID`.
id: Option<MessageId>,
/// The `X-Riferimento-Message-ID`.
reference_id: Option<MessageId>,
}
impl<'a> Message<'a> {
/// Reads a message as delivered to a PEC mailbox, allowing an empty original subject.
///
/// # Errors
///
/// Fails when the bytes are not MIME, when no PEC header names a kind or the header names one the rules do
/// not define, when the subject lacks the prefix of its kind (§6.3 to §6.5), when `X-VerificaSicurezza`
/// appears outside the virus notices (§6.4.3), when a certified kind lacks its `daticert.xml` or that file is
/// invalid or names another kind, when an envelope lacks the message it wraps, or when a summary delivery receipt
/// carries one (§6.5.2.3).
pub fn parse(raw: &'a [u8]) -> Result<Self, Error> {
let parsed = MessageParser::default().parse(raw).ok_or(Error::NotMime)?;
let root = parsed.root();
let headers = root.headers();
let kind = kind_of(&headers)?;
let security_error =
header_bytes(&headers, "X-VerificaSicurezza").is_some_and(|value| value == b"errore");
if security_error
&& !matches!(
kind,
MessageKind::Certified(Kind::NonAcceptance | Kind::DeliveryError)
)
{
return Err(Error::UnexpectedSecurityHeader(kind));
}
let prefix = subject_prefix(kind, security_error);
let subject = headers.subject().unwrap_or_default();
if !subject.starts_with(prefix) && subject != prefix.trim_end() {
return Err(Error::SubjectMismatch {
expected: prefix,
subject: subject.to_owned(),
});
}
let mut certification_part = None;
let mut original = None;
for part in root.parts() {
if certification_part.is_none() && part.attachment_name() == Some("daticert.xml") {
certification_part = Some(part);
} else if original.is_none()
&& part.is_message()
&& (kind == MessageKind::Anomaly || part.attachment_name() == Some("postacert.eml"))
{
original = Some(part.id());
}
}
let certification = match kind {
MessageKind::Anomaly => None,
MessageKind::Certified(kind) => {
let part = certification_part.ok_or(Error::MissingCertificationData)?;
let bytes = part.decoded();
let xml = core::str::from_utf8(&bytes).map_err(|_| {
Error::CertificationData("daticert.xml is not UTF-8".to_owned())
})?;
let data = CertificationData::from_xml(xml)?;
if data.kind != kind {
return Err(Error::KindMismatch {
header: kind,
data: data.kind,
});
}
Some(data)
}
};
if original.is_none()
&& matches!(
kind,
MessageKind::Anomaly | MessageKind::Certified(Kind::Transport)
)
{
return Err(Error::MissingOriginal);
}
if original.is_some()
&& kind == MessageKind::Certified(Kind::Delivery)
&& certification
.as_ref()
.is_some_and(|data| data.data.receipt == Some(ReceiptKind::Summary))
{
return Err(Error::OriginalInSummaryReceipt);
}
let id = headers.message_id().and_then(|id| id.parse().ok());
let reference_id = header_bytes(&headers, "X-Riferimento-Message-ID")
.and_then(|value| core::str::from_utf8(value).ok())
.and_then(|value| value.parse().ok());
Ok(Self {
parsed,
kind,
security_error,
prefix_len: prefix.len(),
certification,
original,
id,
reference_id,
})
}
/// What the message is.
#[must_use]
pub const fn kind(&self) -> MessageKind {
self.kind
}
/// Whether the message reports a virus, `X-VerificaSicurezza: errore` (§6.4.3).
#[must_use]
pub const fn security_error(&self) -> bool {
self.security_error
}
/// The possibly empty subject of the original message, without the prefix the provider added.
#[must_use]
pub fn subject(&self) -> &str {
self.parsed
.root()
.headers()
.subject()
.and_then(|subject| subject.get(self.prefix_len..))
.unwrap_or_default()
}
/// The `Message-ID` of this message, `None` when absent or not a valid identifier.
#[must_use]
pub const fn message_id(&self) -> Option<&MessageId> {
self.id.as_ref()
}
/// The `Message-ID` the sender's client gave the original message before its provider replaced it,
/// `X-Riferimento-Message-ID` (§6.3). `None` when absent or not a valid identifier.
#[must_use]
pub const fn reference_message_id(&self) -> Option<&MessageId> {
self.reference_id.as_ref()
}
/// The `daticert.xml` of a receipt, notice or transport envelope. An anomaly envelope has none.
#[must_use]
pub const fn certification_data(&self) -> Option<&CertificationData> {
self.certification.as_ref()
}
/// The raw bytes of the wrapped message: the original message of a transport envelope or of a full or short
/// delivery receipt (`postacert.eml`, §7.3.2), or the arrived message of an anomaly envelope.
#[must_use]
pub fn original_message(&self) -> Option<&[u8]> {
let part = self.parsed.part(self.original?)?;
Some(part.nested()?.raw())
}
/// Identifies a short receipt's generated hashes using the sent message, in receipt order (§6.5.2.2).
///
/// Carried user files are excluded even when their names end in `.hash`.
/// Returns an empty list for other messages or a receipt without an original.
///
/// # Errors
///
/// Returns [`Error::NotMime`] for an invalid sent message or a parser-limited sent or receipt tree, [`Error::InvalidAttachmentHash`] for malformed generated hashes, or [`Error::AmbiguousAttachments`] when equally supported assignments disagree on outcomes or evidence interpretations.
pub fn attachment_hashes(
&self,
sent: &[u8],
line_ends: TextLineEnds,
) -> Result<Vec<AttachmentHash>, Error> {
self.short_original()?.map_or_else(
|| Ok(Vec::new()),
|original| attachment_hash::read(original, sent, line_ends),
)
}
/// Compares a short receipt's attachments against the sent message (§6.5.2.2).
///
/// Exact named matches precede name-only differences, then renamed content is paired by digest.
/// `line_ends` selects the accepted text/message hash forms, while carried bytes must be unchanged.
/// Results follow sent attachment order, followed by unpaired receipt parts.
///
/// # Errors
///
/// Returns [`Error::NotShortReceipt`] without a short receipt's original, [`Error::NotMime`] for an invalid sent message or a parser-limited sent or receipt tree, [`Error::InvalidAttachmentHash`] for malformed generated hashes, or [`Error::AmbiguousAttachments`] when equally supported assignments disagree on outcomes or evidence interpretations.
pub fn check_attachments(
&self,
sent: &[u8],
line_ends: TextLineEnds,
) -> Result<Vec<AttachmentCheck>, Error> {
let original = self.short_original()?.ok_or(Error::NotShortReceipt)?;
attachment_hash::check(original, sent, line_ends)
}
/// The original carried by a short delivery receipt, refused when a MIME parser limit cut the receipt short.
fn short_original(&self) -> Result<Option<MessageRef<'_>>, Error> {
if self.kind != MessageKind::Certified(Kind::Delivery)
|| self
.certification
.as_ref()
.and_then(|certification| certification.data.receipt)
!= Some(ReceiptKind::Short)
{
return Ok(None);
}
if attachment_hash::limit_reached(&self.parsed) {
return Err(Error::NotMime);
}
Ok(self
.original
.and_then(|original| self.parsed.part(original)?.nested()))
}
}
/// The kind named by `X-Ricevuta` or `X-Trasporto`. `posta-certificata` names the transport envelope and travels only
/// in `X-Trasporto`, which otherwise carries `errore` for the anomaly envelope.
fn kind_of(headers: &Headers<'_>) -> Result<MessageKind, Error> {
let text = |name: &str| header_bytes(headers, name).map(String::from_utf8_lossy);
match (text("X-Ricevuta"), text("X-Trasporto")) {
(None, None) => Err(Error::NotPec),
(Some(_), Some(_)) => Err(Error::ConflictingKind),
(Some(value), None) => match value.parse()? {
Kind::Transport => Err(Error::UnknownKind(value.into_owned())),
kind => Ok(MessageKind::Certified(kind)),
},
(None, Some(value)) if value == "errore" => Ok(MessageKind::Anomaly),
(None, Some(value)) => match value.parse()? {
Kind::Transport => Ok(MessageKind::Certified(Kind::Transport)),
_ => Err(Error::UnknownKind(value.into_owned())),
},
}
}
/// The value of the first `name` header without surrounding whitespace, `None` when absent.
fn header_bytes<'m>(headers: &Headers<'m>, name: &str) -> Option<&'m [u8]> {
Some(headers.get(name)?.raw_value().trim_ascii())
}
/// The subject prefix the rules give each kind, `[prefix][subject originale]`.
const fn subject_prefix(kind: MessageKind, security_error: bool) -> &'static str {
match kind {
MessageKind::Anomaly => "ANOMALIA MESSAGGIO: ",
MessageKind::Certified(kind) => match kind {
Kind::Acceptance => "ACCETTAZIONE: ",
Kind::NonAcceptance if security_error => "AVVISO DI NON ACCETTAZIONE PER VIRUS: ",
Kind::NonAcceptance => "AVVISO DI NON ACCETTAZIONE: ",
Kind::TakenInCharge => "PRESA IN CARICO: ",
Kind::Delivery => "CONSEGNA: ",
Kind::Transport => "POSTA CERTIFICATA: ",
Kind::DeliveryError if security_error => "AVVISO DI MANCATA CONSEGNA PER VIRUS: ",
Kind::DeliveryError => "AVVISO DI MANCATA CONSEGNA: ",
Kind::DeliveryTimeoutWarning => "AVVISO DI MANCATA CONSEGNA PER SUP. TEMPO MASSIMO: ",
Kind::VirusDetected => "PROBLEMA DI SICUREZZA: ",
},
}
}