monovm-whois-rust 1.0.0

Domain WHOIS and RDAP lookups with availability detection, structured record parsing, referral chasing, caching and rate limiting.
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
//! What this crate knows about one registry, and how to address it.

use std::fmt;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::domain::{DomainName, Tld};
use crate::error::{Error, Result};

/// Default port for the WHOIS protocol (RFC 3912).
pub const WHOIS_PORT: u16 = 43;

/// One addressable service that can answer a query about a domain.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Endpoint {
    /// A line-oriented WHOIS service, RFC 3912.
    Whois(WhoisEndpoint),
    /// An RDAP service, RFC 7482 / 9082.
    Rdap(RdapEndpoint),
}

impl Endpoint {
    /// A WHOIS endpoint on the default port.
    pub fn whois(host: impl Into<String>) -> Self {
        Endpoint::Whois(WhoisEndpoint::new(host, WHOIS_PORT))
    }

    /// An RDAP endpoint from a service base URL.
    pub fn rdap(base: impl Into<String>) -> Self {
        Endpoint::Rdap(RdapEndpoint::new(base))
    }

    /// Parse the compact textual form used in registry data.
    ///
    /// `whois.nic.uk`, `whois.nic.uk:4343` and `socket://whois.nic.uk` are WHOIS
    /// endpoints; anything with an `http` scheme is RDAP.
    pub fn parse(spec: &str) -> Result<Self> {
        let spec = spec.trim();
        if spec.is_empty() {
            return Err(Error::Definitions("empty endpoint".into()));
        }

        if let Some(rest) = spec.strip_prefix("socket://") {
            return WhoisEndpoint::parse(rest).map(Endpoint::Whois);
        }
        if spec.starts_with("http://") || spec.starts_with("https://") {
            return Ok(Endpoint::Rdap(RdapEndpoint::new(spec)));
        }
        if spec.contains("://") {
            return Err(Error::Definitions(format!(
                "unsupported endpoint scheme in {spec:?}"
            )));
        }

        WhoisEndpoint::parse(spec).map(Endpoint::Whois)
    }

    /// Whether this is a port 43 endpoint.
    pub fn is_whois(&self) -> bool {
        matches!(self, Endpoint::Whois(_))
    }

    /// Whether this is an RDAP endpoint.
    pub fn is_rdap(&self) -> bool {
        matches!(self, Endpoint::Rdap(_))
    }

    /// A short label for logs, diagnostics and cache keys.
    pub fn address(&self) -> String {
        match self {
            Endpoint::Whois(endpoint) => endpoint.address(),
            Endpoint::Rdap(endpoint) => endpoint.base().to_string(),
        }
    }
}

impl fmt::Display for Endpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Endpoint::Whois(endpoint) => write!(f, "whois://{}", endpoint.address()),
            Endpoint::Rdap(endpoint) => f.write_str(endpoint.base()),
        }
    }
}

/// Host and port of a WHOIS service.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WhoisEndpoint {
    host: String,
    port: u16,
}

impl WhoisEndpoint {
    /// Build from a host and port.
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        WhoisEndpoint {
            host: host.into().trim().trim_matches('/').to_ascii_lowercase(),
            port,
        }
    }

    /// Parse `host` or `host:port`.
    pub fn parse(spec: &str) -> Result<Self> {
        let spec = spec.trim().trim_matches('/');
        let (host, port) = match spec.rsplit_once(':') {
            Some((host, port)) => {
                let port = port.parse::<u16>().map_err(|_| {
                    Error::Definitions(format!("{spec:?} has an invalid WHOIS port"))
                })?;
                (host, port)
            }
            None => (spec, WHOIS_PORT),
        };

        if host.is_empty() {
            return Err(Error::Definitions(format!("{spec:?} has no WHOIS host")));
        }

        Ok(WhoisEndpoint::new(host, port))
    }

    /// The host name.
    pub fn host(&self) -> &str {
        &self.host
    }

    /// The TCP port.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// `host` when the port is the default, `host:port` otherwise.
    pub fn address(&self) -> String {
        if self.port == WHOIS_PORT {
            self.host.clone()
        } else {
            format!("{}:{}", self.host, self.port)
        }
    }
}

/// Base URL of an RDAP service.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RdapEndpoint {
    base: String,
}

impl RdapEndpoint {
    /// Build from a service base URL.
    pub fn new(base: impl Into<String>) -> Self {
        RdapEndpoint {
            base: base.into().trim().to_string(),
        }
    }

    /// The URL as configured.
    pub fn base(&self) -> &str {
        &self.base
    }

    /// The full query URL for one domain.
    ///
    /// Registry data is inconsistent about how much of the RDAP path the base URL
    /// already contains — the IANA bootstrap file publishes service roots such as
    /// `https://rdap.verisign.com/com/v1/`, while hand-written definitions often
    /// include the object type. Both are accepted and produce the same URL:
    ///
    /// ```
    /// use monovm_whois::registry::RdapEndpoint;
    ///
    /// let root = RdapEndpoint::new("https://rdap.verisign.com/com/v1/");
    /// let full = RdapEndpoint::new("https://rdap.verisign.com/com/v1/domain/");
    /// assert_eq!(root.query_url("example.com"), full.query_url("example.com"));
    /// ```
    pub fn query_url(&self, domain: &str) -> String {
        let base = self.base.trim_end_matches('/');
        if base.ends_with("/domain") {
            format!("{base}/{domain}")
        } else {
            format!("{base}/domain/{domain}")
        }
    }

    /// Whether the endpoint is plain HTTP. Two registries in the IANA bootstrap
    /// file still publish one, and a caller may reasonably refuse to use them.
    pub fn is_plaintext(&self) -> bool {
        self.base.starts_with("http://")
    }
}

/// Which form of an internationalised name a registry wants on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum IdnForm {
    /// Punycode. The default, and correct almost everywhere.
    #[default]
    Ascii,
    /// The Unicode form. DENIC answers `Status: invalid` for the punycode
    /// spelling of a `.de` name it resolves fine in Unicode.
    Unicode,
}

/// Everything this crate knows about one registry.
///
/// A single instance is shared by every suffix the registry serves, so the
/// `.com`/`.net` pair is one value rather than two.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Registry {
    tlds: Vec<Tld>,
    endpoints: Vec<Endpoint>,
    available_markers: Vec<String>,
    premium_markers: Vec<String>,
    thin: bool,
    idn: IdnForm,
    available_when_empty: bool,
    note: Option<String>,
}

impl Registry {
    /// Start building a registry definition for one or more suffixes.
    pub fn builder(tlds: impl IntoIterator<Item = Tld>) -> RegistryBuilder {
        RegistryBuilder {
            registry: Registry {
                tlds: tlds.into_iter().collect(),
                endpoints: Vec::new(),
                available_markers: Vec::new(),
                premium_markers: Vec::new(),
                thin: false,
                idn: IdnForm::default(),
                available_when_empty: false,
                note: None,
            },
        }
    }

    /// Every suffix served by this registry.
    pub fn tlds(&self) -> &[Tld] {
        &self.tlds
    }

    /// The endpoints to try, in the order the definition listed them.
    pub fn endpoints(&self) -> &[Endpoint] {
        &self.endpoints
    }

    /// Literal substrings that, when present in a response, mean the name is
    /// unregistered at this registry.
    ///
    /// These come from curated data and are the highest-confidence availability
    /// signal there is, because they were written for one specific server's
    /// wording rather than inferred from a general pattern.
    pub fn available_markers(&self) -> &[String] {
        &self.available_markers
    }

    /// Literal substrings that mean the registry has priced the name above the
    /// standard fee.
    pub fn premium_markers(&self) -> &[String] {
        &self.premium_markers
    }

    /// Whether the registry answers with a referral to the registrar instead of
    /// the full record. A hint that following referrals is worthwhile, not a
    /// promise that a referral will be present.
    pub fn is_thin(&self) -> bool {
        self.thin
    }

    /// Which form of an internationalised name to put on the wire.
    pub fn idn_form(&self) -> IdnForm {
        self.idn
    }

    /// Whether a response with no record and no refusal means "unregistered".
    ///
    /// Opt-in per registry, never a global rule: a few registries answer an
    /// unregistered name with nothing but their banner, and for those the
    /// absence of a record is the only signal there is. Everywhere else the same
    /// inference would report a rate-limit notice as a free domain.
    pub fn available_when_empty(&self) -> bool {
        self.available_when_empty
    }

    /// Free-text note from the definition data, usually explaining why an
    /// endpoint is unusual or why a marker is what it is.
    pub fn note(&self) -> Option<&str> {
        self.note.as_deref()
    }

    /// The endpoints of one kind, in order.
    pub fn endpoints_matching(&self, kind: EndpointKind) -> impl Iterator<Item = &Endpoint> {
        self.endpoints.iter().filter(move |endpoint| match kind {
            EndpointKind::Whois => endpoint.is_whois(),
            EndpointKind::Rdap => endpoint.is_rdap(),
        })
    }

    /// The query string to send for a name, in the form this registry wants.
    pub fn wire_form(&self, name: &DomainName) -> String {
        match self.idn {
            IdnForm::Ascii => name.as_ascii().to_string(),
            IdnForm::Unicode => name.as_unicode().to_string(),
        }
    }

    /// Merge another definition over this one, field by field.
    ///
    /// Used by [`LayeredRegistry`](crate::registry::LayeredRegistry) so a local
    /// override file can correct one field of a bundled definition without
    /// restating the rest. `other` wins wherever it says anything.
    pub fn overlay(&self, other: &Registry) -> Registry {
        let pick = |theirs: &Vec<String>, ours: &Vec<String>| {
            if theirs.is_empty() {
                ours.clone()
            } else {
                theirs.clone()
            }
        };

        Registry {
            tlds: if other.tlds.is_empty() {
                self.tlds.clone()
            } else {
                other.tlds.clone()
            },
            endpoints: if other.endpoints.is_empty() {
                self.endpoints.clone()
            } else {
                other.endpoints.clone()
            },
            available_markers: pick(&other.available_markers, &self.available_markers),
            premium_markers: pick(&other.premium_markers, &self.premium_markers),
            thin: self.thin || other.thin,
            idn: if other.idn == IdnForm::default() {
                self.idn
            } else {
                other.idn
            },
            available_when_empty: self.available_when_empty || other.available_when_empty,
            note: other.note.clone().or_else(|| self.note.clone()),
        }
    }

    /// Merge another definition over this one, but keep both sets of endpoints.
    ///
    /// Same field rules as [`overlay`](Registry::overlay), except that endpoints
    /// accumulate — this one's first, then any of `other`'s that are new. Used to
    /// stack data sources that each know about a different protocol, where
    /// replacing endpoints outright would throw away real coverage.
    pub fn union(&self, other: &Registry) -> Registry {
        let mut merged = self.overlay(other);

        merged.endpoints = self.endpoints.clone();
        for endpoint in &other.endpoints {
            if !merged.endpoints.contains(endpoint) {
                merged.endpoints.push(endpoint.clone());
            }
        }

        let mut tlds = self.tlds.clone();
        for tld in &other.tlds {
            if !tlds.contains(tld) {
                tlds.push(tld.clone());
            }
        }
        merged.tlds = tlds;

        merged
    }
}

/// Which protocol an endpoint speaks. Used to filter and to express preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EndpointKind {
    /// RFC 3912 WHOIS over TCP port 43.
    Whois,
    /// RDAP over HTTP.
    Rdap,
}

/// Fluent builder for [`Registry`].
///
/// Definitions have eight fields, six of which are usually left at their
/// default. A builder keeps the common case to one line and means adding a
/// seventh field later is not a breaking change:
///
/// ```
/// use monovm_whois::registry::{Endpoint, Registry};
/// use monovm_whois::Tld;
///
/// let registry = Registry::builder([Tld::parse("example").unwrap()])
///     .endpoint(Endpoint::whois("whois.nic.example"))
///     .available_marker("No match for")
///     .thin(true)
///     .build();
///
/// assert!(registry.is_thin());
/// assert_eq!(registry.endpoints().len(), 1);
/// ```
#[derive(Debug, Clone)]
pub struct RegistryBuilder {
    registry: Registry,
}

impl RegistryBuilder {
    /// Add one endpoint. Order is preserved and is the order they get tried in.
    pub fn endpoint(mut self, endpoint: Endpoint) -> Self {
        self.registry.endpoints.push(endpoint);
        self
    }

    /// Add several endpoints.
    pub fn endpoints(mut self, endpoints: impl IntoIterator<Item = Endpoint>) -> Self {
        self.registry.endpoints.extend(endpoints);
        self
    }

    /// Add a literal "this name is unregistered" marker.
    pub fn available_marker(mut self, marker: impl Into<String>) -> Self {
        self.registry.available_markers.push(marker.into());
        self
    }

    /// Add several availability markers.
    pub fn available_markers(mut self, markers: impl IntoIterator<Item = String>) -> Self {
        self.registry.available_markers.extend(markers);
        self
    }

    /// Add a literal "this name is premium" marker.
    pub fn premium_marker(mut self, marker: impl Into<String>) -> Self {
        self.registry.premium_markers.push(marker.into());
        self
    }

    /// Add several premium markers.
    pub fn premium_markers(mut self, markers: impl IntoIterator<Item = String>) -> Self {
        self.registry.premium_markers.extend(markers);
        self
    }

    /// Mark the registry as answering with referrals rather than full records.
    pub fn thin(mut self, thin: bool) -> Self {
        self.registry.thin = thin;
        self
    }

    /// Set which form of an internationalised name to send.
    pub fn idn_form(mut self, idn: IdnForm) -> Self {
        self.registry.idn = idn;
        self
    }

    /// Allow "no record at all" to be read as availability for this registry.
    pub fn available_when_empty(mut self, allow: bool) -> Self {
        self.registry.available_when_empty = allow;
        self
    }

    /// Attach an explanatory note.
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.registry.note = Some(note.into());
        self
    }

    /// Finish, returning the definition.
    pub fn build(self) -> Registry {
        self.registry
    }

    /// Finish, wrapping in the `Arc` that providers hand out.
    pub fn build_shared(self) -> Arc<Registry> {
        Arc::new(self.registry)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_the_compact_endpoint_forms() {
        assert_eq!(
            Endpoint::parse("whois.nic.uk").unwrap(),
            Endpoint::Whois(WhoisEndpoint::new("whois.nic.uk", 43))
        );
        assert_eq!(
            Endpoint::parse("socket://whois.nic.uk/").unwrap(),
            Endpoint::Whois(WhoisEndpoint::new("whois.nic.uk", 43))
        );
        assert_eq!(
            Endpoint::parse("whois.example:4343").unwrap(),
            Endpoint::Whois(WhoisEndpoint::new("whois.example", 4343))
        );
        assert!(Endpoint::parse("https://rdap.example/").unwrap().is_rdap());
        assert!(Endpoint::parse("").is_err());
        assert!(Endpoint::parse("ftp://whois.example").is_err());
        assert!(Endpoint::parse("whois.example:not-a-port").is_err());
    }

    #[test]
    fn whois_address_hides_the_default_port() {
        assert_eq!(
            WhoisEndpoint::new("whois.nic.uk", 43).address(),
            "whois.nic.uk"
        );
        assert_eq!(
            WhoisEndpoint::new("whois.nic.uk", 4343).address(),
            "whois.nic.uk:4343"
        );
    }

    #[test]
    fn rdap_query_url_normalises_either_base_form() {
        let expected = "https://rdap.example/v1/domain/example.com";
        for base in [
            "https://rdap.example/v1",
            "https://rdap.example/v1/",
            "https://rdap.example/v1/domain",
            "https://rdap.example/v1/domain/",
        ] {
            assert_eq!(RdapEndpoint::new(base).query_url("example.com"), expected);
        }
    }

    #[test]
    fn wire_form_follows_the_idn_setting() {
        let name = DomainName::parse("münchen.de").unwrap();
        let tlds = vec![Tld::parse("de").unwrap()];

        let ascii = Registry::builder(tlds.clone()).build();
        assert_eq!(ascii.wire_form(&name), "xn--mnchen-3ya.de");

        let unicode = Registry::builder(tlds).idn_form(IdnForm::Unicode).build();
        assert_eq!(unicode.wire_form(&name), "münchen.de");
    }

    #[test]
    fn overlay_takes_the_other_side_where_it_speaks() {
        let tlds = vec![Tld::parse("example").unwrap()];
        let base = Registry::builder(tlds.clone())
            .endpoint(Endpoint::whois("old.example"))
            .available_marker("No match")
            .note("bundled")
            .build();

        let patch = Registry::builder(tlds)
            .endpoint(Endpoint::whois("new.example"))
            .thin(true)
            .build();

        let merged = base.overlay(&patch);
        assert_eq!(merged.endpoints()[0].address(), "new.example");
        // Untouched by the patch, so the bundled values survive.
        assert_eq!(merged.available_markers(), ["No match"]);
        assert_eq!(merged.note(), Some("bundled"));
        assert!(merged.is_thin());
    }
}