manydns 1.3.0

Provider-agnostic DNS zone and record management, inspired by the Go libdns project
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
//! RFC-compliant fixed-size DNS types.
//!
//! This module provides strictly-sized types that conform to the DNS RFCs:
//! - RFC 1035: Domain Names - Implementation and Specification
//! - RFC 2181: Clarifications to the DNS Specification
//! - RFC 2782: A DNS RR for specifying the location of services (DNS SRV)
//!
//! All types in this module are designed to be:
//! - Fixed size (no heap allocation where possible)
//! - Copy where the size permits
//! - No Drop trait implementation required
//!
//! # Size Limits (from RFCs)
//!
//! | Field | Limit | Reference |
//! |-------|-------|-----------|
//! | Label | 1-63 octets | RFC 1035 §2.3.4 |
//! | Domain name | ≤255 octets | RFC 1035 §2.3.4 |
//! | TTL | 0 to 2^31-1 seconds | RFC 2181 §8 |
//! | TYPE | 16-bit unsigned | RFC 1035 §3.2.2 |
//! | CLASS | 16-bit unsigned | RFC 1035 §3.2.4 |
//! | Priority (MX/SRV) | 16-bit unsigned | RFC 1035 §3.3.9, RFC 2782 |
//! | Weight (SRV) | 16-bit unsigned | RFC 2782 |
//! | Port (SRV) | 16-bit unsigned | RFC 2782 |

use core::fmt;

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

/// Maximum length of a single DNS label (RFC 1035 §2.3.4).
pub const MAX_LABEL_LEN: usize = 63;

/// Maximum length of a full domain name including separators (RFC 1035 §2.3.4).
pub const MAX_DOMAIN_LEN: usize = 255;

/// Maximum TTL value per RFC 2181 §8: 2^31 - 1 seconds.
pub const MAX_TTL: u32 = 2_147_483_647;

/// API environment for providers that support sandbox/production modes.
///
/// Some DNS providers offer a sandbox environment for testing API integrations
/// without affecting production domains. This enum provides a standardized way
/// to specify the target environment.
///
/// # Example
///
/// ```
/// use manydns::types::Environment;
///
/// let env = Environment::Sandbox;
/// assert!(!env.is_production());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Environment {
    /// Production environment - changes affect real domains.
    #[default]
    Production,
    /// Sandbox/testing environment - safe for development and testing.
    Sandbox,
}

impl Environment {
    /// Returns `true` if this is the production environment.
    pub fn is_production(&self) -> bool {
        matches!(self, Environment::Production)
    }

    /// Returns `true` if this is the sandbox environment.
    pub fn is_sandbox(&self) -> bool {
        matches!(self, Environment::Sandbox)
    }
}

impl fmt::Display for Environment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Environment::Production => write!(f, "production"),
            Environment::Sandbox => write!(f, "sandbox"),
        }
    }
}

/// A DNS label - a single component of a domain name.
///
/// Labels are limited to 63 octets (RFC 1035 §2.3.4).
/// The high-order two bits of the length octet must be zero.
///
/// This is a fixed-size, Copy type with no heap allocation.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct Label {
    /// Length of the label (1-63).
    len: u8,
    /// Label data, padded to max size.
    data: [u8; MAX_LABEL_LEN],
}

impl Label {
    /// Creates a new label from a byte slice.
    ///
    /// Returns `None` if the slice is empty or exceeds 63 bytes.
    #[inline]
    pub const fn new(bytes: &[u8]) -> Option<Self> {
        if bytes.is_empty() || bytes.len() > MAX_LABEL_LEN {
            return None;
        }

        let mut data = [0u8; MAX_LABEL_LEN];
        let mut i = 0;
        while i < bytes.len() {
            data[i] = bytes[i];
            i += 1;
        }

        Some(Self {
            len: bytes.len() as u8,
            data,
        })
    }

    /// Creates a new label from a string slice.
    ///
    /// Returns `None` if the string is empty or exceeds 63 bytes.
    #[inline]
    pub const fn from_str(s: &str) -> Option<Self> {
        Self::new(s.as_bytes())
    }

    /// Returns the label as a byte slice.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[..self.len as usize]
    }

    /// Returns the length of the label in bytes.
    #[inline]
    pub const fn len(&self) -> usize {
        self.len as usize
    }

    /// Returns true if the label is empty.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the label as a string slice, if valid UTF-8.
    #[inline]
    pub fn as_str(&self) -> Option<&str> {
        std::str::from_utf8(self.as_bytes()).ok()
    }
}

impl fmt::Debug for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_str() {
            Some(s) => write!(f, "Label({:?})", s),
            None => write!(f, "Label({:?})", self.as_bytes()),
        }
    }
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_str() {
            Some(s) => write!(f, "{}", s),
            None => write!(f, "{:?}", self.as_bytes()),
        }
    }
}

impl Default for Label {
    fn default() -> Self {
        Self {
            len: 0,
            data: [0u8; MAX_LABEL_LEN],
        }
    }
}

/// A DNS domain name with fixed-size storage.
///
/// Domain names are limited to 255 octets total (RFC 1035 §2.3.4).
/// This includes the length octets for each label and the terminating zero.
///
/// This is a fixed-size type with no heap allocation.
/// It's too large to be Copy (256 bytes), but implements Clone.
#[derive(Clone, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct DomainName {
    /// Length of the domain name in wire format.
    len: u8,
    /// Domain name data in wire format (length-prefixed labels, null terminated).
    data: [u8; MAX_DOMAIN_LEN],
}

impl DomainName {
    /// Creates a new domain name from a dotted string (e.g., "example.com").
    ///
    /// Returns `None` if the domain name is invalid or too long.
    pub fn from_dotted(s: &str) -> Option<Self> {
        if s.is_empty() {
            // Root domain
            return Some(Self {
                len: 1,
                data: [0u8; MAX_DOMAIN_LEN],
            });
        }

        let mut data = [0u8; MAX_DOMAIN_LEN];
        let mut pos = 0usize;

        for label in s.trim_end_matches('.').split('.') {
            let label_bytes = label.as_bytes();
            if label_bytes.is_empty() || label_bytes.len() > MAX_LABEL_LEN {
                return None;
            }

            // Check if we have room: length byte + label + at least null terminator
            if pos + 1 + label_bytes.len() >= MAX_DOMAIN_LEN {
                return None;
            }

            data[pos] = label_bytes.len() as u8;
            pos += 1;

            data[pos..pos + label_bytes.len()].copy_from_slice(label_bytes);
            pos += label_bytes.len();
        }

        // Null terminator for root
        data[pos] = 0;
        pos += 1;

        Some(Self {
            len: pos as u8,
            data,
        })
    }

    /// Returns the domain name in dotted notation.
    pub fn to_dotted(&self) -> String {
        let mut result = String::with_capacity(self.len as usize);
        let mut pos = 0usize;

        while pos < self.len as usize {
            let label_len = self.data[pos] as usize;
            if label_len == 0 {
                break;
            }

            if !result.is_empty() {
                result.push('.');
            }

            pos += 1;
            if let Ok(s) = std::str::from_utf8(&self.data[pos..pos + label_len]) {
                result.push_str(s);
            }
            pos += label_len;
        }

        result
    }

    /// Returns the wire-format length of the domain name.
    #[inline]
    pub const fn wire_len(&self) -> usize {
        self.len as usize
    }

    /// Returns the wire-format bytes.
    #[inline]
    pub fn as_wire_bytes(&self) -> &[u8] {
        &self.data[..self.len as usize]
    }

    /// Returns true if this is the root domain.
    #[inline]
    pub const fn is_root(&self) -> bool {
        self.len == 1 && self.data[0] == 0
    }
}

impl fmt::Debug for DomainName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "DomainName({:?})", self.to_dotted())
    }
}

impl fmt::Display for DomainName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_dotted())
    }
}

impl Default for DomainName {
    fn default() -> Self {
        Self {
            len: 1,
            data: [0u8; MAX_DOMAIN_LEN], // Root domain
        }
    }
}

/// DNS Time To Live value.
///
/// Per RFC 2181 §8, TTL is an unsigned 32-bit integer with a maximum
/// value of 2^31 - 1 (2,147,483,647) seconds. The MSB must be zero.
///
/// This type enforces the RFC limit and provides semantic clarity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(transparent)]
pub struct Ttl(u32);

impl Ttl {
    /// Zero TTL - record should not be cached (RFC 1035 §3.2.1).
    pub const ZERO: Ttl = Ttl(0);

    /// One hour TTL.
    pub const ONE_HOUR: Ttl = Ttl(3600);

    /// One day TTL.
    pub const ONE_DAY: Ttl = Ttl(86400);

    /// One week TTL.
    pub const ONE_WEEK: Ttl = Ttl(604800);

    /// Maximum valid TTL per RFC 2181 §8.
    pub const MAX: Ttl = Ttl(MAX_TTL);

    /// Creates a new TTL, clamping to the RFC maximum if necessary.
    #[inline]
    pub const fn new(seconds: u32) -> Self {
        if seconds > MAX_TTL {
            Self(MAX_TTL)
        } else {
            Self(seconds)
        }
    }

    /// Creates a TTL from seconds, returning None if it exceeds the RFC maximum.
    #[inline]
    pub const fn try_new(seconds: u32) -> Option<Self> {
        if seconds > MAX_TTL {
            None
        } else {
            Some(Self(seconds))
        }
    }

    /// Returns the TTL value in seconds.
    #[inline]
    pub const fn as_secs(&self) -> u32 {
        self.0
    }

    /// Returns true if the TTL is zero.
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.0 == 0
    }
}

impl From<u32> for Ttl {
    #[inline]
    fn from(secs: u32) -> Self {
        Self::new(secs)
    }
}

impl From<Ttl> for u32 {
    #[inline]
    fn from(ttl: Ttl) -> Self {
        ttl.0
    }
}

impl fmt::Display for Ttl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// DNS Record Type (RFC 1035 §3.2.2).
///
/// This is a 16-bit unsigned integer representing the record type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u16)]
pub enum RecordType {
    /// Host address (RFC 1035).
    A = 1,
    /// Authoritative name server (RFC 1035).
    NS = 2,
    /// Canonical name for an alias (RFC 1035).
    CNAME = 5,
    /// Start of authority (RFC 1035).
    SOA = 6,
    /// Domain name pointer (RFC 1035).
    PTR = 12,
    /// Host information (RFC 1035).
    HINFO = 13,
    /// Mail exchange (RFC 1035).
    MX = 15,
    /// Text strings (RFC 1035).
    TXT = 16,
    /// IPv6 host address (RFC 3596).
    AAAA = 28,
    /// Server selection (RFC 2782).
    SRV = 33,
    /// Delegation signer (RFC 4034).
    DS = 43,
    /// DNSKEY (RFC 4034).
    DNSKEY = 48,
    /// Certification Authority Authorization (RFC 8659).
    CAA = 257,
}

impl RecordType {
    /// Creates a RecordType from a u16 value.
    pub const fn from_u16(value: u16) -> Option<Self> {
        match value {
            1 => Some(Self::A),
            2 => Some(Self::NS),
            5 => Some(Self::CNAME),
            6 => Some(Self::SOA),
            12 => Some(Self::PTR),
            13 => Some(Self::HINFO),
            15 => Some(Self::MX),
            16 => Some(Self::TXT),
            28 => Some(Self::AAAA),
            33 => Some(Self::SRV),
            43 => Some(Self::DS),
            48 => Some(Self::DNSKEY),
            257 => Some(Self::CAA),
            _ => None,
        }
    }

    /// Creates a RecordType from a string.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "A" => Some(Self::A),
            "NS" => Some(Self::NS),
            "CNAME" => Some(Self::CNAME),
            "SOA" => Some(Self::SOA),
            "PTR" => Some(Self::PTR),
            "HINFO" => Some(Self::HINFO),
            "MX" => Some(Self::MX),
            "TXT" => Some(Self::TXT),
            "AAAA" => Some(Self::AAAA),
            "SRV" => Some(Self::SRV),
            "DS" => Some(Self::DS),
            "DNSKEY" => Some(Self::DNSKEY),
            "CAA" => Some(Self::CAA),
            _ => None,
        }
    }

    /// Returns the type code as a u16.
    #[inline]
    pub const fn as_u16(&self) -> u16 {
        *self as u16
    }

    /// Returns the type as a string.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::A => "A",
            Self::NS => "NS",
            Self::CNAME => "CNAME",
            Self::SOA => "SOA",
            Self::PTR => "PTR",
            Self::HINFO => "HINFO",
            Self::MX => "MX",
            Self::TXT => "TXT",
            Self::AAAA => "AAAA",
            Self::SRV => "SRV",
            Self::DS => "DS",
            Self::DNSKEY => "DNSKEY",
            Self::CAA => "CAA",
        }
    }
}

impl fmt::Display for RecordType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// DNS Record Class (RFC 1035 §3.2.4).
///
/// This is a 16-bit unsigned integer representing the record class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u16)]
pub enum RecordClass {
    /// The Internet (RFC 1035).
    #[default]
    IN = 1,
    /// CSNET class (obsolete, RFC 1035).
    CS = 2,
    /// CHAOS class (RFC 1035).
    CH = 3,
    /// Hesiod (RFC 1035).
    HS = 4,
}

impl RecordClass {
    /// Creates a RecordClass from a u16 value.
    pub const fn from_u16(value: u16) -> Option<Self> {
        match value {
            1 => Some(Self::IN),
            2 => Some(Self::CS),
            3 => Some(Self::CH),
            4 => Some(Self::HS),
            _ => None,
        }
    }

    /// Returns the class code as a u16.
    #[inline]
    pub const fn as_u16(&self) -> u16 {
        *self as u16
    }
}

impl fmt::Display for RecordClass {
    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"),
        }
    }
}

/// MX record data with fixed-size priority (RFC 1035 §3.3.9).
///
/// Priority is a 16-bit unsigned integer. Lower values are preferred.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct MxData {
    /// Preference value (lower is more preferred).
    pub priority: u16,
    /// Mail exchange host.
    pub exchange: DomainName,
}

impl MxData {
    /// Creates new MX data.
    pub fn new(priority: u16, exchange: DomainName) -> Self {
        Self { priority, exchange }
    }
}

impl fmt::Debug for MxData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MxData")
            .field("priority", &self.priority)
            .field("exchange", &self.exchange.to_dotted())
            .finish()
    }
}

/// SRV record data with fixed-size fields (RFC 2782).
///
/// All numeric fields are 16-bit unsigned integers.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SrvData {
    /// Priority (lower is more preferred).
    pub priority: u16,
    /// Weight for load balancing among same-priority servers.
    pub weight: u16,
    /// TCP/UDP port number.
    pub port: u16,
    /// Target host providing the service.
    pub target: DomainName,
}

impl SrvData {
    /// Creates new SRV data.
    pub fn new(priority: u16, weight: u16, port: u16, target: DomainName) -> Self {
        Self {
            priority,
            weight,
            port,
            target,
        }
    }
}

impl fmt::Debug for SrvData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SrvData")
            .field("priority", &self.priority)
            .field("weight", &self.weight)
            .field("port", &self.port)
            .field("target", &self.target.to_dotted())
            .finish()
    }
}

/// SOA record data (RFC 1035 §3.3.13).
///
/// All timing values are 32-bit unsigned integers representing seconds.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SoaData {
    /// Primary name server for the zone.
    pub mname: DomainName,
    /// Email of the responsible person (encoded as domain name).
    pub rname: DomainName,
    /// Serial number (zone version).
    pub serial: u32,
    /// Refresh interval in seconds.
    pub refresh: u32,
    /// Retry interval in seconds.
    pub retry: u32,
    /// Expire time in seconds.
    pub expire: u32,
    /// Minimum TTL in seconds.
    pub minimum: u32,
}

impl fmt::Debug for SoaData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SoaData")
            .field("mname", &self.mname.to_dotted())
            .field("rname", &self.rname.to_dotted())
            .field("serial", &self.serial)
            .field("refresh", &self.refresh)
            .field("retry", &self.retry)
            .field("expire", &self.expire)
            .field("minimum", &self.minimum)
            .finish()
    }
}