Skip to main content

hickory_proto/op/
message.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Basic protocol message for DNS
9
10use alloc::{boxed::Box, fmt, vec::Vec};
11use core::{iter, mem, ops::Deref};
12
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15#[cfg(feature = "__dnssec")]
16use tracing::debug;
17use tracing::warn;
18
19#[cfg(feature = "__dnssec")]
20use crate::dnssec::{DnssecIter, rdata::DNSSECRData};
21#[cfg(any(feature = "std", feature = "no-std-rand"))]
22use crate::random;
23#[cfg(feature = "__dnssec")]
24use crate::rr::{TSigVerifier, TSigner};
25use crate::{
26    error::{ProtoError, ProtoResult},
27    op::{Edns, Header, HeaderCounts, MessageType, Metadata, OpCode, Query, ResponseCode},
28    rr::{RData, Record, RecordData, RecordType, rdata::TSIG},
29    serialize::binary::{BinDecodable, BinDecoder, BinEncodable, BinEncoder, DecodeError},
30};
31
32/// The basic request and response data structure, used for all DNS protocols.
33///
34/// [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035)
35///
36/// ```text
37/// 4.1. Format
38///
39/// All communications inside of the domain protocol are carried in a single
40/// format called a message.  The top level format of message is divided
41/// into 5 sections (some of which are empty in certain cases) shown below:
42///
43///     +--------------------------+
44///     |        Header            |
45///     +--------------------------+
46///     |  Question / Zone         | the question for the name server
47///     +--------------------------+
48///     |   Answer  / Prerequisite | RRs answering the question
49///     +--------------------------+
50///     | Authority / Update       | RRs pointing toward an authority
51///     +--------------------------+
52///     |      Additional          | RRs holding additional information
53///     +--------------------------+
54///
55/// The header section is always present.  The header includes fields that
56/// specify which of the remaining sections are present, and also specify
57/// whether the message is a query or a response, a standard query or some
58/// other opcode, etc.
59///
60/// The names of the sections after the header are derived from their use in
61/// standard queries.  The question section contains fields that describe a
62/// question to a name server.  These fields are a query type (QTYPE), a
63/// query class (QCLASS), and a query domain name (QNAME).  The last three
64/// sections have the same format: a possibly empty list of concatenated
65/// resource records (RRs).  The answer section contains RRs that answer the
66/// question; the authority section contains RRs that point toward an
67/// authoritative name server; the additional records section contains RRs
68/// which relate to the query, but are not strictly answers for the
69/// question.
70/// ```
71///
72/// By default Message is a Query. Use the Message::as_update() to create and update, or
73///  Message::new_update()
74#[non_exhaustive]
75#[derive(Clone, Debug, PartialEq, Eq)]
76#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
77pub struct Message {
78    /// Metadata from the message header
79    pub metadata: Metadata,
80    /// Query name and other query parameters
81    pub queries: Vec<Query>,
82    /// Records which directly answer the query
83    pub answers: Vec<Record>,
84    /// Records with describe other authoritative servers
85    ///
86    /// May optionally carry the SOA record for the authoritative data in the answer section.
87    pub authorities: Vec<Record>,
88    /// Records which may be helpful in using the records in the other sections
89    pub additionals: Vec<Record>,
90    /// TSIG signature for the message, if any
91    pub signature: Option<Box<Record<TSIG>>>,
92    /// [RFC 6891, EDNS(0) Extensions, April 2013](https://tools.ietf.org/html/rfc6891#section-6.1.1)
93    ///
94    /// ```text
95    /// 6.1.1.  Basic Elements
96    ///
97    ///  An OPT pseudo-RR (sometimes called a meta-RR) MAY be added to the
98    ///  additional data section of a request.
99    ///
100    ///  The OPT RR has RR type 41.
101    ///
102    ///  If an OPT record is present in a received request, compliant
103    ///  responders MUST include an OPT record in their respective responses.
104    ///
105    ///  An OPT record does not carry any DNS data.  It is used only to
106    ///  contain control information pertaining to the question-and-answer
107    ///  sequence of a specific transaction.  OPT RRs MUST NOT be cached,
108    ///  forwarded, or stored in or loaded from Zone Files.
109    ///
110    ///  The OPT RR MAY be placed anywhere within the additional data section.
111    ///  When an OPT RR is included within any DNS message, it MUST be the
112    ///  only OPT RR in that message.  If a query message with more than one
113    ///  OPT RR is received, a FORMERR (RCODE=1) MUST be returned.  The
114    ///  placement flexibility for the OPT RR does not override the need for
115    ///  the TSIG or SIG(0) RRs to be the last in the additional section
116    ///  whenever they are present.
117    /// ```
118    /// # Return value
119    ///
120    /// Optionally returns a reference to EDNS OPT pseudo-RR
121    pub edns: Option<Edns>,
122}
123
124impl Message {
125    /// Returns a new "empty" Message
126    #[cfg(any(feature = "std", feature = "no-std-rand"))]
127    pub fn query() -> Self {
128        Self::new(random(), MessageType::Query, OpCode::Query)
129    }
130
131    /// Returns a Message constructed with error details to return to a client
132    ///
133    /// # Arguments
134    ///
135    /// * `id` - message id should match the request message id
136    /// * `op_code` - operation of the request
137    /// * `response_code` - the error code for the response
138    pub fn error_msg(id: u16, op_code: OpCode, response_code: ResponseCode) -> Self {
139        let mut message = Self::response(id, op_code);
140        message.metadata.response_code = response_code;
141        message
142    }
143
144    /// Returns a new `Message` with `MessageType::Response` and the given header contents
145    pub fn response(id: u16, op_code: OpCode) -> Self {
146        Self::new(id, MessageType::Response, op_code)
147    }
148
149    /// Create a new [`Message`] with the given header contents
150    pub fn new(id: u16, message_type: MessageType, op_code: OpCode) -> Self {
151        Self {
152            metadata: Metadata::new(id, message_type, op_code),
153            queries: Vec::new(),
154            answers: Vec::new(),
155            authorities: Vec::new(),
156            additionals: Vec::new(),
157            signature: None,
158            edns: None,
159        }
160    }
161
162    /// Truncates a Message, this blindly removes all response fields and sets truncated to `true`
163    pub fn truncate(&self) -> Self {
164        // copy header
165        let mut metadata = self.metadata;
166        metadata.truncation = true;
167
168        let mut msg = Self::new(0, MessageType::Query, OpCode::Query);
169        msg.metadata = metadata;
170
171        // drops additional/answer/nameservers/signature
172        // adds query/OPT
173        msg.add_queries(self.queries.iter().cloned());
174        if let Some(edns) = self.edns.clone() {
175            msg.set_edns(edns);
176        }
177
178        // TODO, perhaps just quickly add a few response records here? that we know would fit?
179        msg
180    }
181
182    /// Strip DNSSEC records per RFC 4035 section 3.2.1
183    ///
184    /// Removes DNSSEC records that don't match the query type from all sections
185    /// when the DNSSEC OK bit is not set in the original query.
186    ///
187    /// Uses the first query in the message to determine the query type.
188    /// If there are no queries, returns the message unchanged.
189    ///
190    /// The query_has_dnssec_ok is a required parameter because the
191    /// dnssec_ok bit in the query might be different from the bit
192    /// in the response. See discussion in
193    /// [#3340](https://github.com/hickory-dns/hickory-dns/issues/3340)
194    pub fn maybe_strip_dnssec_records(mut self, query_has_dnssec_ok: bool) -> Self {
195        if query_has_dnssec_ok {
196            return self;
197        }
198
199        let Some(query_type) = self.queries.first().map(|q| q.query_type()) else {
200            return self; // No query, return unchanged
201        };
202
203        let predicate = |record: &Record| {
204            let record_type = record.record_type();
205            record_type == query_type || !record_type.is_dnssec()
206        };
207
208        self.answers.retain(predicate);
209        self.authorities.retain(predicate);
210        self.additionals.retain(predicate);
211
212        self
213    }
214
215    /// Add a query to the Message, either the query response from the server, or the request Query.
216    pub fn add_query(&mut self, query: Query) -> &mut Self {
217        self.queries.push(query);
218        self
219    }
220
221    /// Adds an iterator over a set of Queries to be added to the message
222    pub fn add_queries<Q, I>(&mut self, queries: Q) -> &mut Self
223    where
224        Q: IntoIterator<Item = Query, IntoIter = I>,
225        I: Iterator<Item = Query>,
226    {
227        for query in queries {
228            self.add_query(query);
229        }
230
231        self
232    }
233
234    /// Add a record to the Answer section.
235    pub fn add_answer(&mut self, record: Record) -> &mut Self {
236        self.answers.push(record);
237        self
238    }
239
240    /// Add all the records from the iterator to the Answer section of the message.
241    pub fn add_answers<R, I>(&mut self, records: R) -> &mut Self
242    where
243        R: IntoIterator<Item = Record, IntoIter = I>,
244        I: Iterator<Item = Record>,
245    {
246        for record in records {
247            self.add_answer(record);
248        }
249
250        self
251    }
252
253    /// Sets the Answer section to the specified set of records.
254    ///
255    /// # Panics
256    ///
257    /// Will panic if the Answer section is already non-empty.
258    pub fn insert_answers(&mut self, records: Vec<Record>) {
259        assert!(self.answers.is_empty());
260        self.answers = records;
261    }
262
263    /// Add a record to the Authority section.
264    pub fn add_authority(&mut self, record: Record) -> &mut Self {
265        self.authorities.push(record);
266        self
267    }
268
269    /// Add all the records from the Iterator to the Authority section of the message.
270    pub fn add_authorities<R, I>(&mut self, records: R) -> &mut Self
271    where
272        R: IntoIterator<Item = Record, IntoIter = I>,
273        I: Iterator<Item = Record>,
274    {
275        for record in records {
276            self.add_authority(record);
277        }
278
279        self
280    }
281
282    /// Sets the Authority section to the specified set of records.
283    ///
284    /// # Panics
285    ///
286    /// Will panic if the Authority section is already non-empty.
287    pub fn insert_authorities(&mut self, records: Vec<Record>) {
288        assert!(self.authorities.is_empty());
289        self.authorities = records;
290    }
291
292    /// Add a record to the Additional section.
293    pub fn add_additional(&mut self, record: Record) -> &mut Self {
294        self.additionals.push(record);
295        self
296    }
297
298    /// Add all the records from the iterator to the Additional section of the message.
299    pub fn add_additionals<R, I>(&mut self, records: R) -> &mut Self
300    where
301        R: IntoIterator<Item = Record, IntoIter = I>,
302        I: Iterator<Item = Record>,
303    {
304        for record in records {
305            self.add_additional(record);
306        }
307
308        self
309    }
310
311    /// Sets the Additional to the specified set of records.
312    ///
313    /// # Panics
314    ///
315    /// Will panic if additional records are already associated to the message.
316    pub fn insert_additionals(&mut self, records: Vec<Record>) {
317        assert!(self.additionals.is_empty());
318        self.additionals = records;
319    }
320
321    /// Add the EDNS OPT pseudo-RR to the Message
322    pub fn set_edns(&mut self, edns: Edns) -> &mut Self {
323        self.edns = Some(edns);
324        self
325    }
326
327    /// Set the TSIG signature record for the message.
328    ///
329    /// This must be used only after all records have been associated. Generally this will be
330    /// handled by the client and not need to be used directly
331    #[cfg(feature = "__dnssec")]
332    pub fn set_signature(&mut self, sig: Box<Record<TSIG>>) -> &mut Self {
333        self.signature = Some(sig);
334        self
335    }
336
337    /// Returns a clone of the `Message` with the message type set to `Response`.
338    pub fn into_response(mut self) -> Self {
339        self.metadata.message_type = MessageType::Response;
340        self
341    }
342
343    /// Returns a borrowed iterator of the answer records wrapped in a dnssec Proven type
344    #[cfg(feature = "__dnssec")]
345    pub fn dnssec_answers(&self) -> DnssecIter<'_> {
346        DnssecIter::new(&self.answers)
347    }
348
349    /// Consume the message, returning an iterator over records from all sections
350    pub fn take_all_sections(&mut self) -> impl Iterator<Item = Record> {
351        let (answers, authorities, additionals) = (
352            mem::take(&mut self.answers),
353            mem::take(&mut self.authorities),
354            mem::take(&mut self.additionals),
355        );
356        answers.into_iter().chain(authorities).chain(additionals)
357    }
358
359    /// All sections chained
360    pub fn all_sections(&self) -> impl Iterator<Item = &Record> {
361        self.answers
362            .iter()
363            .chain(self.authorities.iter())
364            .chain(self.additionals.iter())
365    }
366
367    /// # Return value
368    ///
369    /// the max payload value as it's defined in the EDNS OPT pseudo-RR.
370    pub fn max_payload(&self) -> u16 {
371        let max_size = self.edns.as_ref().map_or(512, Edns::max_payload);
372        if max_size < 512 { 512 } else { max_size }
373    }
374
375    /// # Return value
376    ///
377    /// the version as defined in the EDNS record
378    pub fn version(&self) -> u8 {
379        self.edns.as_ref().map_or(0, Edns::version)
380    }
381
382    /// # Return value
383    ///
384    /// the signature over the message, if any
385    pub fn signature(&self) -> Option<&Record<TSIG>> {
386        self.signature.as_deref()
387    }
388
389    /// Remove signatures from the Message
390    pub fn take_signature(&mut self) -> Option<Box<Record<TSIG>>> {
391        self.signature.take()
392    }
393
394    /// Attempts to read the specified number of `Query`s
395    pub fn read_queries(decoder: &mut BinDecoder<'_>, count: usize) -> ProtoResult<Vec<Query>> {
396        let mut queries = Vec::with_capacity(Ord::min(count, 8));
397        for _ in 0..count {
398            queries.push(Query::read(decoder)?);
399        }
400        Ok(queries)
401    }
402
403    /// Attempts to read the specified number of records
404    ///
405    /// # Returns
406    ///
407    /// This returns a tuple of first standard Records, then a possibly associated Edns, and then
408    /// finally a `Record<TSIG>` if applicable.
409    ///
410    /// A `Record<TSIG>` record is only valid when found in the additional data section.
411    /// Further, it must always be the last record in that section. It is not possible to have
412    /// multiple TSIG records.
413    ///
414    /// RFC 8945 ยง5.1 says:
415    ///  "This TSIG record MUST be the only TSIG RR in the message and MUST be the last record in
416    ///   the additional data section."
417    #[cfg_attr(not(feature = "__dnssec"), allow(unused_mut))]
418    #[expect(clippy::type_complexity)]
419    pub fn read_records(
420        decoder: &mut BinDecoder<'_>,
421        count: usize,
422        is_additional: bool,
423        op: OpCode,
424    ) -> Result<(Vec<Record>, Option<Edns>, Option<Box<Record<TSIG>>>), DecodeError> {
425        let mut records = Vec::with_capacity(Ord::min(count, 8));
426        let mut edns = None;
427        let mut sig = None;
428
429        for _ in 0..count {
430            let record = Record::read(decoder)?;
431            if op != OpCode::Update
432                && record.record_type() != RecordType::OPT
433                && record.data.is_update()
434            {
435                return Err(DecodeError::InvalidEmptyRecord);
436            }
437
438            // There must be no additional records after a TSIG/SIG(0) record.
439            if sig.is_some() {
440                return Err(DecodeError::RecordAfterSig);
441            }
442
443            // OPT, SIG and TSIG records are only allowed in the additional section.
444            if !is_additional
445                && matches!(
446                    record.record_type(),
447                    RecordType::OPT | RecordType::SIG | RecordType::TSIG
448                )
449            {
450                return Err(DecodeError::RecordNotInAdditionalSection(
451                    record.record_type(),
452                ));
453            } else if !is_additional {
454                records.push(record);
455                continue;
456            }
457
458            match record.data {
459                #[cfg(feature = "__dnssec")]
460                RData::DNSSEC(DNSSECRData::SIG(_)) => {
461                    warn!(
462                        "message was SIG(0) signed, but support for SIG(0) message authentication was removed from hickory-dns"
463                    );
464                    records.push(record);
465                }
466                #[cfg(feature = "__dnssec")]
467                RData::TSIG(_) => {
468                    sig = Some(Box::new(
469                        record
470                            .map(|data| match data {
471                                RData::TSIG(tsig) => Some(tsig),
472                                _ => None,
473                            })
474                            .unwrap(/* match arm ensures correct type */),
475                    ))
476                }
477                RData::Update0(RecordType::OPT) | RData::OPT(_) => {
478                    if edns.is_some() {
479                        return Err(DecodeError::DuplicateEdns);
480                    }
481                    edns = Some((&record).into());
482                }
483                _ => {
484                    records.push(record);
485                }
486            }
487        }
488
489        Ok((records, edns, sig))
490    }
491
492    /// Decodes a message from the buffer.
493    pub fn from_vec(buffer: &[u8]) -> Result<Self, DecodeError> {
494        let mut decoder = BinDecoder::new(buffer);
495        Self::read(&mut decoder)
496    }
497
498    /// Encodes the Message into a buffer
499    pub fn to_vec(&self) -> Result<Vec<u8>, ProtoError> {
500        // TODO: this feels like the right place to verify the max packet size of the message,
501        //  will need to update the header for truncation and the lengths if we send less than the
502        //  full response. This needs to conform with the EDNS settings of the server...
503        let mut buffer = Vec::with_capacity(512);
504        {
505            let mut encoder = BinEncoder::new(&mut buffer);
506            self.emit(&mut encoder)?;
507        }
508
509        Ok(buffer)
510    }
511
512    /// Finalize the message prior to sending.
513    ///
514    /// Subsequent to calling this, the Message should not change.
515    #[cfg(feature = "__dnssec")]
516    pub fn finalize(
517        &mut self,
518        finalizer: &TSigner,
519        inception_time: u64,
520    ) -> ProtoResult<Option<TSigVerifier>> {
521        debug!("finalizing message: {:?}", self);
522
523        let (signature, verifier) = finalizer.sign_message(self, inception_time)?;
524        self.set_signature(signature);
525
526        Ok(verifier)
527    }
528}
529
530impl Deref for Message {
531    type Target = Metadata;
532
533    fn deref(&self) -> &Self::Target {
534        &self.metadata
535    }
536}
537
538/// Returns the count written and a boolean if it was truncated
539fn count_was_truncated(result: ProtoResult<usize>) -> ProtoResult<(u16, bool)> {
540    let (count, truncated) = match result {
541        Ok(count) => (count, false),
542        Err(ProtoError::NotAllRecordsWritten { count }) => (count, true),
543        Err(e) => return Err(e),
544    };
545
546    match u16::try_from(count) {
547        Ok(count) => Ok((count, truncated)),
548        Err(_) => Err(ProtoError::Message(
549            "too many records to fit in header count",
550        )),
551    }
552}
553
554/// A trait that defines types which can be emitted as a set, with the associated count returned.
555pub trait EmitAndCount {
556    /// Emit self to the encoder and return the count of items
557    fn emit(&mut self, encoder: &mut BinEncoder<'_>) -> ProtoResult<usize>;
558}
559
560impl<'e, I: Iterator<Item = &'e E>, E: 'e + BinEncodable> EmitAndCount for I {
561    fn emit(&mut self, encoder: &mut BinEncoder<'_>) -> ProtoResult<usize> {
562        encoder.emit_all(self)
563    }
564}
565
566/// Emits the different sections of a message properly
567///
568/// # Return
569///
570/// In the case of a successful emit, the final header (updated counts, etc) is returned for help with logging, etc.
571#[allow(clippy::too_many_arguments)]
572pub fn emit_message_parts<Q, A, N, D>(
573    metadata: &Metadata,
574    queries: &mut Q,
575    answers: &mut A,
576    authorities: &mut N,
577    additionals: &mut D,
578    edns: Option<&Edns>,
579    signature: Option<&Record<TSIG>>,
580    encoder: &mut BinEncoder<'_>,
581) -> ProtoResult<Header>
582where
583    Q: EmitAndCount,
584    A: EmitAndCount,
585    N: EmitAndCount,
586    D: EmitAndCount,
587{
588    let place = encoder.place::<Header>()?;
589
590    let query_count = queries.emit(encoder)?;
591
592    let answer_count;
593    let authority_count;
594    let mut additional_count;
595
596    if let Some(mut edns) = edns.cloned() {
597        // need to commit the error code
598        edns.set_rcode_high(metadata.response_code.high());
599
600        // RFC 6891 section 7: "The minimal response MUST be the DNS header, question section,
601        // and an OPT record. This MUST also occur when a truncated response (using the DNS
602        // header's TC bit) is returned."
603        //
604        // The OPT belongs in the additional section, which must follow answers and authority on
605        // the wire (parsers assign records to sections by count, not by type), so it cannot be
606        // emitted first. Instead, reserve space: the OPT's owner name is always root (one byte),
607        // so its encoded size is stable and can be measured up front.
608        let opt_record = Record::from(&edns);
609        let opt_len = {
610            let mut buf = Vec::new();
611            BinEncoder::new(&mut buf).emit_all(iter::once(&opt_record))?;
612            buf.len() as u16
613        };
614
615        let max_size = encoder.max_size();
616        encoder.set_max_size(max_size.saturating_sub(opt_len));
617
618        answer_count = count_was_truncated(answers.emit(encoder))?;
619        authority_count = count_was_truncated(authorities.emit(encoder))?;
620        additional_count = count_was_truncated(additionals.emit(encoder))?;
621
622        encoder.set_max_size(max_size);
623
624        let count = count_was_truncated(encoder.emit_all(iter::once(&opt_record)))?;
625        additional_count.0 += count.0;
626        additional_count.1 |= count.1;
627    } else {
628        answer_count = count_was_truncated(answers.emit(encoder))?;
629        authority_count = count_was_truncated(authorities.emit(encoder))?;
630        additional_count = count_was_truncated(additionals.emit(encoder))?;
631
632        if metadata.response_code.high() > 0 {
633            warn!(
634                "response code: {} for request: {} requires EDNS but none available",
635                metadata.response_code, metadata.id
636            );
637        }
638    }
639
640    // this is a little hacky, but if we are Verifying a signature, i.e. the original Message
641    //  then the TSIG record should not be encoded and the edns record (if it exists) is
642    //  already part of the additionals section.
643    let count = match signature {
644        Some(rec) => count_was_truncated(encoder.emit_all(iter::once(rec)))?,
645        None => (0, false),
646    };
647    additional_count.0 += count.0;
648    additional_count.1 |= count.1;
649
650    let counts = HeaderCounts {
651        queries: match u16::try_from(query_count) {
652            Ok(count) => count,
653            Err(_) => {
654                return Err(ProtoError::Message(
655                    "too many queries to fit in header count",
656                ));
657            }
658        },
659        answers: answer_count.0,
660        authorities: authority_count.0,
661        additionals: additional_count.0,
662    };
663
664    let mut final_metadata = *metadata;
665    final_metadata.truncation =
666        metadata.truncation || answer_count.1 || authority_count.1 || additional_count.1;
667
668    let header = Header {
669        metadata: final_metadata,
670        counts,
671    };
672
673    place.replace(encoder, header)?;
674    Ok(header)
675}
676
677impl BinEncodable for Message {
678    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
679        emit_message_parts(
680            &self.metadata,
681            &mut self.queries.iter(),
682            &mut self.answers.iter(),
683            &mut self.authorities.iter(),
684            &mut self.additionals.iter(),
685            self.edns.as_ref(),
686            self.signature.as_deref(),
687            encoder,
688        )?;
689
690        Ok(())
691    }
692}
693
694impl<'r> BinDecodable<'r> for Message {
695    fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
696        let Header {
697            mut metadata,
698            counts,
699        } = Header::read(decoder)?;
700
701        // TODO: return just header, and in the case of the rest of message getting an error.
702        //  this could improve error detection while decoding.
703
704        // get the questions
705        let count = counts.queries as usize;
706        let mut queries = Vec::with_capacity(Ord::min(count, 8));
707        for _ in 0..count {
708            queries.push(Query::read(decoder)?);
709        }
710
711        let (answers, _, _) =
712            Self::read_records(decoder, counts.answers as usize, false, metadata.op_code)?;
713        let (authorities, _, _) = Self::read_records(
714            decoder,
715            counts.authorities as usize,
716            false,
717            metadata.op_code,
718        )?;
719        let (additionals, edns, signature) =
720            Self::read_records(decoder, counts.additionals as usize, true, metadata.op_code)?;
721
722        // need to grab error code from EDNS (which might have a higher value)
723        if let Some(edns) = &edns {
724            let high_response_code = edns.rcode_high();
725            metadata.merge_response_code(high_response_code);
726        }
727
728        Ok(Self {
729            metadata,
730            queries,
731            answers,
732            authorities,
733            additionals,
734            signature,
735            edns,
736        })
737    }
738}
739
740impl fmt::Display for Message {
741    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
742        let write_query = |slice, f: &mut fmt::Formatter<'_>| -> Result<(), fmt::Error> {
743            for d in slice {
744                writeln!(f, ";; {d}")?;
745            }
746
747            Ok(())
748        };
749
750        let write_slice = |slice, f: &mut fmt::Formatter<'_>| -> Result<(), fmt::Error> {
751            for d in slice {
752                writeln!(f, "{d}")?;
753            }
754
755            Ok(())
756        };
757
758        writeln!(f, "; header {header}", header = self.metadata)?;
759
760        if let Some(edns) = &self.edns {
761            writeln!(f, "; edns {edns}")?;
762        }
763
764        writeln!(f, "; query")?;
765        write_query(&self.queries, f)?;
766
767        if self.metadata.message_type == MessageType::Response
768            || self.metadata.op_code == OpCode::Update
769        {
770            writeln!(f, "; answers {}", self.answers.len())?;
771            write_slice(&self.answers, f)?;
772            writeln!(f, "; authorities {}", self.authorities.len())?;
773            write_slice(&self.authorities, f)?;
774            writeln!(f, "; additionals {}", self.additionals.len())?;
775            write_slice(&self.additionals, f)?;
776        }
777
778        Ok(())
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    use crate::rr::rdata::A;
787    #[cfg(feature = "std")]
788    use crate::rr::rdata::OPT;
789    #[cfg(feature = "std")]
790    use crate::rr::rdata::opt::{ClientSubnet, EdnsCode, EdnsOption};
791    #[cfg(feature = "__dnssec")]
792    use crate::rr::rdata::{TSIG, tsig::TsigAlgorithm};
793    use crate::rr::{Name, RData};
794    #[cfg(feature = "std")]
795    use crate::std::net::IpAddr;
796    #[cfg(feature = "std")]
797    use crate::std::string::ToString;
798
799    #[test]
800    fn test_emit_and_read_header() {
801        let mut message = Message::response(10, OpCode::Update);
802        message.metadata.authoritative = true;
803        message.metadata.truncation = false;
804        message.metadata.recursion_desired = true;
805        message.metadata.recursion_available = true;
806        message.metadata.response_code = ResponseCode::ServFail;
807
808        test_emit_and_read(message);
809    }
810
811    #[test]
812    fn test_emit_and_read_query() {
813        let mut message = Message::response(10, OpCode::Update);
814        message.metadata.authoritative = true;
815        message.metadata.truncation = true;
816        message.metadata.recursion_desired = true;
817        message.metadata.recursion_available = true;
818        message.metadata.response_code = ResponseCode::ServFail;
819        message.add_query(Query::new());
820
821        test_emit_and_read(message);
822    }
823
824    #[test]
825    fn test_emit_and_read_records() {
826        let mut message = Message::response(10, OpCode::Update);
827        message.metadata.authoritative = true;
828        message.metadata.truncation = true;
829        message.metadata.recursion_desired = true;
830        message.metadata.recursion_available = true;
831        message.metadata.authentic_data = true;
832        message.metadata.checking_disabled = true;
833        message.metadata.response_code = ResponseCode::ServFail;
834
835        message.add_answer(Record::stub());
836        message.add_authority(Record::stub());
837        message.add_additional(Record::stub());
838
839        test_emit_and_read(message);
840    }
841
842    #[cfg(test)]
843    fn test_emit_and_read(message: Message) {
844        let mut byte_vec: Vec<u8> = Vec::with_capacity(512);
845        {
846            let mut encoder = BinEncoder::new(&mut byte_vec);
847            message.emit(&mut encoder).unwrap();
848        }
849
850        let mut decoder = BinDecoder::new(&byte_vec);
851        let got = Message::read(&mut decoder).unwrap();
852
853        assert_eq!(got, message);
854    }
855
856    #[test]
857    fn test_header_counts_correction_after_emit_read() {
858        let mut message = Message::response(10, OpCode::Update);
859        message.metadata.authoritative = true;
860        message.metadata.truncation = true;
861        message.metadata.recursion_desired = true;
862        message.metadata.recursion_available = true;
863        message.metadata.authentic_data = true;
864        message.metadata.checking_disabled = true;
865        message.metadata.response_code = ResponseCode::ServFail;
866
867        message.add_answer(Record::stub());
868        message.add_authority(Record::stub());
869        message.add_additional(Record::stub());
870
871        let got = get_message_after_emitting_and_reading(message);
872        assert_eq!(got.queries.len(), 0);
873        assert_eq!(got.answers.len(), 1);
874        assert_eq!(got.authorities.len(), 1);
875        assert_eq!(got.additionals.len(), 1);
876    }
877
878    #[cfg(test)]
879    fn get_message_after_emitting_and_reading(message: Message) -> Message {
880        let mut byte_vec: Vec<u8> = Vec::with_capacity(512);
881        {
882            let mut encoder = BinEncoder::new(&mut byte_vec);
883            message.emit(&mut encoder).unwrap();
884        }
885
886        let mut decoder = BinDecoder::new(&byte_vec);
887
888        Message::read(&mut decoder).unwrap()
889    }
890
891    #[test]
892    fn test_legit_message() {
893        #[rustfmt::skip]
894        let buf: Vec<u8> = vec![
895            0x10, 0x00, 0x81,
896            0x80, // id = 4096, response, op=query, recursion_desired, recursion_available, no_error
897            0x00, 0x01, 0x00, 0x01, // 1 query, 1 answer,
898            0x00, 0x00, 0x00, 0x00, // 0 nameservers, 0 additional record
899            0x03, b'w', b'w', b'w', // query --- www.example.com
900            0x07, b'e', b'x', b'a', //
901            b'm', b'p', b'l', b'e', //
902            0x03, b'c', b'o', b'm', //
903            0x00,                   // 0 = endname
904            0x00, 0x01, 0x00, 0x01, // RecordType = A, Class = IN
905            0xC0, 0x0C,             // name pointer to www.example.com
906            0x00, 0x01, 0x00, 0x01, // RecordType = A, Class = IN
907            0x00, 0x00, 0x00, 0x02, // TTL = 2 seconds
908            0x00, 0x04,             // record length = 4 (ipv4 address)
909            0x5D, 0xB8, 0xD7, 0x0E, // address = 93.184.215.14
910        ];
911
912        let mut decoder = BinDecoder::new(&buf);
913        let message = Message::read(&mut decoder).unwrap();
914
915        assert_eq!(message.id, 4_096);
916
917        let mut buf: Vec<u8> = Vec::with_capacity(512);
918        {
919            let mut encoder = BinEncoder::new(&mut buf);
920            message.emit(&mut encoder).unwrap();
921        }
922
923        let mut decoder = BinDecoder::new(&buf);
924        let message = Message::read(&mut decoder).unwrap();
925
926        assert_eq!(message.id, 4_096);
927    }
928
929    #[test]
930    fn rdata_zero_roundtrip() {
931        let buf = &[
932            160, 160, 0, 13, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0,
933        ];
934
935        assert!(Message::from_bytes(buf).is_err());
936    }
937
938    #[test]
939    fn nsec_deserialization() {
940        const CRASHING_MESSAGE: &[u8] = &[
941            0, 0, 132, 0, 0, 0, 0, 1, 0, 0, 0, 1, 36, 49, 101, 48, 101, 101, 51, 100, 51, 45, 100,
942            52, 50, 52, 45, 52, 102, 55, 56, 45, 57, 101, 52, 99, 45, 99, 51, 56, 51, 51, 55, 55,
943            56, 48, 102, 50, 98, 5, 108, 111, 99, 97, 108, 0, 0, 1, 128, 1, 0, 0, 0, 120, 0, 4,
944            192, 168, 1, 17, 36, 49, 101, 48, 101, 101, 51, 100, 51, 45, 100, 52, 50, 52, 45, 52,
945            102, 55, 56, 45, 57, 101, 52, 99, 45, 99, 51, 56, 51, 51, 55, 55, 56, 48, 102, 50, 98,
946            5, 108, 111, 99, 97, 108, 0, 0, 47, 128, 1, 0, 0, 0, 120, 0, 5, 192, 70, 0, 1, 64,
947        ];
948
949        Message::from_vec(CRASHING_MESSAGE).expect("failed to parse message");
950    }
951
952    #[test]
953    fn test_read_records_unsigned() {
954        let records = vec![
955            Record::from_rdata(
956                Name::from_labels(vec!["example", "com"]).unwrap(),
957                300,
958                RData::A(A::new(127, 0, 0, 1)),
959            ),
960            Record::from_rdata(
961                Name::from_labels(vec!["www", "example", "com"]).unwrap(),
962                300,
963                RData::A(A::new(127, 0, 0, 1)),
964            ),
965        ];
966        let result = encode_and_read_records(records.clone(), false);
967        let (output_records, edns, signature) = result.unwrap();
968        assert_eq!(output_records.len(), records.len());
969        assert!(edns.is_none());
970        assert!(signature.is_none());
971    }
972
973    #[cfg(feature = "std")]
974    #[test]
975    fn test_read_records_edns() {
976        let records = vec![
977            Record::from_rdata(
978                Name::from_labels(vec!["example", "com"]).unwrap(),
979                300,
980                RData::A(A::new(127, 0, 0, 1)),
981            ),
982            Record::from_rdata(
983                Name::new(),
984                0,
985                RData::OPT(OPT::new(vec![(
986                    EdnsCode::Subnet,
987                    EdnsOption::Subnet(ClientSubnet::new(IpAddr::from([127, 0, 0, 1]), 0, 24)),
988                )])),
989            ),
990        ];
991        let result = encode_and_read_records(records, true);
992        let (output_records, edns, signature) = result.unwrap();
993        assert_eq!(output_records.len(), 1); // Only the A record, OPT becomes EDNS
994        assert!(edns.is_some());
995        assert!(signature.is_none());
996    }
997
998    #[cfg(feature = "__dnssec")]
999    #[test]
1000    fn test_read_records_tsig() {
1001        let records = vec![
1002            Record::from_rdata(
1003                Name::from_labels(vec!["example", "com"]).unwrap(),
1004                300,
1005                RData::A(A::new(127, 0, 0, 1)),
1006            ),
1007            Record::from_rdata(
1008                Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1009                0,
1010                fake_tsig(),
1011            ),
1012        ];
1013        let result = encode_and_read_records(records, true);
1014        let (output_records, edns, signature) = result.unwrap();
1015        assert_eq!(output_records.len(), 1); // Only the A record, TSIG becomes signature
1016        assert!(edns.is_none());
1017        assert!(signature.is_some());
1018    }
1019
1020    #[cfg(all(feature = "std", feature = "__dnssec"))]
1021    #[test]
1022    fn test_read_records_edns_tsig() {
1023        let records = vec![
1024            Record::from_rdata(
1025                Name::from_labels(vec!["example", "com"]).unwrap(),
1026                300,
1027                RData::A(A::new(127, 0, 0, 1)),
1028            ),
1029            Record::from_rdata(
1030                Name::new(),
1031                0,
1032                RData::OPT(OPT::new(vec![(
1033                    EdnsCode::Subnet,
1034                    EdnsOption::Subnet(ClientSubnet::new(IpAddr::from([127, 0, 0, 1]), 0, 24)),
1035                )])),
1036            ),
1037            Record::from_rdata(
1038                Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1039                0,
1040                fake_tsig(),
1041            ),
1042        ];
1043
1044        let result = encode_and_read_records(records, true);
1045        assert!(result.is_ok());
1046        let (output_records, edns, signature) = result.unwrap();
1047        assert_eq!(output_records.len(), 1); // Only the A record
1048        assert!(edns.is_some());
1049        assert!(signature.is_some());
1050    }
1051
1052    #[cfg(feature = "std")]
1053    #[test]
1054    fn test_read_records_unsigned_multiple_edns() {
1055        let opt_record = Record::from_rdata(
1056            Name::new(),
1057            0,
1058            RData::OPT(OPT::new(vec![(
1059                EdnsCode::Subnet,
1060                EdnsOption::Subnet(ClientSubnet::new(IpAddr::from([127, 0, 0, 1]), 0, 24)),
1061            )])),
1062        );
1063        let error = encode_and_read_records(
1064            vec![
1065                opt_record.clone(),
1066                Record::from_rdata(
1067                    Name::from_labels(vec!["example", "com"]).unwrap(),
1068                    300,
1069                    RData::A(A::new(127, 0, 0, 1)),
1070                ),
1071                opt_record.clone(),
1072            ],
1073            true,
1074        )
1075        .unwrap_err();
1076        assert!(error.to_string().contains("more than one EDNS record"));
1077    }
1078
1079    #[cfg(feature = "std")]
1080    #[test]
1081    fn test_read_records_opt_not_additional() {
1082        let opt_record = Record::from_rdata(
1083            Name::new(),
1084            0,
1085            RData::OPT(OPT::new(vec![(
1086                EdnsCode::Subnet,
1087                EdnsOption::Subnet(ClientSubnet::new(IpAddr::from([127, 0, 0, 1]), 0, 24)),
1088            )])),
1089        );
1090        let err = encode_and_read_records(
1091            vec![
1092                opt_record.clone(),
1093                Record::from_rdata(
1094                    Name::from_labels(vec!["example", "com"]).unwrap(),
1095                    300,
1096                    RData::A(A::new(127, 0, 0, 1)),
1097                ),
1098            ],
1099            false,
1100        )
1101        .unwrap_err();
1102        assert!(
1103            err.to_string()
1104                .contains("record type OPT only allowed in additional")
1105        );
1106    }
1107
1108    #[cfg(all(feature = "std", feature = "__dnssec"))]
1109    #[test]
1110    fn test_read_records_signed_multiple_edns() {
1111        let opt_record = Record::from_rdata(
1112            Name::new(),
1113            0,
1114            RData::OPT(OPT::new(vec![(
1115                EdnsCode::Subnet,
1116                EdnsOption::Subnet(ClientSubnet::new(IpAddr::from([127, 0, 0, 1]), 0, 24)),
1117            )])),
1118        );
1119        let error = encode_and_read_records(
1120            vec![
1121                opt_record.clone(),
1122                Record::from_rdata(
1123                    Name::from_labels(vec!["example", "com"]).unwrap(),
1124                    300,
1125                    RData::A(A::new(127, 0, 0, 1)),
1126                ),
1127                opt_record.clone(),
1128                Record::from_rdata(
1129                    Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1130                    0,
1131                    fake_tsig(),
1132                ),
1133            ],
1134            true,
1135        )
1136        .unwrap_err();
1137        assert!(error.to_string().contains("more than one EDNS record"));
1138    }
1139
1140    #[cfg(all(feature = "std", feature = "__dnssec"))]
1141    #[test]
1142    fn test_read_records_tsig_not_additional() {
1143        let err = encode_and_read_records(
1144            vec![
1145                Record::from_rdata(
1146                    Name::from_labels(vec!["example", "com"]).unwrap(),
1147                    300,
1148                    RData::A(A::new(127, 0, 0, 1)),
1149                ),
1150                Record::from_rdata(
1151                    Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1152                    0,
1153                    fake_tsig(),
1154                ),
1155            ],
1156            false,
1157        )
1158        .unwrap_err();
1159        assert!(
1160            err.to_string()
1161                .contains("record type TSIG only allowed in additional")
1162        );
1163    }
1164
1165    #[cfg(all(feature = "std", feature = "__dnssec"))]
1166    #[test]
1167    fn test_read_records_tsig_not_last() {
1168        let a_record = Record::from_rdata(
1169            Name::from_labels(vec!["example", "com"]).unwrap(),
1170            300,
1171            RData::A(A::new(127, 0, 0, 1)),
1172        );
1173        let error = encode_and_read_records(
1174            vec![
1175                a_record.clone(),
1176                Record::from_rdata(
1177                    Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1178                    0,
1179                    fake_tsig(),
1180                ),
1181                a_record.clone(),
1182            ],
1183            true,
1184        )
1185        .unwrap_err()
1186        .to_string();
1187        assert!(error.contains("record after TSIG or SIG(0)"));
1188    }
1189
1190    #[cfg(all(feature = "std", feature = "__dnssec"))]
1191    #[test]
1192    fn test_read_records_sig0_not_last() {
1193        let a_record = Record::from_rdata(
1194            Name::from_labels(vec!["example", "com"]).unwrap(),
1195            300,
1196            RData::A(A::new(127, 0, 0, 1)),
1197        );
1198        let error = encode_and_read_records(
1199            vec![
1200                a_record.clone(),
1201                Record::from_rdata(
1202                    Name::from_labels(vec!["sig0", "example", "com"]).unwrap(),
1203                    0,
1204                    fake_tsig(),
1205                ),
1206                a_record.clone(),
1207            ],
1208            true,
1209        )
1210        .unwrap_err()
1211        .to_string();
1212        assert!(error.contains("record after TSIG or SIG(0)"));
1213    }
1214
1215    #[cfg(all(feature = "std", feature = "__dnssec"))]
1216    #[test]
1217    fn test_read_records_multiple_tsig() {
1218        let tsig_record = Record::from_rdata(
1219            Name::from_labels(vec!["tsig", "example", "com"]).unwrap(),
1220            0,
1221            fake_tsig(),
1222        );
1223        let error = encode_and_read_records(
1224            vec![
1225                Record::from_rdata(
1226                    Name::from_labels(vec!["example", "com"]).unwrap(),
1227                    300,
1228                    RData::A(A::new(127, 0, 0, 1)),
1229                ),
1230                tsig_record.clone(),
1231                tsig_record.clone(),
1232            ],
1233            true,
1234        )
1235        .unwrap_err()
1236        .to_string();
1237        assert!(error.contains("record after TSIG or SIG(0)"));
1238    }
1239
1240    #[cfg(all(feature = "std", feature = "__dnssec"))]
1241    #[test]
1242    fn test_read_records_multiple_sig0() {
1243        let sig0_record = Record::from_rdata(
1244            Name::from_labels(vec!["sig0", "example", "com"]).unwrap(),
1245            0,
1246            fake_tsig(),
1247        );
1248        let error = encode_and_read_records(
1249            vec![
1250                Record::from_rdata(
1251                    Name::from_labels(vec!["example", "com"]).unwrap(),
1252                    300,
1253                    RData::A(A::new(127, 0, 0, 1)),
1254                ),
1255                sig0_record.clone(),
1256                sig0_record.clone(),
1257            ],
1258            true,
1259        )
1260        .unwrap_err()
1261        .to_string();
1262        assert!(error.contains("record after TSIG or SIG(0)"));
1263    }
1264
1265    #[expect(clippy::type_complexity)]
1266    fn encode_and_read_records(
1267        records: Vec<Record>,
1268        is_additional: bool,
1269    ) -> ProtoResult<(Vec<Record>, Option<Edns>, Option<Box<Record<TSIG>>>)> {
1270        let mut bytes = Vec::new();
1271        let mut encoder = BinEncoder::new(&mut bytes);
1272        encoder.emit_all(records.iter())?;
1273        Ok(Message::read_records(
1274            &mut BinDecoder::new(&bytes),
1275            records.len(),
1276            is_additional,
1277            OpCode::Query,
1278        )?)
1279    }
1280
1281    #[cfg(feature = "__dnssec")]
1282    fn fake_tsig() -> RData {
1283        RData::TSIG(TSIG::new(
1284            TsigAlgorithm::HmacSha256,
1285            0,
1286            0,
1287            vec![],
1288            0,
1289            None,
1290            vec![],
1291        ))
1292    }
1293}