cdns_rs/
common.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
/*-
 * cdns-rs - a simple sync/async DNS query library
 * Copyright (C) 2020  Aleksandr Morozov
 * 
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use std::{cmp::Ordering, fmt, net::{IpAddr, Ipv4Addr, Ipv6Addr}, path::Path, sync::LazyLock};
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};

use crate::{error::*, query_private::QDnsReq, cfg_resolv_parser::ResolveConfigLookup, cfg_host_parser::HostnameEntry};
use crate::internal_error;

use super::cfg_resolv_parser::ResolveConfig;

/// A location on the disk where resolv.conf is located
pub const RESOLV_CFG_PATH: &'static str = "/etc/resolv.conf";

/// A hosts file location on disk
pub const HOST_CFG_PATH: &'static str = "/etc/hosts";

pub static RESOLV_CFG_PATH_P: LazyLock<&'static Path> = LazyLock::new(|| {Path::new(RESOLV_CFG_PATH)});
pub static HOST_CFG_PATH_P: LazyLock<&'static Path> = LazyLock::new(|| {Path::new(HOST_CFG_PATH)});

/// A nsswitch location
pub const NSSWITCH_CFG_PATH: &'static str = "/etc/nsswitch.conf";

const IN_ADDR_ARPA: &[u8] = b"\x07in-addr\x04arpa\x00";
const IN_ADDR6_ARPA: &[u8] = b"\x03ip6\x04arpa\x00";

/// Default BIND for IPv4
pub const IPV4_BIND_ALL: IpAddr = IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0));
/// Default BIND for IPv6
pub const IPV6_BIND_ALL: IpAddr = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));


/// Converts a part of the octec of IP to printable hex i.e valid range is from
/// 0 up to 15 will be converted to 0x30..0x39 and 'a'..'f'.
/// 
/// # Arguments
/// 
/// * `b` - a part of the octec
/// 
/// # Returns
/// 
/// * u8 an ASCII representation
/// 
/// # Throws
/// 
/// Panic when input b >= 16
pub 
fn byte2hexchar(b: u8) -> u8
{
    match b
    {
        0..=9 => return '0' as u8 + b,
        10..=15 => return 'a' as u8 + (b - 10),
        _ => panic!("out of hex range!")
    }
}

/// Converts [IpAddr] to sequence of bytes coded specially for the payload
/// of package.
/// 
/// # Arguments
/// 
/// * `ip` - the argument with IP address
/// 
/// # Returns
/// 
/// * [CDnsResult] with vector of coded data
pub 
fn ip2pkt(ip: &IpAddr) -> CDnsResult<Vec<u8>>
{    
    match *ip
    {
        IpAddr::V4(ref ipv4) =>
            return ipv4_pkt(ipv4),
        IpAddr::V6(ref ipv6) =>
            return ipv6_pkt(ipv6)
    };
}

const MAX_NAME_LEN: usize = 63;

pub 
fn ipv4_pkt(ip: &Ipv4Addr) -> CDnsResult<Vec<u8>>
{    

    // pre allocate space
    let mut out: Vec<u8> = Vec::with_capacity(16 + IN_ADDR_ARPA.len());
    
    let mut octets = ip.octets();
    octets.reverse();

    for oct in octets
    {
        let str_oct = oct.to_string();

        if str_oct.len() > 3
        {
            internal_error!(
                CDnsErrorType::InternalError, 
                "domain component too long, len: '{}' oct: '{}'", 
                str_oct.len(), str_oct
            );
        }

        let ln: u8 = str_oct.len() as u8;

        out.push(ln);
        out.extend(str_oct.as_bytes());
    }

    out.extend(IN_ADDR_ARPA);

    return Ok(out);
}

pub 
fn ipv6_pkt(ip: &Ipv6Addr) -> CDnsResult<Vec<u8>>
{    
    // pre allocate space
    let mut out: Vec<u8> = Vec::with_capacity(32 + IN_ADDR6_ARPA.len());
    
    let mut octets = ip.octets();
    octets.reverse();

    for oct in octets
    {
        let h_oct = byte2hexchar((oct & 0xF0) >> 4);
        //format!("{:x}", (oct & 0xF0) >> 4);
        let l_oct = byte2hexchar(oct & 0x0F);
        //format!("{:x}", oct & 0x0F);

        //let ln: u8 = str_oct.len() as u8;

        out.push(1);
        out.push(l_oct);
        //out.extend(l_oct.as_bytes());
        out.push(1);
        out.push(h_oct);
    }

    out.extend(IN_ADDR6_ARPA);

    return Ok(out);
}

pub 
fn name2pkt(name: &str) -> CDnsResult<Vec<u8>>
{    
    // pre allocate space
    let mut out: Vec<u8> = Vec::with_capacity(name.len() + 2);
    
    for n in name.split(".")
    {
        if n.len() >= MAX_NAME_LEN
        {
            internal_error!(CDnsErrorType::InternalError, "name too long: '{}' in: '{}'", n.len(), name);
        }

        out.push((n.len() & 0xFF) as u8);
        out.extend(n.as_bytes());
    }

    out.push(0);

    return Ok(out);
}


/// A two octet code which specifies the type of the query.
/// TYPE fields are used in resource records.  Note that these types are a
/// subset of QTYPEs.
/// QTYPE fields appear in the question part of a query.  QTYPES are a
/// superset of TYPEs, hence all TYPEs are valid QTYPEs.
#[repr(u16)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QType
{
    /// 1 a host address
    A = 1,
    /// 2 an authoritative name server
    NS = 2,
    /// 3 a mail destination (Obsolete - use MX)
    MD = 3,
    /// 4 a mail forwarder (Obsolete - use MX)
    MF = 4,
    /// 5 the canonical name for an alias
    CNAME = 5,
    /// 6 marks the start of a zone of authority
    SOA = 6,
    /// 7 a mailbox domain name (EXPERIMENTAL)
    MB = 7,
    /// 8 a mail group member (EXPERIMENTAL)
    MG = 8,
    /// 9 a mail rename domain name (EXPERIMENTAL)
    MR = 9,
    /// 10 a null RR (EXPERIMENTAL)
    NULL = 10,
    /// 11 a well known service description
    WKS = 11,
    /// 12 a domain name pointer
    PTR = 12,
    /// 13 host information
    HINFO = 13,
    /// 14 mailbox or mail list information
    MINFO = 14,
    /// 15 mail exchange
    MX = 15,
    /// 16 text strings
    TXT = 16,
    /// 18 AFS database record 
    AFSDB = 18,
    /// 25 Key record
    KEY = 25,
    /// 28 IPv6 address record
    AAAA = 28,
    /// 37 Certificate records
    CERT = 37,
    /// 43 Delegation signer
    DS = 43,
    /// 46 DNSSEC signature
    RRSIG = 46,
    /// 47 Next Secure record
    NSEC = 47,
    /// DNS Key record
    DNSKEY = 48,
    /// 50 Next Secure record version 3
    NSEC3 = 50,
    /// 51 NSEC3 parameters
    NSEC3PARAM = 51,
    /// 59 Child DS 
    CDS = 59,
    /// 60 Child copy of DNSKEY record, for transfer to parent
    CDNSKEY = 60,
    /// OpenPGP public key record 
    OPENPGPKEY = 61,
    // ---- QTYPE ----
    /// 252 A request for a transfer of an entire zone
    AXFR = 252,
    /// 253 A request for mailbox-related records (MB, MG or MR)
    MAILB = 253,
    /// 254 A request for mail agent RRs (Obsolete - see MX)
    MAILA = 254,
    /// 257 Certification Authority Authorization 
    CAA = 257,
    /// *
    ALL = 255,
    /// 32769 DNSSEC Lookaside Validation record
    DLV = 32769,
}

impl Default for QType
{
    fn default() -> Self 
    {
        return Self::A;    
    }
}


impl Into<u16> for QType
{
    fn into(self) -> u16 
    {
        return self as u16;
    }
}

impl fmt::Display for QType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        match *self
        {
            Self::A          => write!(f, "A"),
            Self::NS         => write!(f, "NS"),
            Self::MD         => write!(f, "MD"),
            Self::MF         => write!(f, "MF"),
            Self::CNAME      => write!(f, "CNAME"),
            Self::SOA        => write!(f, "SOA"),
            Self::MB         => write!(f, "MB"),
            Self::MG         => write!(f, "MG"),
            Self::MR         => write!(f, "MR"),
            Self::NULL       => write!(f, "NULL"),
            Self::WKS        => write!(f, "WKS"),
            Self::PTR        => write!(f, "PTR"),
            Self::HINFO      => write!(f, "HINFO"),
            Self::MINFO      => write!(f, "MINFO"),
            Self::MX         => write!(f, "MX"),
            Self::TXT        => write!(f, "TXT"),
            Self::AFSDB      => write!(f, "AFSDB"),
            Self::KEY        => write!(f, "KEY"),
            Self::AAAA       => write!(f, "AAAA"),
            Self::CERT       => write!(f, "CERT"),
            Self::DS         => write!(f, "DS"),
            Self::RRSIG      => write!(f, "RRSIG"),
            Self::NSEC       => write!(f, "NSEC"),
            Self::DNSKEY     => write!(f, "DNSKEY"),
            Self::NSEC3      => write!(f, "NSEC"),
            Self::NSEC3PARAM => write!(f, "NSEC3PARAM"),
            Self::CDS        => write!(f, "CDS"),
            Self::CDNSKEY    => write!(f, "CDNSKEY"),
            Self::OPENPGPKEY => write!(f, "OPENPGPKEY"),
            Self::AXFR       => write!(f, "AXFR"),
            Self::MAILB      => write!(f, "MAILB"),
            Self::MAILA      => write!(f, "MAILA"),
            Self::CAA        => write!(f, "CAA"),
            Self::ALL        => write!(f, "ALL"),
            Self::DLV        => write!(f, "DLV"),
        }
    }
}


impl QType
{
    pub 
    fn ipaddr_match(&self, ip: &IpAddr) -> bool
    {
        match *self
        {
            Self::A => return ip.is_ipv4(),
            Self::AAAA => return ip.is_ipv6(),
            _ => false,
        }
    }

    pub 
    fn u16_to_qtype(value: u16) -> CDnsResult<QType>
    {
        match value
        {
            x if x == Self::AXFR as u16    => return Ok(Self::AXFR),
            x if x == Self::MAILB as u16   => return Ok(Self::MAILB),
            x if x == Self::MAILA as u16   => return Ok(Self::MAILA),
            x if x == Self::ALL as u16     => return Ok(Self::ALL),
            x if x == Self::DLV as u16     => return Ok(Self::DLV),
            _ => return Self::u16_to_type(value),
        }
    }

    pub 
    fn u16_to_type(value: u16) -> CDnsResult<QType>
    {

        match value
        {
            x if x == Self::A as u16            => return Ok(Self::A),
            x if x == Self::NS as u16           => return Ok(Self::NS),
            x if x == Self::MD as u16           => return Ok(Self::MD),
            x if x == Self::MF as u16           => return Ok(Self::MF),
            x if x == Self::CNAME as u16        => return Ok(Self::CNAME),
            x if x == Self::SOA as u16          => return Ok(Self::SOA),
            x if x == Self::MB as u16           => return Ok(Self::MB),
            x if x == Self::MG as u16           => return Ok(Self::MG),
            x if x == Self::MR as u16           => return Ok(Self::MR),
            x if x == Self::NULL as u16         => return Ok(Self::NULL),
            x if x == Self::WKS as u16          => return Ok(Self::WKS),
            x if x == Self::PTR as u16          => return Ok(Self::PTR),
            x if x == Self::HINFO as u16        => return Ok(Self::HINFO),
            x if x == Self::MINFO as u16        => return Ok(Self::MINFO),
            x if x == Self::MX as u16           => return Ok(Self::MX),
            x if x == Self::TXT as u16          => return Ok(Self::TXT),
            x if x == Self::AFSDB as u16        => return Ok(Self::AFSDB),
            x if x == Self::KEY as u16          => return Ok(Self::KEY),
            x if x == Self::AAAA as u16         => return Ok(Self::AAAA),
            x if x == Self::CERT as u16         => return Ok(Self::CERT),
            x if x == Self::DS as u16           => return Ok(Self::DS),
            x if x == Self::RRSIG as u16        => return Ok(Self::RRSIG),
            x if x == Self::NSEC as u16         => return Ok(Self::NSEC),
            x if x == Self::DNSKEY as u16       => return Ok(Self::DNSKEY),
            x if x == Self::NSEC3 as u16        => return Ok(Self::NSEC3),
            x if x == Self::NSEC3PARAM as u16   => return Ok(Self::NSEC3PARAM),
            x if x == Self::CDS as u16          => return Ok(Self::CDS),
            x if x == Self::CDNSKEY as u16      => return Ok(Self::CDNSKEY),
            x if x == Self::OPENPGPKEY as u16   => return Ok(Self::OPENPGPKEY),
            _ => internal_error!(CDnsErrorType::DnsResponse, "unknown request record type: '{}'", value),
        }
    }
}


/// A two octet code that specifies the class of the query.
/// 
/// 
#[repr(u16)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QClass
{
    /// the Internet 1
    IN = 1,
    /// the CSNET class (Obsolete) 2
    CS = 2,
    /// the CHAOS class 3
    CH = 3,
    /// Hesiod [Dyer 87] 4
    HS = 4,
    
    //  --- QClass
    /// any class 255
    ALL = 255,
}

impl fmt::Display for QClass
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::IN  => write!(f, "IN"),
            Self::CS  => write!(f, "CS"),
            Self::CH  => write!(f, "CH"),
            Self::HS  => write!(f, "HS"),
            Self::ALL => write!(f, "ALL"),
        }
    }
}

impl Default for QClass
{
    fn default() -> Self 
    {
        return Self::IN;    
    }
}

impl Into<u16> for QClass
{
    fn into(self) -> u16 
    {
        return self as u16;
    }
}

impl QClass
{
    /// Converts u16 to enum [QClass].
    /// 
    /// QCLASS fields appear in the question part of a query.  QCLASS are a
    /// superset of CLASSes, hence all CLASSes are valid QCLASSes.
    pub 
    fn u16_to_qclass(value: u16) -> CDnsResult<QClass>
    {
        match value
        {
            x if x == QClass::ALL as u16 => return Ok(QClass::ALL),
            _ => Self::u16_to_class(value),
        }
    }

    /// Converts u16 to enum [QClass], but for the response part of a query.
    pub 
    fn u16_to_class(value: u16) -> CDnsResult<QClass>
    {
        match value
        {
            x if x == QClass::IN as u16 => return Ok(QClass::IN),
            x if x == QClass::CS as u16 => return Ok(QClass::CS),
            x if x == QClass::CH as u16 => return Ok(QClass::CH),
            x if x == QClass::HS as u16 => return Ok(QClass::HS),
            _ => internal_error!(CDnsErrorType::DnsResponse, "unknown QCLASS type: '{}'", value),
        }
    }
}

// (req.status & !StatusBits::OPCODE_STANDARD) | ...
// () 

bitflags! {     
    /// Flags  which control the status of th DNS query    
    #[derive(Default, Debug, Copy, Clone, PartialEq, Eq)] 
    pub struct StatusBits: u16  
    {     
        // Pkt type Request/Result R/W    
        /// A request/response bit, when 1 - response
        const QR_RESP           = 0x8000;

        // Request Type (Write only)
        /// a standard query (QUERY) USE inverse to reset
        const OPCODE_STANDARD   = 0x87FF;
        /// an inverse query (IQUERY)
        const OPCODE_IQUERY     = 0x0040;
        /// a server status request (STATUS)
        const OPCODE_STATUS     = 0x0020;
        // reserved for future use 3-15
        // 0x4000 .. 0x0800

        /// AA  Authoritative Answer (Read only)
        /// Authoritative Answer - this bit is valid in responses,
        /// and specifies that the responding name server is an
        /// authority for the domain name in question section.
        const AUTH_ANSWER       = 0x0400;

        /// TrunCation (Read only)
        /// TrunCation - specifies that this message was truncated
        /// due to length greater than that permitted on the transmission channel.
        const TRUN_CATION       = 0x0200;

        /// RD Recursion desired (write only)
        /// Recursion Desired - this bit may be set in a query and
        /// is copied into the response.  If RD is set, it directs
        /// the name server to pursue the query recursively.
        /// Recursive query support is optional.
        const RECURSION_DESIRED = 0x0100;

        /// RA Recursion available (read only)
        /// Recursion Available - this be is set or cleared in a
        /// response, and denotes whether recursive query support is
        /// available in the name server.
        const RECURSION_AVAIL   = 0x0080;

        /// Z Zero reserver
        /// Reserved for future use.  Must be zero in all queries
        /// and responses.
        const RSERVER0          = 0x0040; 

        const ANSWER_AUTHN      = 0x0020; 
        const NON_AUTH_DATA     = 0x0010; 

        // RCODE response code 

        /// No error condition
        const RESP_NOERROR      = 0x0000; 
        /// Format error - The name server was unable to interpret the query.
        const RESP_FORMERR      = 0x0001; 
        /// Server failure - The name server was unable to process this query due to a
        /// problem with the name server.
        const RESP_SERVFAIL     = 0x0002; 
        /// Name Error - Meaningful only for responses from an authoritative name
        /// server, this code signifies that the domain name referenced in the query does
        /// not exist.
        const RESP_NXDOMAIN     = 0x0003;
        /// Not Implemented - The name server does not support the requested kind of query.
        const RESP_NOT_IMPL     = 0x0004; 
        /// Refused - The name server refuses to perform the specified operation for
        /// policy reasons.
        const RESP_REFUSED      = 0x0005; 
        // ..= 0x000F
    }
}

/// An structure for the target in request.
/// Implements From for [IpAddr], [Ipv4Addr], [Ipv6Addr], [str]
/// In case if IP address is in the human readable 'string' format
/// it will be stored as Name. And later the code will try to convert it
/// to IP address before returing as string.
#[derive(Clone, Debug, Hash)]
pub enum QDnsName
{
    //Ip(&'temp IpAddr),
    IpV4(Ipv4Addr),
    IpV6(Ipv6Addr),
    Name(String),
}

impl QDnsName
{
    /// Answers if current type is IpV4.
    /// But does not performs check if Name is an IP in str format
    pub
    fn is_ipv4(&self) -> bool
    {
        match *self
        {
            Self::IpV4(_) => return true,
            _ => return false,
        }
    }

    /// Answers if current type is IpV6.
    /// But does not performs check if Name is an IP in str format
    pub 
    fn is_ipv6(&self) -> bool
    {
        match *self
        {
            Self::IpV6(_) => return true,
            _ => return false,
        }
    }

    /// Answers if current type is IpV4 or IpV6.
    /// But does not performs check if Name is an IP in str format
    pub 
    fn is_ip(&self) -> bool
    {
        match *self
        {
            Self::IpV4(_) => return true,
            Self::IpV6(_) => return true,
            _ => return false,
        }
    }

    /// Returns the type of the IP address version in [QType] format.
    pub 
    fn get_ip_qtype(&self) -> Option<QType>
    {
        match *self
        {
            Self::IpV4(_) => return Some(QType::A),
            Self::IpV6(_) => return Some(QType::AAAA),
            Self::Name(_) =>
            {
                return None;
            }
        }
    }
}

impl Eq for QDnsName {}

impl PartialEq for QDnsName
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self == other;    
    }
}

impl PartialEq<str> for QDnsName
{
    fn eq(&self, other: &str) -> bool 
    {
        match *self
        {
            Self::Name(ref name) => return name == other,
            Self::IpV4(ref ip) =>
            {
                if let Ok(other_ip) = other.parse::<Ipv4Addr>()
                {   
                    return &other_ip == ip;
                }
                
                return false;
            },
            Self::IpV6(ref ip) =>
            {
                if let Ok(other_ip) = other.parse::<Ipv6Addr>()
                {
                    return &other_ip == ip;
                }

                return false;
            }
        }
    }
}

impl From<&IpAddr> for QDnsName
{
    fn from(ip: &IpAddr) -> Self 
    {
        match *ip
        {
            IpAddr::V4(ref ip) => 
                return Self::IpV4(ip.clone()),
            IpAddr::V6(ref ip) => 
                return Self::IpV6(ip.clone()),
        }
    }
}

impl From<IpAddr> for QDnsName
{
    fn from(ip: IpAddr) -> Self 
    {
        match ip
        {
            IpAddr::V4(ip) => 
                return Self::IpV4(ip),
            IpAddr::V6(ip) => 
                return Self::IpV6(ip),
        }
    }
}

impl From<&Ipv4Addr> for QDnsName
{
    fn from(ip: &Ipv4Addr) -> Self 
    {
        return Self::IpV4(ip.clone());
    }
}

impl From<Ipv4Addr> for QDnsName
{
    fn from(ip: Ipv4Addr) -> Self 
    {
        return Self::IpV4(ip);
    }
}

impl From<&Ipv6Addr> for QDnsName
{
    fn from(ip: &Ipv6Addr) -> Self 
    {
        return Self::IpV6(ip.clone());
    }
}

impl From<Ipv6Addr> for QDnsName
{
    fn from(ip: Ipv6Addr) -> Self 
    {
        return Self::IpV6(ip);
    }
}

impl From<&str> for QDnsName
{
    fn from(name: &str) -> Self 
    {
        let ipp = name.parse::<IpAddr>();
        if ipp.is_err()
        {
            return Self::Name(name.to_string());
        }
        else
        {
            return QDnsName::from(ipp.unwrap());
        }
    }
}

impl TryInto<Vec<u8>> for QDnsName
{
    type Error = CDnsError;
    fn try_into(self) -> Result<Vec<u8>, Self::Error> 
    {
        match self
        {
            Self::IpV4(ref ip) =>
            {
                return ipv4_pkt(ip);
            },
            Self::IpV6(ref ip) =>
            {
                return ipv6_pkt(ip);
            },
            Self::Name(ref name) =>
            {
                if let Ok(ip) = name.parse::<Ipv4Addr>()
                {   
                    return ipv4_pkt(&ip);
                }
                else if let Ok(ip) = name.parse::<Ipv6Addr>()
                {
                    return ipv6_pkt(&ip);
                }
                else
                {
                    return name2pkt(name);
                }
            }
        }
    }
}

impl From<&QDnsName> for String
{
    fn from(dnsname: &QDnsName) -> Self 
    {
        match *dnsname
        {
            QDnsName::IpV4(ref ip) =>
            {
                return ip.to_string();
            },
            QDnsName::IpV6(ref ip) =>
            {
                return ip.to_string();
            },
            QDnsName::Name(ref name) =>
            {
                return name.to_string();
            }
        }
    }
}


impl TryFrom<&QDnsName> for IpAddr
{
    type Error = CDnsError;
    fn try_from(value: &QDnsName) -> Result<Self, Self::Error> 
    {
        match *value
        {
            QDnsName::IpV4(ref ip) =>
            {
                return Ok(IpAddr::V4(ip.clone()));
            },
            QDnsName::IpV6(ref ip) =>
            {
                return Ok(IpAddr::V6(ip.clone()));
            },
            QDnsName::Name(ref name) =>
            {
                if let Ok(ip) = name.parse::<Ipv4Addr>()
                {   
                    return Ok(IpAddr::V4(ip.clone()));
                }
                else if let Ok(ip) = name.parse::<Ipv6Addr>()
                {
                    return Ok(IpAddr::V6(ip.clone()));
                }
                else
                {
                    internal_error!(CDnsErrorType::InternalError, "not ip address!")
                }
            }
        }
    }
}


impl TryFrom<QDnsName> for IpAddr
{
    type Error = CDnsError;
    fn try_from(value: QDnsName) -> Result<Self, Self::Error> 
    {
        match value
        {
            QDnsName::IpV4(ip) =>
            {
                return Ok(IpAddr::V4(ip));
            },
            QDnsName::IpV6(ip) =>
            {
                return Ok(IpAddr::V6(ip));
            },
            QDnsName::Name(ref name) =>
            {
                if let Ok(ip) = name.parse::<Ipv4Addr>()
                {   
                    return Ok(IpAddr::V4(ip));
                }
                else if let Ok(ip) = name.parse::<Ipv6Addr>()
                {
                    return Ok(IpAddr::V6(ip));
                }
                else
                {
                    internal_error!(CDnsErrorType::InternalError, "not ip address!")
                }
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DnsHeader
{
    /// A 16 bit identifier assigned by the program that
    /// generates any kind of query.
    pub id: u16,

    /// Query control flags
    pub status: StatusBits,

    /// an unsigned 16 bit integer specifying the number of
    /// entries in the question section.
    pub qdcount: u16,

    /// an unsigned 16 bit integer specifying the number of
    /// resource records in the answer section.
    pub ancount: u16,

    /// an unsigned 16 bit integer specifying the number of name
    /// server resource records in the authority records
    /// section.
    pub nscount: u16,

    /// an unsigned 16 bit integer specifying the number of
    /// resource records in the additional records section.
    pub arcount: u16,
}


#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DnsRequestAnswer
{
    /// request header
    pub header: DnsHeader,
    /// Query content
    pub request: DnsRequestPayload,
    /// Resonse section
    pub response: Vec<DnsResponsePayload>,
    /// Additional RR
    pub additional: Vec<DnsResponsePayload>,
    /// Authortative nameservers
    pub authoratives: Vec<DnsResponsePayload>,
}

impl DnsRequestAnswer
{
    /// Validates the content
    /// 
    /// # Arguments
    /// 
    /// * `req` - a request which was sent 
    pub 
    fn verify(&self, req: &DnsRequestHeader) -> CDnsResult<()>
    {
        if self.header.id != req.header.id
        {
            internal_error!(
                CDnsErrorType::DnsResponse, 
                "request and response ID did not match: '{}' != '{}'", 
                req.header.id, self.header.id
            );
        }

        // check if request matches with what we sent previously
        if self.request != req.payload
        {
            internal_error!(CDnsErrorType::DnsResponse, 
                "received request section is different from sent");
        }
        else if req.payload.qtype != QType::ALL
        {
            // check qtype matches requested. (is it correct?)
            if req.payload.qtype != self.request.qtype
            {
                internal_error!(
                    CDnsErrorType::DnsResponse, 
                    "requested QTYPE differ received TYPE: '{}' != '{}'", 
                    req.payload.qtype, 
                    self.request.qtype
                );
            }
        }
        else if self.header.status.contains(StatusBits::TRUN_CATION) == true
        {
            internal_error!(CDnsErrorType::MessageTruncated, 
                "DNS response was truncated, aborting processing");
        }

        return Ok(());
    }

}

#[derive(Clone, Debug, Default)]
pub struct DnsRequestHeader
{
    /// request header
    pub header: DnsHeader,
    /// Query content
    pub payload: DnsRequestPayload,
}

impl Eq for DnsRequestHeader {}

impl PartialEq for DnsRequestHeader
{
    fn eq(&self, other: &DnsRequestHeader) -> bool 
    {
        return self.header.id == other.header.id;
    }
}

impl Ord for DnsRequestHeader 
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        // Sort in reverse order
        return self.header.id.cmp(&other.header.id);
    }
}

impl PartialOrd for DnsRequestHeader 
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> 
    {
        return Some(self.cmp(other));
    }
}

impl Hash for DnsRequestHeader
{
    fn hash<H: Hasher>(&self, state: &mut H) 
    {
        self.header.id.hash(state);
    }
}

impl Borrow<u16> for DnsRequestHeader
{
    fn borrow(&self) -> &u16 
    {
        return &self.header.id;
    }
}



impl DnsRequestHeader
{
    pub 
    fn regenerate_id(&mut self)
    {
        self.header.id = rand::random();
    }

    pub 
    fn get_id(&self) -> u16
    {
        return self.header.id;
    }

    pub 
    fn from_qdns_req(qrec: &QDnsReq, resolvers: &ResolveConfig) -> CDnsResult<Self>
    {
        if resolvers.lookup.contains(ResolveConfigLookup::BIND) == true
        {
            return DnsRequestHeader::construct_lookup(qrec.get_req_name().clone(), *qrec.get_type());
        }
        else
        {
            panic!("QDnsReq::get_header() misuse!");
        };
    }

    pub 
    fn derive(&self) -> Self
    {
        let header = 
            DnsHeader
            {
                id: rand::random(),
                status: self.header.status,
                qdcount: self.header.qdcount,
                ancount: self.header.ancount,
                nscount: self.header.nscount,
                arcount: self.header.arcount,
            };

        return DnsRequestHeader{ header: header, payload: self.payload.clone() };
    }

    /// Constructs the request from input.
    pub
    fn construct_lookup(name: QDnsName, qtype: QType) -> CDnsResult<DnsRequestHeader>
    {
        //let rng = rand::thread_rng();
        // preparing status register
        let mut status: StatusBits = StatusBits::empty();
        status = (status & !StatusBits::OPCODE_STANDARD) | StatusBits::RECURSION_DESIRED;

        // constructing request structure
        let mut req: DnsRequestHeader = DnsRequestHeader{ ..Default::default() };

        req.header.id = rand::random();
        req.header.status = status;
        req.header.qdcount = 1;

        // creating payload request
        req.payload = DnsRequestPayload::new(name.try_into()?, qtype, QClass::IN);

        
        /*let pkt = req.to_bytes().map_err(|e|
            internal_error_map!(CDnsErrorType::InternalError, "{}", e)
        )?;*/

        return Ok(req);
    }

}

/// A request payload with (request) lines.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DnsRequestPayload
{
    /// a domain name represented as a sequence of labels
    pub qname: Vec<u8>,

    /// a two octet code which specifies the type of the query.
    pub qtype: QType,
    
    /// a two octet code that specifies the class of the query.
    pub qclass: QClass,
}

impl DnsRequestPayload
{
    pub 
    fn new(qname: Vec<u8>, qtype: QType, qclass: QClass) -> Self
    {
        return DnsRequestPayload{ qname: qname, qtype: qtype.into(), qclass: qclass.into() };
    }
}

/// A response section
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DnsResponsePayload
{
    // A domain name that was queried, in the same format as the QNAME in the question
    pub name: String,
    /// Two octets containing one of th type codes.
    pub dtype: QType,
    /// Two octets which specify the class of the data in the RDATA field
    pub class: QClass,
    /// specifies the time interval that the resource record may be cached before the source
    /// of the information should again be consulted
    pub ttl: i32,
    /// specifies the length in octets of the RDATA field
    pub rdlength: u16,
    /// a variable length string of octets that describes the resource
    pub rdata: DnsRdata,
}

impl DnsResponsePayload
{
    /// Creates a record from [HostnameEntry], but only for types like
    /// A, AAAA, PTR
    pub(crate)
    fn new_local(dtype: QType, data: &HostnameEntry) -> CDnsResult<Vec<Self>>
    {

        match dtype
        {
            QType::A => 
            {
                let mut out: Vec<Self> = Vec::with_capacity(1);

                let ipv4: Ipv4Addr = 
                    if let IpAddr::V4(ipv4) = data.get_ip() 
                    {
                        ipv4.clone()
                    }
                    else
                    {
                        internal_error!(CDnsErrorType::InternalError, "wrong data type");
                    };

                out.push(
                    DnsResponsePayload
                    {
                        name: [data.get_hostnames()[0].as_str(), ".local"].concat(),
                        dtype: dtype,
                        class: QClass::IN,
                        ttl: i32::MAX,
                        rdlength: 0,
                        rdata: DnsRdata::A{ ip: ipv4 },
                    }
                );

                return Ok(out);
            },
            QType::AAAA => 
            {
                let mut out: Vec<Self> = Vec::with_capacity(1);

                let ipv6: Ipv6Addr = 
                    if let IpAddr::V6(ipv6) = data.get_ip() 
                    {
                        ipv6.clone()
                    }
                    else
                    {
                        internal_error!(CDnsErrorType::InternalError, "wrong data type");
                    };

                out.push(
                    DnsResponsePayload
                    {
                        name: [data.get_hostnames()[0].as_str(), ".local"].concat(),
                        dtype: dtype,
                        class: QClass::IN,
                        ttl: i32::MAX,
                        rdlength: 0,
                        rdata: DnsRdata::AAAA{ ip: ipv6 },
                    }
                );

                return Ok(out);
            },
            QType::PTR => 
            {
                let mut out: Vec<Self> = Vec::with_capacity(data.get_hostnames().len());

                // copy all hostnames from the list
                for h in data.get_hostnames_iter()
                {
                    out.push(
                        DnsResponsePayload
                        {
                            name: [data.get_ip().to_string().as_str(), ".local"].concat(),
                            dtype: dtype,
                            class: QClass::IN,
                            ttl: i32::MAX,
                            rdlength: 0,
                            rdata: DnsRdata::PTR{ fqdn: h.clone() },
                        }
                    );
                }
            
                return Ok(out);
            },
            _ => 
            {
                internal_error!(CDnsErrorType::InternalError, "new_local can not be used for types except A, AAAA, PTR");
            }
        }
        
    }
}

/*impl Default for DnsResponsePayload
{
    fn default() -> Self 
    {
        return Self::Empty;    
    }
}*/

impl fmt::Display for DnsResponsePayload
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "{} {} {} {} {}", 
            self.name, self.dtype, self.class, self.ttl, self.rdata)  
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DnsSoa
{
    /// primary name server
    pub pnm: String, 
    /// responsible authority mailbox
    pub ram: String,
    /// serial number
    pub serial: u32,
    /// refresh interval
    pub interv_refr: u32,
    /// retry interval
    pub interv_retry: u32,
    /// expire limit
    pub expire_limit: u32,
    /// minimum TTL
    pub min_ttl: u32,
}

impl fmt::Display for DnsSoa
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
    {
        writeln!(f, "{} {} {} {} {} {} {}", 
            self.pnm, self.ram, self.serial, self.interv_refr, 
            self.interv_retry, self.expire_limit, self.min_ttl)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DnsRdata
{
    None,
    A{ ip: Ipv4Addr },
    NS{ fqdn: String },
    MD{ data: Vec<u8> },
    MF{ data: Vec<u8> },
    CNAME{ fqdn: String },
    SOA{ soa: DnsSoa },
    MB{ data: Vec<u8> },
    MG{ data: Vec<u8> },
    MR{ data: Vec<u8> },
    NULL{ data: Vec<u8> },
    WKS{ data: Vec<u8> },
    PTR{ fqdn: String },
    HINFO{ data: Vec<u8> },
    MX{ preference: u16, exchange: String },
    TXT{ data: Vec<u8> },
    AFSDB{ data: Vec<u8> },
    KEY{ data: Vec<u8> },
    AAAA{ ip: Ipv6Addr },
    CERT{ data: Vec<u8> },
    DS{ data: Vec<u8> },
    RRSIG{ data: Vec<u8> },
    NSEC{ data: Vec<u8> },
    DNSKEY{ data: Vec<u8> },
    NSEC3{ data: Vec<u8> },
    NSEC3PARAM{ data: Vec<u8> },
    CDS{ data: Vec<u8> },
    CDNSKEY{ data: Vec<u8> },
    OPENPGPKEY{ data: Vec<u8> },    
    UNKNOWN{ data: Vec<u8> },
}

impl fmt::Display for DnsRdata
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::None => 
                write!(f, "No record"),
            Self::A{ ref ip } => 
                write!(f, "{}", ip),
            Self::NS{ ref fqdn } => 
                write!(f, "{}", fqdn),
            Self::AAAA{ ref ip} => 
                write!(f, "{}", ip),
            Self::MX{ preference, ref exchange } =>
                write!(f, "{} {}", preference, exchange),
            Self::CNAME{ ref fqdn } => 
                write!(f, "{}", fqdn),
            Self::PTR{ ref fqdn } => 
                write!(f, "{}", fqdn),
            Self::SOA{ ref soa } => 
                write!(f, "{}", soa),
            Self::UNKNOWN{ .. } => 
                write!(f, "UNKNOWN"),
            _ => write!(f, "RAW DATA"),
        }
    }
}

impl Default for DnsRdata
{
    fn default() -> Self 
    {
        return Self::None;   
    }
}

impl DnsRdata
{
    pub 
    fn is_some(&self) -> bool
    {
        return *self != Self::None;
    }
}