cdns-rs 2.0.0-next.0

A native Sync/Async Rust implementation of client DNS resolver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
/*-
 * cdns-rs - a simple sync/async DNS query library
 * 
 * Copyright (C) 2021  Aleksandr Morozov
 * Copyright (C) 2025  Aleksandr Morozov
 * Copyright (C) 2026  Aleksandr Morozov, 4neko.org
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::net::SocketAddr;
use std::fmt;
use std::ops::Index;
use std::time::Duration;
use std::time::Instant;

use crate::configuration::DnsConfigReader;
use crate::{DnsConfig, ResolveConfig, error::*};
use crate::internal_error;
use crate::parsers::cfg_resolv_parser::ResolveConfigFamily;

use super::common::*;

bitflags! {     
    /// Flags  which control the status of th DNS query    
    #[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] 
    pub struct QuerySetupFlags: u16  
    {    
        /// Sets the realtime counter to measure delay
        const MEASURE_TIME      = 0x0001; 

        /// Forces to ignore hosts file
        const IGNORE_HOSTS      = 0x0002;

        /// Try next NS on OK if answer is not Non-authoritative.
        const NEXT_NS_ON_OK     = 0x0004;
    }
}

/// A query override instance.
#[derive(Debug, Clone)]
pub struct QuerySetup
{
    /// Setups
    pub(crate) flags: QuerySetupFlags,

    /// Overrides the timeout duration for reply awaiting.
    pub(crate) timeout: Option<Duration>,
}

impl Default for QuerySetup
{
    fn default() -> Self 
    {
        return 
            Self 
            { 
                flags: 
                    QuerySetupFlags::empty(),
                timeout: 
                    None, 
            };
    }
}

impl QuerySetup
{
    pub(crate) 
    fn get_measure_time(&self) -> bool
    {
        return self.flags.intersects(QuerySetupFlags::MEASURE_TIME);
    }

    pub(crate) 
    fn get_ignore_hosts(&self) -> bool
    {
        return self.flags.intersects(QuerySetupFlags::IGNORE_HOSTS);
    }

    pub(crate) 
    fn get_next_ns_ok(&self) -> bool
    {
        return self.flags.intersects(QuerySetupFlags::NEXT_NS_ON_OK);
    }

    /// Turns on/off the time measurment whcih measure how many time went
    /// since query started for each response.
    pub 
    fn measure_time(mut self, flag: bool) -> Self
    {
        self.flags.set(QuerySetupFlags::MEASURE_TIME, flag);
        
        return self;
    }

    /// Turns on/off the option which when set is force to ignore lookup in
    /// /etc/hosts
    pub 
    fn ign_hosts(mut self, flag: bool) -> Self
    {
        self.flags.set(QuerySetupFlags::IGNORE_HOSTS, flag);

        return self;
    }

    /// Overrides the timeout. Can not be 0.
    pub 
    fn override_timeout(mut self, timeout: u64) -> Self
    {
        if timeout == 0
        {
            return self;
        }

        self.timeout = Some(Duration::from_secs(timeout));

        return self;
    }

    pub 
    fn get_timeout(&self, rc: &ResolveConfig) -> Duration
    {
        return self.timeout.unwrap_or(Duration::from_secs(rc.timeout as u64));
    }

    /// Resets the override timeout.
    pub 
    fn reset_override_timeout(&mut self)
    {
        self.timeout = None;
    }

    /// If set to `true` changes the behaviour of the resolver. By default
    /// resolver on receiving a response with OK status but non-authorative
    /// flag set considers this as ok. If this value is set, the resilver 
    /// will try to ask other NS if any.
    pub 
    fn try_next_ns(mut self, flag: bool) -> Self
    {
        self.flags.set(QuerySetupFlags::NEXT_NS_ON_OK, flag);

        return self;
    }

}

/// A [StatusBits] decoded response status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QDnsQueryRec
{
    /// Response is Ok and
    Ok,
    /// Server side error
    ServFail,
    /// Query does not exist, but meaningfull when `aa` is true
    NxDomain,
    /// A name server refuses to perform the specified operation
    Refused,
    /// A name server does not support the requested kind of query
    NotImpl,
    /// A message was truncated
    Truncated, 
    /// A fromat error
    FormError,
}

impl QDnsQueryRec
{
    /// Returns true if [QueryMode] is set to continue query other nameservers.  
    /// Returns false if there is no need to query other nameservers i.e 
    ///  [QueryMode::DefaultMode] or the response was from authotherative server.
    /// 
    /// If `not_aa_retry_next` is set to `true` and the result is `Ok` and `aa`
    /// is false, returns `true` i.e try next.
    pub(crate)
    fn try_next_nameserver(&self, aa: bool, not_aa_retry_next: bool) -> bool
    {
        match *self
        {
            Self::Ok => 
            {
                if not_aa_retry_next == true && aa == false
                {
                    return true;
                }

                return false;
            }
            Self::NxDomain =>
            {
                if aa == true
                {
                    // the response is from authotherative server
                    return false;
                }

                return true;
            },
            Self::Truncated =>
            {
                return true;
            },
            Self::Refused | Self::ServFail | Self::NotImpl | Self::FormError =>
            {
                return true;
            }
        }
    }

    pub(crate)
    fn should_try_tcp(&self) -> bool
    {
        return *self == Self::Truncated || *self == Self::ServFail || *self == Self::NxDomain;
    }
}

impl TryFrom<StatusBits> for QDnsQueryRec
{
    type Error = CDnsError;

    fn try_from(value: StatusBits) -> Result<Self, Self::Error> 
    {
        if value.contains(StatusBits::TRUN_CATION) == true
        {
            return Ok(QDnsQueryRec::Truncated);
        }
        else if value.contains(StatusBits::RESP_NOERROR) == true
        {
            /*let resps: Vec<QueryRec> = 
                ans.response.into_iter().map(|a| a.into()).collect();
            */
            return Ok(QDnsQueryRec::Ok);
        }
        else if value.contains(StatusBits::RESP_FORMERR) == true
        {
            return Ok(QDnsQueryRec::FormError);
        }
        else if value.contains(StatusBits::RESP_NOT_IMPL) == true
        {
            return Ok(QDnsQueryRec::NotImpl);
        }
        else if value.contains(StatusBits::RESP_NXDOMAIN) == true
        {
            return Ok(QDnsQueryRec::NxDomain);
        }
        else if value.contains(StatusBits::RESP_REFUSED) == true
        {
            return Ok(QDnsQueryRec::Refused);
        }
        else if value.contains(StatusBits::RESP_SERVFAIL) == true
        {
            return Ok(QDnsQueryRec::ServFail);
        }
        else
        {
            internal_error!(CDnsErrorType::DnsResponse(CDnsErrorDnsResponse::DnsInvalidStatusBits), 
                "response status bits unknwon result: '{}'", value.bits());
        };
    }
}


impl fmt::Display for QDnsQueryRec
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::Ok => 
                writeln!(f, "OK"),
            Self::ServFail =>
                writeln!(f, "SERVFAIL"),
            Self::NxDomain =>
                writeln!(f, "NXDOMAIN"),
            Self::Refused =>  
                writeln!(f, "REFUSED"),
            Self::NotImpl => 
                writeln!(f, "NOT IMPLEMENTED"),
            Self::Truncated =>
                writeln!(f, "TRUNCATED"),
            Self::FormError =>
                writeln!(f, "FORMAT ERROR"),
        }
    }
}

/// A results container. Each result is paired with the request.
#[derive(Debug, Default)]
pub struct QDnsQueryResult
{
    queries: BTreeMap<u64, CDnsResult<QDnsQuery>>,
}

impl IntoIterator for QDnsQueryResult 
{
    type Item = (u64, CDnsResult<QDnsQuery>);
    type IntoIter = std::collections::btree_map::IntoIter<u64, CDnsResult<QDnsQuery>>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter 
    {
        return self.queries.into_iter();
    }
}


impl Index<u64> for QDnsQueryResult
{
    type Output = CDnsResult<QDnsQuery>;

    fn index(&self, index: u64) -> &Self::Output 
    {
        return &self.queries.get(&index).unwrap();
    }
}

impl QDnsQueryResult
{
    pub(crate) 
    fn new() -> Self
    {
        return Self{ queries: BTreeMap::new() };
    }

    pub(crate) 
    fn push(&mut self, req_id: u64, resp: CDnsResult<QDnsQuery>)
    {
        self.queries.insert(req_id, resp);
    }

    pub(crate) 
    fn push_req(&mut self, req: &DnsRequest, resp: CDnsResult<QDnsQuery>)
    {
        self.queries.insert(req.get_assigned_id(), resp);
    }

    pub 
    fn is_empty(&self) -> bool
    {
        return self.queries.is_empty();
    }

    /// Checks if the response with the `req_id` presents in the 
    /// current instance.
    pub 
    fn contains_dnsreq(&self, req_id: u64) -> bool
    {
        return self.queries.contains_key(&req_id);
    }

    /// Extends (merges) the current instance with provided data.
    /// 
    /// * replaces answer with error to answer without error
    /// * inserts a new record (disregarding the result) 
    pub(crate)  
    fn extend(&mut self, other: Self, opts: &QuerySetup)
    {
        for (resp_id, new_resp) in other
        {
            let Some(prev_resp) = self.queries.get_mut(&resp_id)
            else
            {
                self.queries.insert(resp_id, new_resp);

                continue;
            };

            if new_resp.is_err() == false && prev_resp.is_err() == true
            {
                // replace with non error answer
                *prev_resp = new_resp;
            }
            else if new_resp.is_err() == true && prev_resp.is_err() == true
            {
                continue;
            }
            else if new_resp.as_ref().unwrap().should_check_next_ns(opts.get_next_ns_ok()) == false &&
                prev_resp.as_ref().unwrap().should_check_next_ns(opts.get_next_ns_ok()) == true
            {
                // replace with non error answer
                *prev_resp = new_resp;
            }

            // else just don't extend
        }
    }

    /// Returns the immutable iterator.
    pub 
    fn list_results(&self) -> std::collections::btree_map::Iter<'_, u64, Result<QDnsQuery, CDnsError>>
    {
        return self.queries.iter();
    }

    /// Simply returns all records which are not error, removing the assigned IDs.
    pub 
    fn get_result(self) -> CDnsResult<Vec<QDnsQuery>>
    {
        let ok = self.collect_ok();

        if ok.is_empty() == true
        {
            internal_error!(CDnsErrorType::DnsNotAvailable, "network error");
        }

        return Ok(ok);
    }

    /// Ger the result with specific ID.
    pub 
    fn get(&self, id: u64) -> Option<&Result<QDnsQuery, CDnsError>>
    {
        return self.queries.get(&id);
    }

    /// Returns [Result::Err] if any of the records contains error.
    pub 
    fn get_ok_or_error(self) ->CDnsResult<Vec<QDnsQuery>>
    {
        return
            self
                .queries
                .into_iter()
                .map(|e| e.1)
                .collect::<CDnsResult<Vec<QDnsQuery>>>();
    }

    /// Collects all responses which does not contain error. It does not mean
    /// that the answer was successfull.
    pub 
    fn collect_ok(self) -> Vec<QDnsQuery>
    {
        return 
            self
                .queries
                .into_iter()
                .filter(
                    |(_k, v)| 
                    v.is_ok()
                )
                .map(|(_, v)| v.unwrap())
                .collect();
    }

    /// Does the same as [Self::collect_ok] but preserves the assigned IDs.
    pub 
    fn collect_ok_with_id(self) -> BTreeMap<u64, QDnsQuery>
    {
        return 
            self
                .queries
                .into_iter()
                .filter(
                    |(_k, v)| 
                    v.is_ok()
                )
                .map(|(k, v)| (k, v.unwrap()))
                .collect();
    }

    /// Collects all responses which are not errors and contains the response.
    pub 
    fn collect_ok_with_answers(self) -> Vec<QDnsQuery>
    {
        return 
            self
                .queries
                .into_iter()
                .filter(
                    |(_k, v)| 
                    v.is_ok() && v.as_ref().unwrap().resp.is_empty() == false
                )
                .map(|(_, v)| v.unwrap())
                .collect();
    }

    /// Does the same as [Self::collect_ok_with_answers] but preserving the assigned IDs.
    pub 
    fn collect_ok_with_answers_with_id(self) -> BTreeMap<u64, QDnsQuery>
    {
        return 
            self
                .queries
                .into_iter()
                .filter(
                    |(_k, v)| 
                    v.is_ok() && v.as_ref().unwrap().resp.is_empty() == false
                )
                .map(|(k, v)| (k, v.unwrap()))
                .collect();
    }


    /// Splits the resukt into lists of [Result::Ok] and [Result::Err] where
    /// 0 - ok, 1 - error.
    pub 
    fn collect_split(self) -> (Vec<(u64, Result<QDnsQuery, CDnsError>)>, Vec<(u64, Result<QDnsQuery, CDnsError>)>)

    {
        return 
            self
                .queries
                .into_iter()
                .partition(|(_, v)|
                    v.is_ok()
                );
    }

}

impl fmt::Display for QDnsQueryResult
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        if self.is_empty() == false
        {
            for (req, qr) in self.list_results()
            {
                match qr
                {
                    Ok(r) => 
                        write!(f, "{}", r)?,
                    Err(e) =>
                        write!(f, "request: {}, error: {}", req, e)?
                }
                
            }
        }
        else
        {
            write!(f, "No DNS server available")?;
        }

        return Ok(());
    }
}

/// A structure which describes the query properties and contains the
/// results.
#[derive(Clone, Debug)]
pub struct QDnsQuery
{
    /// A realtime time elapsed for query
    pub elapsed: Option<Duration>,
    /// Server which performed the response and port number
    pub server: String,
    /// Flags
    pub flags: StatusBits,
    /// Authoratives section
    pub authoratives: Vec<DnsResponsePayload>,
    /// Responses
    pub resp: Vec<DnsResponsePayload>,
    /// Status
    pub status: QDnsQueryRec,
}

impl fmt::Display for QDnsQuery
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "Source: {} ", self.server)?;
        if let Some(ref el) = self.elapsed
        {
            write!(f, "{:.2?} ", el)?;
        }

        if self.is_authorative() == true
        {
            write!(f, "Authoritative answer")?;
        }
        else
        {
            write!(f, "Non-Authoritative answer")?;
        }

        if self.is_authentic_data() == true
        {
            write!(f, "AUTHETIC answer")?;
        }
        else
        {
            write!(f, "Non-AUTHETIC answer")?;
        }


        writeln!(f, "\n Authoritatives: {}", self.authoratives.len())?;

        if self.authoratives.len() > 0
        {
            for a in self.authoratives.iter()
            {
                writeln!(f, "{}", a)?;
            }

            writeln!(f, "")?;
        }

        writeln!(f, "Status: {}", self.status)?;

        writeln!(f, "Answers: {}", self.resp.len())?;

        if self.resp.len() > 0
        {
            for r in self.resp.iter()
            {
                writeln!(f, "{}", r)?;
            }

            writeln!(f, "")?;
        }

        return Ok(());
    }
}

impl IntoIterator for QDnsQuery
{
    type Item = DnsResponsePayload;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter 
    {
        self.resp.into_iter()
    }
}
 
impl QDnsQuery
{
    /// Returns true if the response is OK
    pub 
    fn is_ok(&self) -> bool
    {
        return self.status == QDnsQueryRec::Ok;
    }

    pub 
    fn is_authorative(&self) -> bool
    {
        return self.flags.contains(StatusBits::AUTH_ANSWER);
    }

    pub 
    fn get_elapsed_time(&self) -> Option<&Duration>
    {
        return self.elapsed.as_ref();
    }

    pub 
    fn get_server(&self) -> &String
    {
        return &self.server;
    }

    /// Returns the authorative server data if any
    pub 
    fn get_authoratives(&self) -> &[DnsResponsePayload]
    {
        return self.authoratives.as_slice();
    }

    /// Returns the responses if any
    pub 
    fn get_responses(&self) -> &[DnsResponsePayload]
    {
        return self.resp.as_slice();
    }

    /// Moves the responses from structure
    pub 
    fn move_responses(self) -> Vec<DnsResponsePayload>
    {
        return self.resp;
    }

    pub 
    fn get_status(&self) -> QDnsQueryRec
    {
        return self.status;
    }

    /// Tells if the next NS should be checked. The `not_aa_retry_next` adjusts the 
    /// behaviour, so if answer is `Ok`, the answer is not `aa` and `not_aa_retry_next`
    /// is set to true, returns true i.e check next.
    pub(crate)  
    fn should_check_next_ns(&self, not_aa_retry_next: bool) -> bool
    {
        return self.status.try_next_nameserver(self.is_authorative(), not_aa_retry_next);
    }

    pub 
    fn is_authentic_data(&self) -> bool
    {
        return self.flags.contains(StatusBits::ANSWER_AUTHN);
    }

    pub 
    fn is_checking_disabled(&self) -> bool
    {
        return self.flags.contains(StatusBits::CHECKING_DISABLED);
    }
}

impl QDnsQuery
{
    /// Constructs instance like it is from 'local' source but not from DNS server.
    pub(crate)  
    fn from_local(req_pl: Vec<DnsResponsePayload>, now: Option<&Instant>) -> QDnsQuery
    {
        let elapsed = now.map(|n| n.elapsed());

        return 
            Self
            {
                elapsed: 
                    elapsed,
                server: 
                    HOST_CFG_PATH.to_string(),
                flags: 
                    StatusBits::AUTH_ANSWER | StatusBits::CHECKING_DISABLED | StatusBits::RESP_NOERROR,
                authoratives: 
                    Vec::new(),
                status: 
                    QDnsQueryRec::Ok,
                resp: 
                    req_pl
            };
    }

    /// Constructs an instance from the remote response.
    pub(crate)  
    fn from_response(
        server: &SocketAddr, 
        ans_header: DnsHeader, 
        ans: DnsRequestAnswer, 
        now: Option<Instant>
    ) -> CDnsResult<Self>
    {
        return Ok(
            Self
            {
                elapsed: 
                    now.map_or(None, |n| Some(n.elapsed())),
                server: 
                    server.to_string(),
                flags: 
                    ans_header.status, //ans_header.status.contains(StatusBits::AUTH_ANSWER),
                authoratives: 
                    ans.authoratives,
                status: 
                    ans_header.status.try_into()?,
                resp: 
                    ans.response,
            }
        );
    }

}

/// An instance which collects the requests and keeps it pre-parsed
/// and prepared for submitting it to `resolver`.
/// 
/// Once created, can be cached to avoid creating it again.
/// 
/// ```ignore
///
/// let mut dns_req = 
///     QDnsRequests::make_empty(QuerySetup::default()).unwrap();
///   
/// dns_req.add_request(QType::SOA, "protonmail.com");
/// ```
#[derive(Clone, Debug)]
pub struct QDnsRequests
{
    /// A pre-ordered list of the requests, if more than one
    pub(crate) ordered_req_list: Vec<DnsRequest>,

    /// Overrides query options
    pub(crate) opts: QuerySetup,
}

impl QDnsRequests
{
    #[inline]
    pub(crate) 
    fn mirror<'t>(&'t self) -> Vec<&'t DnsRequest>
    {
        return self.ordered_req_list.iter().collect();
    }
}

impl QDnsRequests
{
    /// Initializes new empty storage for requests.
    /// 
    /// # Arguments
    /// 
    /// * `opts` - [QuerySetup] additional options or overrides. Use default() for default
    ///     values.
    /// 
    /// # Returns
    ///
    /// An instance is returned.
    pub 
    fn make_empty(opts: QuerySetup) -> Self
    {
        return
            Self
            {
                ordered_req_list: Vec::new(),
                opts: opts,
            };
    }

    /// Adds a new request to current instance. A `req_is` should be provided
    /// which helps to identify the respone in case if there are more than one
    /// in the `request`.
    /// 
    /// # Arguemnts
    /// 
    /// * `req_id` - a uniq ID.
    /// 
    /// * `qtype` - a [QType] type of the request
    /// 
    /// * `req_name` - a [Into] [QDnsName] which is target. i.e 'localhost' or 'domain.tld'
    ///     '127.0.0.1'.
    pub 
    fn add_request<R>(&mut self, req_id: u64, qtype: QType, req_name: R) -> CDnsResult<()>
    where 
        R: TryInto<QDnsName, Error = CDnsError>
    {
        let qnsname = req_name.try_into()?;

        self.ordered_req_list.push(DnsRequest::construct_lookup(req_id, qnsname, qtype)?);

        return Ok(());
    }

    /// A template which resolves `A` and `AAAA` records depending on the [ResolveConfig].
    pub 
    fn resolve_fqdn<R>(cfg: &DnsConfig<ResolveConfig>, req_id_4: u64, req_id_6: u64, req_name: R, opts: QuerySetup) -> CDnsResult<Self>
    where 
        R: TryInto<QDnsName, Error = CDnsError>
    {
        return 
            Self::resolve_a_aaaa_request(req_id_4, req_id_6, 
                cfg.read_config().family, req_name, opts);
    }

    /// This is helper which makes for you an A, AAAA query. The order of A and AAAA 
    /// is defined in the [ResolveConfig].
    /// 
    /// Use this function directly. Do not use [QDns::make_empty]
    /// 
    /// # Arguments
    /// 
    /// * `resolvers` - an [Option] value [Arc] [ResolveConfig] which can be used to 
    ///     override the system's `resolv.conf`
    /// 
    /// * `req_name` - a [Into] [QDnsName] which is target i.e 'localhost' or 'domain.tld'
    /// 
    /// * `opts` - [QuerySetup] additional options or overrides. Use default() for default
    ///     values.
    /// 
    /// # Returns
    /// 
    /// A [CDnsResult] is returned;
    /// 
    /// * [Result::Ok] - with Self as inner type
    /// 
    /// * [Result::Err] is returned with error description. The error may happen during attempt 
    ///     to read resolv config or obtain a cached verion.
    pub 
    fn resolve_a_aaaa_request<R>(req4_id: u64, req6_id: u64, res_fam: ResolveConfigFamily, 
        req_name_ref: R, opts: QuerySetup
    ) -> CDnsResult<Self>
    where 
        R: TryInto<QDnsName, Error = CDnsError>
    {
        let req_n = req_name_ref.try_into()?;

        // store the A and AAAA depending on order
        let reqs = 
            match res_fam
            {
                ResolveConfigFamily::INET4_INET6 => 
                {
                    vec![
                        DnsRequest::construct_lookup(req4_id, req_n.clone(), QType::A)?,
                        DnsRequest::construct_lookup(req6_id, req_n, QType::AAAA)?
                    ]
                },
                ResolveConfigFamily::INET6_INET4 => 
                {
                    vec![
                        DnsRequest::construct_lookup(req6_id, req_n.clone(), QType::AAAA)?,
                        DnsRequest::construct_lookup(req4_id, req_n, QType::A)?
                    ]
                },
                ResolveConfigFamily::INET6 => 
                {
                    vec![
                        DnsRequest::construct_lookup(req6_id, req_n, QType::AAAA)?,
                    ]
                },
                ResolveConfigFamily::INET4 => 
                {
                    vec![
                        DnsRequest::construct_lookup(req4_id, req_n.clone(), QType::A)?
                    ]
                }
                _ =>
                {
                    // set default

                    vec![
                        DnsRequest::construct_lookup(req4_id, req_n.clone(), QType::A)?,
                        DnsRequest::construct_lookup(req6_id, req_n, QType::AAAA)?,
                    ]
                }
            };

        
        
        return Ok(
            Self
            {
                ordered_req_list: reqs,
                opts: opts,
            }
        );
    }

    pub 
    fn resolve_reverse<R>(req_id: u64, fqdn: R, opts: QuerySetup) -> CDnsResult<QDnsRequests>
    where 
        R: AsRef<str>
    {
        let mut dns_req =  QDnsRequests::make_empty(opts);

        dns_req.add_request(req_id, QType::PTR, fqdn.as_ref())?;

        return Ok(dns_req);
    }

    pub 
    fn resolve_soa<R>(req_id: u64, fqdn: R, opts: QuerySetup) -> CDnsResult<QDnsRequests>
    where 
        R: AsRef<str>
    {
        let mut dns_req =  QDnsRequests::make_empty(opts);

        dns_req.add_request(req_id, QType::SOA, fqdn.as_ref())?;


        return Ok(dns_req);
    }

    pub 
    fn resolve_mx<R>(req_id: u64, fqdn: R, opts: QuerySetup) -> CDnsResult<QDnsRequests>
    where 
        R: AsRef<str>
    {
        let mut dns_req =  QDnsRequests::make_empty(opts);

        dns_req.add_request(req_id, QType::MX, fqdn.as_ref())?;

        return Ok(dns_req);
    }
}