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
// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! option record for passing protocol options between the client and server
#![allow(clippy::use_self)]

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use std::{collections::HashMap, fmt};

#[cfg(feature = "serde-config")]
use serde::{Deserialize, Serialize};

use tracing::warn;

use crate::{
    error::{ProtoError, ProtoErrorKind, ProtoResult},
    rr::{RData, RecordData, RecordDataDecodable, RecordType},
    serialize::binary::{BinDecodable, BinDecoder, BinEncodable, BinEncoder, Restrict},
};

#[cfg(feature = "dnssec")]
use crate::rr::dnssec::SupportedAlgorithms;

/// The OPT record type is used for ExtendedDNS records.
///
/// These allow for additional information to be associated with the DNS request that otherwise
/// would require changes to the DNS protocol.
///
/// [RFC 6891, EDNS(0) Extensions, April 2013](https://tools.ietf.org/html/rfc6891#section-6)
///
/// ```text
/// 6.1.  OPT Record Definition
///
/// 6.1.1.  Basic Elements
///
///    An OPT pseudo-RR (sometimes called a meta-RR) MAY be added to the
///    additional data section of a request.
///
///    The OPT RR has RR type 41.
///
///    If an OPT record is present in a received request, compliant
///    responders MUST include an OPT record in their respective responses.
///
///    An OPT record does not carry any DNS data.  It is used only to
///    contain control information pertaining to the question-and-answer
///    sequence of a specific transaction.  OPT RRs MUST NOT be cached,
///    forwarded, or stored in or loaded from Zone Files.
///
///    The OPT RR MAY be placed anywhere within the additional data section.
///    When an OPT RR is included within any DNS message, it MUST be the
///    only OPT RR in that message.  If a query message with more than one
///    OPT RR is received, a FORMERR (RCODE=1) MUST be returned.  The
///    placement flexibility for the OPT RR does not override the need for
///    the TSIG or SIG(0) RRs to be the last in the additional section
///    whenever they are present.
///
/// 6.1.2.  Wire Format
///
///    An OPT RR has a fixed part and a variable set of options expressed as
///    {attribute, value} pairs.  The fixed part holds some DNS metadata,
///    and also a small collection of basic extension elements that we
///    expect to be so popular that it would be a waste of wire space to
///    encode them as {attribute, value} pairs.
///
///    The fixed part of an OPT RR is structured as follows:
///
///        +------------+--------------+------------------------------+
///        | Field Name | Field Type   | Description                  |
///        +------------+--------------+------------------------------+
///        | NAME       | domain name  | MUST be 0 (root domain)      |
///        | TYPE       | u_int16_t    | OPT (41)                     |
///        | CLASS      | u_int16_t    | requestor's UDP payload size |
///        | TTL        | u_int32_t    | extended RCODE and flags     |
///        | RDLEN      | u_int16_t    | length of all RDATA          |
///        | RDATA      | octet stream | {attribute,value} pairs      |
///        +------------+--------------+------------------------------+
///
///                                OPT RR Format
///
///    The variable part of an OPT RR may contain zero or more options in
///    the RDATA.  Each option MUST be treated as a bit field.  Each option
///    is encoded as:
///
///                   +0 (MSB)                            +1 (LSB)
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///     0: |                          OPTION-CODE                          |
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///     2: |                         OPTION-LENGTH                         |
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///     4: |                                                               |
///        /                          OPTION-DATA                          /
///        /                                                               /
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///
///    OPTION-CODE
///       Assigned by the Expert Review process as defined by the DNSEXT
///       working group and the IESG.
///
///    OPTION-LENGTH
///       Size (in octets) of OPTION-DATA.
///
///    OPTION-DATA
///       Varies per OPTION-CODE.  MUST be treated as a bit field.
///
///    The order of appearance of option tuples is not defined.  If one
///    option modifies the behaviour of another or multiple options are
///    related to one another in some way, they have the same effect
///    regardless of ordering in the RDATA wire encoding.
///
///    Any OPTION-CODE values not understood by a responder or requestor
///    MUST be ignored.  Specifications of such options might wish to
///    include some kind of signaled acknowledgement.  For example, an
///    option specification might say that if a responder sees and supports
///    option XYZ, it MUST include option XYZ in its response.
///
/// 6.1.3.  OPT Record TTL Field Use
///
///    The extended RCODE and flags, which OPT stores in the RR Time to Live
///    (TTL) field, are structured as follows:
///
///                   +0 (MSB)                            +1 (LSB)
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///     0: |         EXTENDED-RCODE        |            VERSION            |
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///     2: | DO|                           Z                               |
///        +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///
///    EXTENDED-RCODE
///       Forms the upper 8 bits of extended 12-bit RCODE (together with the
///       4 bits defined in [RFC1035].  Note that EXTENDED-RCODE value 0
///       indicates that an unextended RCODE is in use (values 0 through
///       15).
///
///    VERSION
///       Indicates the implementation level of the setter.  Full
///       conformance with this specification is indicated by version '0'.
///       Requestors are encouraged to set this to the lowest implemented
///       level capable of expressing a transaction, to minimise the
///       responder and network load of discovering the greatest common
///       implementation level between requestor and responder.  A
///       requestor's version numbering strategy MAY ideally be a run-time
///       configuration option.
///       If a responder does not implement the VERSION level of the
///       request, then it MUST respond with RCODE=BADVERS.  All responses
///       MUST be limited in format to the VERSION level of the request, but
///       the VERSION of each response SHOULD be the highest implementation
///       level of the responder.  In this way, a requestor will learn the
///       implementation level of a responder as a side effect of every
///       response, including error responses and including RCODE=BADVERS.
///
/// 6.1.4.  Flags
///
///    DO
///       DNSSEC OK bit as defined by [RFC3225].
///
///    Z
///       Set to zero by senders and ignored by receivers, unless modified
///       in a subsequent specification.
/// ```
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct OPT {
    options: HashMap<EdnsCode, EdnsOption>,
}

impl OPT {
    /// Creates a new OPT record data.
    ///
    /// # Arguments
    ///
    /// * `options` - A map of the codes and record types
    ///
    /// # Return value
    ///
    /// The newly created OPT data
    pub fn new(options: HashMap<EdnsCode, EdnsOption>) -> Self {
        Self { options }
    }

    #[deprecated(note = "Please use as_ref() or as_mut() for shared/mutable references")]
    /// The entire map of options
    pub fn options(&self) -> &HashMap<EdnsCode, EdnsOption> {
        &self.options
    }

    /// Get a single option based on the code
    pub fn get(&self, code: EdnsCode) -> Option<&EdnsOption> {
        self.options.get(&code)
    }

    /// Insert a new option, the key is derived from the `EdnsOption`
    pub fn insert(&mut self, option: EdnsOption) {
        self.options.insert((&option).into(), option);
    }

    /// Remove an option, the key is derived from the `EdnsOption`
    pub fn remove(&mut self, option: EdnsCode) {
        self.options.remove(&option);
    }
}

impl AsMut<HashMap<EdnsCode, EdnsOption>> for OPT {
    fn as_mut(&mut self) -> &mut HashMap<EdnsCode, EdnsOption> {
        &mut self.options
    }
}

impl AsRef<HashMap<EdnsCode, EdnsOption>> for OPT {
    fn as_ref(&self) -> &HashMap<EdnsCode, EdnsOption> {
        &self.options
    }
}

impl BinEncodable for OPT {
    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
        for (edns_code, edns_option) in self.as_ref().iter() {
            encoder.emit_u16(u16::from(*edns_code))?;
            encoder.emit_u16(edns_option.len())?;
            edns_option.emit(encoder)?
        }
        Ok(())
    }
}

impl<'r> RecordDataDecodable<'r> for OPT {
    fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> ProtoResult<Self> {
        let mut state: OptReadState = OptReadState::ReadCode;
        let mut options: HashMap<EdnsCode, EdnsOption> = HashMap::new();
        let start_idx = decoder.index();

        // There is no unsafe direct use of the rdata length after this point
        let rdata_length = length.map(|u| u as usize).unverified(/*rdata length usage is bounded*/);
        while rdata_length > decoder.index() - start_idx {
            match state {
                OptReadState::ReadCode => {
                    state = OptReadState::Code {
                        code: EdnsCode::from(
                            decoder.read_u16()?.unverified(/*EdnsCode is verified as safe*/),
                        ),
                    };
                }
                OptReadState::Code { code } => {
                    let length = decoder
                        .read_u16()?
                        .map(|u| u as usize)
                        .verify_unwrap(|u| *u <= rdata_length)
                        .map_err(|_| ProtoError::from("OPT value length exceeds rdata length"))?;
                    // If we know that the length is 0, we can avoid the `OptReadState::Data` state
                    // and directly add the option to the map.
                    // The data state does not process 0-length correctly, since it always reads at
                    // least 1 byte, thus making the length check fail.
                    state = if length == 0 {
                        options.insert(code, (code, &[] as &[u8]).try_into()?);
                        OptReadState::ReadCode
                    } else {
                        OptReadState::Data {
                            code,
                            length,
                            // TODO: this can be replaced with decoder.read_vec(), right?
                            //  the current version allows for malformed opt to be skipped...
                            collected: Vec::<u8>::with_capacity(length),
                        }
                    };
                }
                OptReadState::Data {
                    code,
                    length,
                    mut collected,
                } => {
                    // TODO: can this be replaced by read_slice()?
                    collected.push(decoder.pop()?.unverified(/*byte array is safe*/));
                    if length == collected.len() {
                        options.insert(code, (code, &collected as &[u8]).try_into()?);
                        state = OptReadState::ReadCode;
                    } else {
                        state = OptReadState::Data {
                            code,
                            length,
                            collected,
                        };
                    }
                }
            }
        }

        if state != OptReadState::ReadCode {
            // there was some problem parsing the data for the options, ignoring them
            // TODO: should we ignore all of the EDNS data in this case?
            warn!("incomplete or poorly formatted EDNS options: {:?}", state);
            options.clear();
        }

        // the record data is stored as unstructured data, the expectation is that this will be processed after initial parsing.
        Ok(Self::new(options))
    }
}

impl RecordData for OPT {
    fn try_from_rdata(data: RData) -> Result<Self, RData> {
        match data {
            RData::OPT(csync) => Ok(csync),
            _ => Err(data),
        }
    }

    fn try_borrow(data: &RData) -> Option<&Self> {
        match data {
            RData::OPT(csync) => Some(csync),
            _ => None,
        }
    }

    fn record_type(&self) -> RecordType {
        RecordType::OPT
    }

    fn into_rdata(self) -> RData {
        RData::OPT(self)
    }
}

impl fmt::Display for OPT {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(self, f)
    }
}

#[derive(Debug, PartialEq, Eq)]
enum OptReadState {
    ReadCode,
    Code {
        code: EdnsCode,
    }, // expect LSB for the opt code, store the high byte
    Data {
        code: EdnsCode,
        length: usize,
        collected: Vec<u8>,
    }, // expect the data for the option
}

/// The code of the EDNS data option
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[derive(Hash, Debug, Copy, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EdnsCode {
    /// [RFC 6891, Reserved](https://tools.ietf.org/html/rfc6891)
    Zero,

    /// [RFC 8764l, Apple's Long-Lived Queries, Optional](https://tools.ietf.org/html/rfc8764)
    LLQ,

    /// [UL On-hold](http://files.dns-sd.org/draft-sekar-dns-ul.txt)
    UL,

    /// [RFC 5001, NSID](https://tools.ietf.org/html/rfc5001)
    NSID,
    // 4 Reserved [draft-cheshire-edns0-owner-option] -EXPIRED-
    /// [RFC 6975, DNSSEC Algorithm Understood](https://tools.ietf.org/html/rfc6975)
    DAU,

    /// [RFC 6975, DS Hash Understood](https://tools.ietf.org/html/rfc6975)
    DHU,

    /// [RFC 6975, NSEC3 Hash Understood](https://tools.ietf.org/html/rfc6975)
    N3U,

    /// [RFC 7871, Client Subnet, Optional](https://tools.ietf.org/html/rfc7871)
    Subnet,

    /// [RFC 7314, EDNS EXPIRE, Optional](https://tools.ietf.org/html/rfc7314)
    Expire,

    /// [RFC 7873, DNS Cookies](https://tools.ietf.org/html/rfc7873)
    Cookie,

    /// [RFC 7828, edns-tcp-keepalive](https://tools.ietf.org/html/rfc7828)
    Keepalive,

    /// [RFC 7830, The EDNS(0) Padding](https://tools.ietf.org/html/rfc7830)
    Padding,

    /// [RFC 7901, CHAIN Query Requests in DNS, Optional](https://tools.ietf.org/html/rfc7901)
    Chain,

    /// Unknown, used to deal with unknown or unsupported codes
    Unknown(u16),
}

// TODO: implement a macro to perform these inversions
impl From<u16> for EdnsCode {
    fn from(value: u16) -> Self {
        match value {
            0 => Self::Zero,
            1 => Self::LLQ,
            2 => Self::UL,
            3 => Self::NSID,
            // 4 Reserved [draft-cheshire-edns0-owner-option] -EXPIRED-
            5 => Self::DAU,
            6 => Self::DHU,
            7 => Self::N3U,
            8 => Self::Subnet,
            9 => Self::Expire,
            10 => Self::Cookie,
            11 => Self::Keepalive,
            12 => Self::Padding,
            13 => Self::Chain,
            _ => Self::Unknown(value),
        }
    }
}

impl From<EdnsCode> for u16 {
    fn from(value: EdnsCode) -> Self {
        match value {
            EdnsCode::Zero => 0,
            EdnsCode::LLQ => 1,
            EdnsCode::UL => 2,
            EdnsCode::NSID => 3,
            // 4 Reserved [draft-cheshire-edns0-owner-option] -EXPIRED-
            EdnsCode::DAU => 5,
            EdnsCode::DHU => 6,
            EdnsCode::N3U => 7,
            EdnsCode::Subnet => 8,
            EdnsCode::Expire => 9,
            EdnsCode::Cookie => 10,
            EdnsCode::Keepalive => 11,
            EdnsCode::Padding => 12,
            EdnsCode::Chain => 13,
            EdnsCode::Unknown(value) => value,
        }
    }
}

/// options used to pass information about capabilities between client and server
///
/// `note: Not all EdnsOptions are supported at this time.`
///
/// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-13>
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Hash)]
#[non_exhaustive]
pub enum EdnsOption {
    /// [RFC 6975, DNSSEC Algorithm Understood](https://tools.ietf.org/html/rfc6975)
    #[cfg(feature = "dnssec")]
    #[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
    DAU(SupportedAlgorithms),

    /// [RFC 6975, DS Hash Understood](https://tools.ietf.org/html/rfc6975)
    #[cfg(feature = "dnssec")]
    #[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
    DHU(SupportedAlgorithms),

    /// [RFC 6975, NSEC3 Hash Understood](https://tools.ietf.org/html/rfc6975)
    #[cfg(feature = "dnssec")]
    #[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
    N3U(SupportedAlgorithms),

    /// [RFC 7871, Client Subnet, Optional](https://tools.ietf.org/html/rfc7871)
    Subnet(ClientSubnet),

    /// Unknown, used to deal with unknown or unsupported codes
    Unknown(u16, Vec<u8>),
}

impl EdnsOption {
    /// Returns the length in bytes of the EdnsOption
    pub fn len(&self) -> u16 {
        match *self {
            #[cfg(feature = "dnssec")]
            EdnsOption::DAU(ref algorithms)
            | EdnsOption::DHU(ref algorithms)
            | EdnsOption::N3U(ref algorithms) => algorithms.len(),
            EdnsOption::Subnet(ref subnet) => subnet.len(),
            EdnsOption::Unknown(_, ref data) => data.len() as u16, // TODO: should we verify?
        }
    }

    /// Returns `true` if the length in bytes of the EdnsOption is 0
    pub fn is_empty(&self) -> bool {
        match *self {
            #[cfg(feature = "dnssec")]
            EdnsOption::DAU(ref algorithms)
            | EdnsOption::DHU(ref algorithms)
            | EdnsOption::N3U(ref algorithms) => algorithms.is_empty(),
            EdnsOption::Subnet(ref subnet) => subnet.is_empty(),
            EdnsOption::Unknown(_, ref data) => data.is_empty(),
        }
    }
}

impl BinEncodable for EdnsOption {
    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
        match *self {
            #[cfg(feature = "dnssec")]
            EdnsOption::DAU(ref algorithms)
            | EdnsOption::DHU(ref algorithms)
            | EdnsOption::N3U(ref algorithms) => algorithms.emit(encoder),
            EdnsOption::Subnet(ref subnet) => subnet.emit(encoder),
            EdnsOption::Unknown(_, ref data) => encoder.emit_vec(data), // gah, clone needed or make a crazy api.
        }
    }
}

/// only the supported extensions are listed right now.
impl<'a> TryFrom<(EdnsCode, &'a [u8])> for EdnsOption {
    type Error = ProtoError;

    #[allow(clippy::match_single_binding)]
    fn try_from(value: (EdnsCode, &'a [u8])) -> Result<Self, Self::Error> {
        Ok(match value.0 {
            #[cfg(feature = "dnssec")]
            EdnsCode::DAU => Self::DAU(value.1.into()),
            #[cfg(feature = "dnssec")]
            EdnsCode::DHU => Self::DHU(value.1.into()),
            #[cfg(feature = "dnssec")]
            EdnsCode::N3U => Self::N3U(value.1.into()),
            EdnsCode::Subnet => Self::Subnet(value.1.try_into()?),
            _ => Self::Unknown(value.0.into(), value.1.to_vec()),
        })
    }
}

impl<'a> TryFrom<&'a EdnsOption> for Vec<u8> {
    type Error = ProtoError;

    fn try_from(value: &'a EdnsOption) -> Result<Self, Self::Error> {
        Ok(match *value {
            #[cfg(feature = "dnssec")]
            EdnsOption::DAU(ref algorithms)
            | EdnsOption::DHU(ref algorithms)
            | EdnsOption::N3U(ref algorithms) => algorithms.into(),
            EdnsOption::Subnet(ref subnet) => subnet.try_into()?,
            EdnsOption::Unknown(_, ref data) => data.clone(), // gah, clone needed or make a crazy api.
        })
    }
}

impl<'a> From<&'a EdnsOption> for EdnsCode {
    fn from(value: &'a EdnsOption) -> Self {
        match *value {
            #[cfg(feature = "dnssec")]
            EdnsOption::DAU(..) => Self::DAU,
            #[cfg(feature = "dnssec")]
            EdnsOption::DHU(..) => Self::DHU,
            #[cfg(feature = "dnssec")]
            EdnsOption::N3U(..) => Self::N3U,
            EdnsOption::Subnet(..) => Self::Subnet,
            EdnsOption::Unknown(code, _) => code.into(),
        }
    }
}

/// [RFC 7871, Client Subnet, Optional](https://tools.ietf.org/html/rfc7871)
///
/// +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/// 0: |                            FAMILY                             |
///    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/// 2: |     SOURCE PREFIX-LENGTH      |     SCOPE PREFIX-LENGTH       |
///    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
/// 4: |                           ADDRESS...                          /
///    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
///
/// o  FAMILY, 2 octets, indicates the family of the address contained in
///    the option, using address family codes as assigned by IANA in
///    Address Family Numbers [Address_Family_Numbers].
/// o  SOURCE PREFIX-LENGTH, an unsigned octet representing the leftmost
///    number of significant bits of ADDRESS to be used for the lookup.
///    In responses, it mirrors the same value as in the queries.
/// o  SCOPE PREFIX-LENGTH, an unsigned octet representing the leftmost
///    number of significant bits of ADDRESS that the response covers.
///    In queries, it MUST be set to 0.
/// o  ADDRESS, variable number of octets, contains either an IPv4 or
///    IPv6 address, depending on FAMILY, which MUST be truncated to the
///    number of bits indicated by the SOURCE PREFIX-LENGTH field,
///    padding with 0 bits to pad to the end of the last octet needed.
/// o  A server receiving an ECS option that uses either too few or too
///    many ADDRESS octets, or that has non-zero ADDRESS bits set beyond
///    SOURCE PREFIX-LENGTH, SHOULD return FORMERR to reject the packet,
///    as a signal to the software developer making the request to fix
///    their implementation.
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
pub struct ClientSubnet {
    address: IpAddr,
    source_prefix: u8,
    scope_prefix: u8,
}

impl ClientSubnet {
    /// Construct a new EcsOption with the address, source_prefix and scope_prefix.
    pub fn new(address: IpAddr, source_prefix: u8, scope_prefix: u8) -> Self {
        Self {
            address,
            source_prefix,
            scope_prefix,
        }
    }

    /// Returns the length in bytes of the EdnsOption
    pub fn len(&self) -> u16 {
        // FAMILY: 2 octets
        // SOURCE PREFIX-LENGTH: 1 octets
        // SCOPE PREFIX-LENGTH: 1 octets
        // ADDRESS: runcated to the number of bits indicated by the SOURCE PREFIX-LENGTH field
        2 + 1 + 1 + self.addr_len()
    }

    /// Returns `true` if the length in bytes of the EcsOption is 0
    #[inline]
    pub fn is_empty(&self) -> bool {
        false
    }

    fn addr_len(&self) -> u16 {
        let source_prefix = self.source_prefix as u16;
        source_prefix / 8 + if source_prefix % 8 > 0 { 1 } else { 0 }
    }
}

impl BinEncodable for ClientSubnet {
    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
        let address = self.address;
        let source_prefix = self.source_prefix;
        let scope_prefix = self.scope_prefix;

        let addr_len = self.addr_len();

        match address {
            IpAddr::V4(ip) => {
                encoder.emit_u16(1)?; // FAMILY: IPv4
                encoder.emit_u8(source_prefix)?;
                encoder.emit_u8(scope_prefix)?;
                let octets = ip.octets();
                let addr_len = addr_len as usize;
                if addr_len <= octets.len() {
                    encoder.emit_vec(&octets[0..addr_len])?
                } else {
                    return Err(ProtoErrorKind::Message(
                        "Invalid addr length for encode EcsOption",
                    )
                    .into());
                }
            }
            IpAddr::V6(ip) => {
                encoder.emit_u16(2)?; // FAMILY: IPv6
                encoder.emit_u8(source_prefix)?;
                encoder.emit_u8(scope_prefix)?;
                let octets = ip.octets();
                let addr_len = addr_len as usize;
                if addr_len <= octets.len() {
                    encoder.emit_vec(&octets[0..addr_len])?
                } else {
                    return Err(ProtoErrorKind::Message(
                        "Invalid addr length for encode EcsOption",
                    )
                    .into());
                }
            }
        }
        Ok(())
    }
}

impl<'a> BinDecodable<'a> for ClientSubnet {
    fn read(decoder: &mut BinDecoder<'a>) -> ProtoResult<Self> {
        let family = decoder.read_u16()?.unverified();

        match family {
            1 => {
                // ipv4
                let source_prefix = decoder.read_u8()?.unverified();
                let scope_prefix = decoder.read_u8()?.unverified();
                let addr_len =
                    (source_prefix / 8 + if source_prefix % 8 > 0 { 1 } else { 0 }) as usize;
                let mut octets = Ipv4Addr::UNSPECIFIED.octets();
                for octet in octets.iter_mut().take(addr_len) {
                    *octet = decoder.read_u8()?.unverified();
                }
                Ok(Self {
                    address: IpAddr::from(octets),
                    source_prefix,
                    scope_prefix,
                })
            }
            2 => {
                // ipv6
                let source_prefix = decoder.read_u8()?.unverified();
                let scope_prefix = decoder.read_u8()?.unverified();
                let addr_len =
                    (source_prefix / 8 + if source_prefix % 8 > 0 { 1 } else { 0 }) as usize;
                let mut octets = Ipv6Addr::UNSPECIFIED.octets();
                for octet in octets.iter_mut().take(addr_len) {
                    *octet = decoder.read_u8()?.unverified();
                }

                Ok(Self {
                    address: IpAddr::from(octets),
                    source_prefix,
                    scope_prefix,
                })
            }
            _ => Err(ProtoErrorKind::Message("Invalid family type.").into()),
        }
    }
}

impl<'a> TryFrom<&'a ClientSubnet> for Vec<u8> {
    type Error = ProtoError;

    fn try_from(value: &'a ClientSubnet) -> Result<Self, Self::Error> {
        let mut bytes = Self::with_capacity(value.len() as usize); // today this is less than 8
        let mut encoder = BinEncoder::new(&mut bytes);
        value.emit(&mut encoder)?;
        bytes.shrink_to_fit();
        Ok(bytes)
    }
}

impl<'a> TryFrom<&'a [u8]> for ClientSubnet {
    type Error = ProtoError;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        let mut decoder = BinDecoder::new(value);
        Self::read(&mut decoder)
    }
}

impl From<ipnet::IpNet> for ClientSubnet {
    fn from(net: ipnet::IpNet) -> Self {
        Self {
            address: net.addr(),
            source_prefix: net.prefix_len(),
            scope_prefix: Default::default(),
        }
    }
}

impl FromStr for ClientSubnet {
    type Err = ipnet::AddrParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        ipnet::IpNet::from_str(s).map(ClientSubnet::from)
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::dbg_macro, clippy::print_stdout)]

    use super::*;

    #[test]
    #[cfg(feature = "dnssec")]
    fn test() {
        let mut rdata = OPT::default();
        rdata.insert(EdnsOption::DAU(SupportedAlgorithms::all()));

        let mut bytes = Vec::new();
        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
        assert!(rdata.emit(&mut encoder).is_ok());
        let bytes = encoder.into_bytes();

        println!("bytes: {bytes:?}");

        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
        let restrict = Restrict::new(bytes.len() as u16);
        let read_rdata = OPT::read_data(&mut decoder, restrict).expect("Decoding error");
        assert_eq!(rdata, read_rdata);
    }

    #[test]
    fn test_read_empty_option_at_end_of_opt() {
        let bytes: Vec<u8> = vec![
            0x00, 0x0a, 0x00, 0x08, 0x0b, 0x64, 0xb4, 0xdc, 0xd7, 0xb0, 0xcc, 0x8f, 0x00, 0x08,
            0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00,
        ];

        let mut decoder: BinDecoder<'_> = BinDecoder::new(&bytes);
        let read_rdata = OPT::read_data(&mut decoder, Restrict::new(bytes.len() as u16));
        assert!(
            read_rdata.is_ok(),
            "error decoding: {:?}",
            read_rdata.unwrap_err()
        );

        let opt = read_rdata.unwrap();
        let mut options = HashMap::default();
        options.insert(
            EdnsCode::Subnet,
            EdnsOption::Subnet("0.0.0.0/0".parse().unwrap()),
        );
        options.insert(
            EdnsCode::Cookie,
            EdnsOption::Unknown(10, vec![0x0b, 0x64, 0xb4, 0xdc, 0xd7, 0xb0, 0xcc, 0x8f]),
        );
        options.insert(EdnsCode::Keepalive, EdnsOption::Unknown(11, vec![]));
        let options = OPT::new(options);
        assert_eq!(opt, options);
    }

    #[test]
    fn test_write_client_subnet() {
        let expected_bytes: Vec<u8> = vec![0x00, 0x01, 0x18, 0x00, 0xac, 0x01, 0x01];
        let ecs: ClientSubnet = "172.1.1.1/24".parse().unwrap();
        let bytes = Vec::<u8>::try_from(&ecs).unwrap();
        println!("bytes: {bytes:?}");
        assert_eq!(bytes, expected_bytes);
    }

    #[test]
    fn test_read_client_subnet() {
        let bytes: Vec<u8> = vec![0x00, 0x01, 0x18, 0x00, 0xac, 0x01, 0x01];
        let ecs = ClientSubnet::try_from(bytes.as_slice()).unwrap();
        assert_eq!(ecs, "172.1.1.0/24".parse().unwrap());
    }
}