domain-check-lib 1.2.0

A fast, robust library for checking domain availability using RDAP and WHOIS protocols
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
//! WHOIS protocol implementation for domain availability checking.
//!
//! WHOIS (RFC 3912) is the fallback when RDAP is not available. The client
//! speaks the protocol directly over TCP port 43, so it needs no system
//! `whois` binary and behaves the same on every platform.
//!
//! WHOIS replies are free text and every registry formats them differently,
//! so [`classify`] reads them as `key: value` fields plus a small set of
//! "not found" phrases, and answers [`Verdict::Unknown`] rather than guess.

use crate::error::DomainCheckError;
use crate::types::{CheckMethod, DomainResult};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::Semaphore;

/// Well-known WHOIS port (RFC 3912).
const WHOIS_PORT: u16 = 43;

/// Most queries one WHOIS server gets at a time. Registries throttle bulk
/// use (whois.nic.it answers a burst by slowing every reply to 15 s+).
const MAX_QUERIES_PER_SERVER: usize = 2;

/// Replies larger than this are cut off; real ones are a few KB.
const MAX_RESPONSE_BYTES: u64 = 1024 * 1024;

/// IANA's WHOIS server, which refers each TLD to its registry's server.
const IANA_WHOIS_SERVER: &str = "whois.iana.org";

/// Message for replies that are neither clearly taken nor clearly free.
/// The checker matches on this text to report UNKNOWN.
const UNDETERMINED: &str = "Unable to determine domain status from WHOIS response";

/// Message for TLDs whose registry offers RDAP only.
const NO_WHOIS_SERVICE: &str = "the registry offers no WHOIS service";

/// WHOIS client for checking domain availability.
#[derive(Clone)]
pub struct WhoisClient {
    /// Timeout for one WHOIS query (connect, send, and read)
    timeout: Duration,
    /// TCP port (43; tests use a local server)
    port: u16,
}

impl WhoisClient {
    /// Create a new WHOIS client with default settings.
    pub fn new() -> Self {
        Self::with_timeout(Duration::from_secs(5))
    }

    /// Create a new WHOIS client with custom timeout.
    pub fn with_timeout(timeout: Duration) -> Self {
        Self {
            timeout,
            port: WHOIS_PORT,
        }
    }

    #[cfg(test)]
    fn with_port(timeout: Duration, port: u16) -> Self {
        Self { timeout, port }
    }

    /// Check domain availability, discovering the registry's WHOIS server
    /// through IANA.
    pub async fn check_domain(&self, domain: &str) -> Result<DomainResult, DomainCheckError> {
        let tld = crate::protocols::registry::extract_tld(domain)?;
        match crate::protocols::registry::whois_server_status(&tld).await {
            WhoisServer::Known(server) => self.check_domain_with_server(domain, &server).await,
            WhoisServer::NoneListed => Err(no_whois_service_error(domain)),
            WhoisServer::Unreachable => Err(DomainCheckError::whois(
                domain,
                format!("could not ask IANA for the .{tld} WHOIS server"),
            )),
        }
    }

    /// Check domain availability against a specific WHOIS server.
    pub async fn check_domain_with_server(
        &self,
        domain: &str,
        server: &str,
    ) -> Result<DomainResult, DomainCheckError> {
        let start_time = Instant::now();
        let query = query_for(server, domain);

        // Waiting for a slot doesn't count against the query timeout.
        let slots = server_slots(server, self.port);
        let _slot = slots.acquire().await.ok();
        let mut verdict = classify(&self.query(server, &query, domain).await?, domain);
        if verdict == Verdict::RateLimited {
            tokio::time::sleep(Duration::from_secs(1)).await;
            verdict = classify(&self.query(server, &query, domain).await?, domain);
        }

        let available = match verdict {
            Verdict::Taken => false,
            Verdict::Available => true,
            Verdict::RateLimited => {
                return Err(DomainCheckError::whois(
                    domain,
                    format!("{server} rate limited the query"),
                ))
            }
            Verdict::Unknown(reason) => return Err(DomainCheckError::whois(domain, reason)),
        };

        Ok(DomainResult {
            domain: domain.to_string(),
            available: Some(available),
            info: None,
            check_duration: Some(start_time.elapsed()),
            method_used: CheckMethod::Whois,
            error_message: None,
            for_sale: None,
        })
    }

    async fn query(
        &self,
        server: &str,
        query: &str,
        domain: &str,
    ) -> Result<String, DomainCheckError> {
        match tokio::time::timeout(self.timeout, raw_query(server, self.port, query)).await {
            Ok(Ok(text)) => Ok(text),
            Ok(Err(e)) => Err(DomainCheckError::whois(
                domain,
                format!("WHOIS query to {server} failed: {e}"),
            )),
            Err(_) => Err(DomainCheckError::timeout("WHOIS query", self.timeout)),
        }
    }
}

impl Default for WhoisClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Per-server query slots, shared by every client in the process.
fn server_slots(server: &str, port: u16) -> Arc<Semaphore> {
    static SLOTS: OnceLock<Mutex<HashMap<String, Arc<Semaphore>>>> = OnceLock::new();
    let mut slots = SLOTS
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    slots
        .entry(format!("{}:{port}", server.to_ascii_lowercase()))
        .or_insert_with(|| Arc::new(Semaphore::new(MAX_QUERIES_PER_SERVER)))
        .clone()
}

/// Send one RFC 3912 query and read the reply until the server closes.
async fn raw_query(server: &str, port: u16, query: &str) -> std::io::Result<String> {
    // Connect to every address at once and keep the first that answers:
    // some registries publish an IPv4 or IPv6 address that never responds.
    let attempts: Vec<_> = tokio::net::lookup_host((server, port))
        .await?
        .map(|addr| Box::pin(TcpStream::connect(addr)))
        .collect();
    if attempts.is_empty() {
        return Err(std::io::Error::other(format!("{server} has no addresses")));
    }
    let (mut stream, _) = futures_util::future::select_ok(attempts).await?;
    stream.write_all(format!("{query}\r\n").as_bytes()).await?;
    let mut reply = Vec::new();
    stream
        .take(MAX_RESPONSE_BYTES)
        .read_to_end(&mut reply)
        .await?;
    // Some registries still answer in Latin-1; only field values are affected.
    Ok(String::from_utf8_lossy(&reply).into_owned())
}

/// Registry-specific query syntax.
fn query_for(server: &str, domain: &str) -> String {
    if server.eq_ignore_ascii_case("whois.jprs.jp") {
        // Without "/e" JPRS answers with Japanese field names.
        format!("{domain}/e")
    } else {
        domain.to_string()
    }
}

/// What IANA says about a TLD's WHOIS server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WhoisServer {
    Known(String),
    /// IANA answered and lists none: the registry has no WHOIS service.
    NoneListed,
    /// IANA could not be asked (blocked port, timeout, garbled reply).
    Unreachable,
}

/// Ask IANA which WHOIS server serves `tld`.
pub(crate) async fn discover(tld: &str) -> WhoisServer {
    match tokio::time::timeout(
        Duration::from_secs(10),
        raw_query(IANA_WHOIS_SERVER, WHOIS_PORT, tld),
    )
    .await
    {
        Ok(Ok(reply)) => parse_iana_discovery(&reply),
        _ => WhoisServer::Unreachable,
    }
}

/// "None listed" needs a real IANA record (it always has a `domain:` line);
/// anything else is treated as not having asked.
fn parse_iana_discovery(reply: &str) -> WhoisServer {
    if let Some(server) = parse_iana_refer_response(reply) {
        return WhoisServer::Known(server);
    }
    let is_record = reply
        .lines()
        .any(|l| l.trim_start().to_lowercase().starts_with("domain:"));
    if is_record {
        WhoisServer::NoneListed
    } else {
        WhoisServer::Unreachable
    }
}

/// Error for a TLD whose registry runs no WHOIS service (only RDAP).
pub(crate) fn no_whois_service_error(domain: &str) -> DomainCheckError {
    DomainCheckError::whois(domain, NO_WHOIS_SERVICE)
}

pub(crate) fn is_no_whois_service(error: &DomainCheckError) -> bool {
    matches!(error, DomainCheckError::WhoisError { message, .. } if message == NO_WHOIS_SERVICE)
}

/// Parse an IANA WHOIS response for the authoritative WHOIS server.
///
/// The IANA WHOIS response may use either `refer:` or `whois:` to indicate
/// the authoritative WHOIS server for a TLD. We check both fields, preferring
/// `refer:` when present.
///
/// ```text
/// whois:        whois.verisign-grs.com
/// refer:        whois.verisign-grs.com
/// ```
fn parse_iana_refer_response(response: &str) -> Option<String> {
    let mut whois_server = None;

    for line in response.lines() {
        let line_trimmed = line.trim();
        if let Some(server) = line_trimmed.strip_prefix("refer:") {
            let server = server.trim();
            if !server.is_empty() {
                // `refer:` is the canonical field — return immediately
                return Some(server.to_string());
            }
        } else if let Some(server) = line_trimmed.strip_prefix("whois:") {
            let server = server.trim();
            if !server.is_empty() {
                whois_server = Some(server.to_string());
            }
        }
    }

    whois_server
}

/// What a WHOIS reply says about a domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Verdict {
    Taken,
    Available,
    RateLimited,
    Unknown(&'static str),
}

// Kinds of registration data. A reply with two of them (or one plus the
// domain name echoed back) describes a registered domain. "Last updated"
// is left out: registries stamp free replies with it too.
const CREATED: u8 = 1;
const EXPIRES: u8 = 1 << 1;
const REGISTRAR: u8 = 1 << 3;
const REGISTRANT: u8 = 1 << 4;
const NAME_SERVERS: u8 = 1 << 5;
const STATUS: u8 = 1 << 6;

/// Phrases registries use for an unregistered name, collected from real
/// replies (see `tests/fixtures/whois`). Only consulted when the reply holds
/// no registration data, so a disclaimer can't turn a taken domain free.
const FREE_PHRASES: &[&str] = &[
    "no match",
    "not found",
    "no matching record",
    "no matching entry",
    "no entries found",
    "no data found",
    "no data was found",
    "no information available about",
    "nothing found",
    "no such domain",
    "does not exist",
    "not registered",
    "has not been registered",
    "is available for registration",
    "domain available",
    "object_not_found",
    "no object found",
];

/// Wording of actual rate-limit replies. Kept specific because registry
/// disclaimers talk about throttling and "query rates" in general terms.
const RATE_LIMIT_PHRASES: &[&str] = &[
    "rate limit exceeded",
    "query rate limit",
    "maximum query rate",
    "query rate reached",
    "too many queries",
    "too many requests",
    "quota exceeded",
    "limit exceeded",
    "queries exceeded",
    "number of allowed queries",
    "try again later",
    "rate-limited",
];

const REFUSED_PHRASES: &[&str] = &[
    "not permitted",
    "access denied",
    "not authorised",
    "not authorized",
    "refused",
];

/// Registries answer in short lines ("No match for X.COM", "% nothing
/// found"); longer lines are disclaimers, whose wording must not count.
const MAX_MESSAGE_LINE: usize = 100;

/// Decide whether a WHOIS reply describes a registered or a free domain.
///
/// Registration data wins over everything else; "free" needs an explicit
/// phrase or status and no registration data at all. Anything else is
/// unknown: an empty, refused, or unfamiliar reply must never read as
/// AVAILABLE.
pub(crate) fn classify(response: &str, domain: &str) -> Verdict {
    let text = response.to_lowercase().replace('\t', " ");
    let domain = domain.trim_end_matches('.').to_lowercase();

    let mut evidence = 0u8;
    let mut echoed = false;
    let mut free_status = false;
    for line in text.lines().map(str::trim) {
        if is_comment(line) {
            continue;
        }
        let Some((key, value)) = split_field(line) else {
            continue;
        };
        if is_status_key(key) && is_free_value(value) {
            free_status = true;
        } else if is_domain_key(key) {
            echoed |= value
                .split_whitespace()
                .next()
                .map(|v| v.trim_end_matches('.'))
                == Some(domain.as_str());
        } else {
            evidence |= category(key, value);
        }
    }

    if evidence.count_ones() >= 2 || (echoed && evidence != 0) {
        return Verdict::Taken;
    }

    // Short lines only, comments included (.at, .lu, .il answer in `%` lines).
    let messages: Vec<&str> = text
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && l.len() <= MAX_MESSAGE_LINE)
        .collect();
    let says = |phrases: &[&str]| {
        messages
            .iter()
            .any(|l| phrases.iter().any(|p| l.contains(p)))
    };

    if says(RATE_LIMIT_PHRASES) {
        return Verdict::RateLimited;
    }
    let free_phrase = format!("{domain} is free");
    if evidence == 0
        && (free_status || says(FREE_PHRASES) || messages.iter().any(|l| l.contains(&free_phrase)))
    {
        return Verdict::Available;
    }
    // After "free": standard disclaimers say "you are not authorized to…".
    let refused = messages
        .iter()
        .filter(|l| !is_comment(l))
        .any(|l| REFUSED_PHRASES.iter().any(|p| l.contains(p)));
    if refused {
        return Verdict::Unknown("WHOIS server refused the query");
    }
    if text.trim().is_empty() {
        return Verdict::Unknown("WHOIS server sent an empty reply");
    }
    Verdict::Unknown(UNDETERMINED)
}

fn is_comment(line: &str) -> bool {
    line.starts_with('%') || line.starts_with('#') || line.starts_with(">>>")
}

/// Split `key: value` or JPRS-style `[key] value`.
fn split_field(line: &str) -> Option<(&str, &str)> {
    let (key, value) = if let Some(rest) = line.strip_prefix('[') {
        rest.split_once(']')?
    } else {
        line.split_once(':')?
    };
    let key = key.trim();
    if key.is_empty() || key.len() > 40 || key.starts_with("http") {
        return None;
    }
    Some((key, value.trim()))
}

fn is_domain_key(key: &str) -> bool {
    matches!(key, "domain" | "domain name" | "domainname" | "domain-name")
}

fn is_status_key(key: &str) -> bool {
    key == "status" || key.ends_with(" status") || key == "domaintype"
}

fn is_free_value(value: &str) -> bool {
    value.starts_with("available")
        || value.starts_with("free")
        || value.starts_with("not registered")
        || value.starts_with("no object found")
}

/// Map one field to the kind of registration data it carries, if any.
fn category(key: &str, value: &str) -> u8 {
    let has_value = !value.is_empty();
    // Headers whose data follows on the next lines (e.g. `.be`, `.bg`).
    let header = |k: &str| key == k;

    if is_status_key(key) && has_value {
        STATUS
    } else if (key.contains("creat")
        || key == "registered"
        || key.contains("registration date")
        || key.contains("registration time"))
        && has_value
    {
        CREATED
    } else if (key.contains("expir") || key.contains("paid-till") || key.contains("renewal"))
        && has_value
    {
        EXPIRES
    } else if key.starts_with("registrar") || key.starts_with("sponsoring registrar") {
        if has_value || header("registrar") {
            REGISTRAR
        } else {
            0
        }
    } else if key.contains("registrant") || key == "holder" || key.starts_with("owner") {
        if has_value || header("registrant") {
            REGISTRANT
        } else {
            0
        }
    } else if key.contains("nserver") || key.contains("name server") || key.contains("nameserver") {
        NAME_SERVERS
    } else {
        0
    }
}

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

    // ── WhoisClient creation ────────────────────────────────────────────

    #[test]
    fn test_whois_client_new() {
        let client = WhoisClient::new();
        assert_eq!(client.timeout, Duration::from_secs(5));
    }

    #[test]
    fn test_whois_client_with_timeout() {
        let client = WhoisClient::with_timeout(Duration::from_secs(10));
        assert_eq!(client.timeout, Duration::from_secs(10));
    }

    #[test]
    fn test_whois_client_default() {
        let client = WhoisClient::default();
        assert_eq!(client.timeout, Duration::from_secs(5));
    }

    // ── classify: real replies from each registry ──────────────────────
    //
    // Captured 2026-10-09 with `google.<tld>` (taken) and
    // `zq7x9k2m4ptest.<tld>` (free); personal contact fields redacted.

    macro_rules! fixture {
        ($file:literal) => {
            include_str!(concat!("../../tests/fixtures/whois/", $file))
        };
    }

    fn taken_domain(tld: &str) -> String {
        match tld {
            "uk" => "google.co.uk".into(),
            "il" => "google.co.il".into(),
            "nz" => "stuff.co.nz".into(),
            _ => format!("google.{tld}"),
        }
    }

    fn free_domain(tld: &str) -> String {
        match tld {
            "il" => "zq7x9k2m4ptest.co.il".into(),
            _ => format!("zq7x9k2m4ptest.{tld}"),
        }
    }

    const FIXTURES: &[(&str, &str, &str)] = &[
        ("ai", fixture!("ai.taken.txt"), fixture!("ai.free.txt")),
        ("at", fixture!("at.taken.txt"), fixture!("at.free.txt")),
        ("be", fixture!("be.taken.txt"), fixture!("be.free.txt")),
        ("bg", fixture!("bg.taken.txt"), fixture!("bg.free.txt")),
        ("cl", fixture!("cl.taken.txt"), fixture!("cl.free.txt")),
        ("cn", fixture!("cn.taken.txt"), fixture!("cn.free.txt")),
        ("co", fixture!("co.taken.txt"), fixture!("co.free.txt")),
        ("com", fixture!("com.taken.txt"), fixture!("com.free.txt")),
        ("cz", fixture!("cz.taken.txt"), fixture!("cz.free.txt")),
        ("de", fixture!("de.taken.txt"), fixture!("de.free.txt")),
        ("dk", fixture!("dk.taken.txt"), fixture!("dk.free.txt")),
        ("eu", fixture!("eu.taken.txt"), fixture!("eu.free.txt")),
        ("fi", fixture!("fi.taken.txt"), fixture!("fi.free.txt")),
        ("fr", fixture!("fr.taken.txt"), fixture!("fr.free.txt")),
        ("gg", fixture!("gg.taken.txt"), fixture!("gg.free.txt")),
        ("hk", fixture!("hk.taken.txt"), fixture!("hk.free.txt")),
        ("hr", fixture!("hr.taken.txt"), fixture!("hr.free.txt")),
        ("hu", fixture!("hu.taken.txt"), fixture!("hu.free.txt")),
        ("ie", fixture!("ie.taken.txt"), fixture!("ie.free.txt")),
        ("il", fixture!("il.taken.txt"), fixture!("il.free.txt")),
        ("io", fixture!("io.taken.txt"), fixture!("io.free.txt")),
        ("it", fixture!("it.taken.txt"), fixture!("it.free.txt")),
        ("je", fixture!("je.taken.txt"), fixture!("je.free.txt")),
        ("jp", fixture!("jp.taken.txt"), fixture!("jp.free.txt")),
        ("lu", fixture!("lu.taken.txt"), fixture!("lu.free.txt")),
        ("me", fixture!("me.taken.txt"), fixture!("me.free.txt")),
        ("mx", fixture!("mx.taken.txt"), fixture!("mx.free.txt")),
        ("my", fixture!("my.taken.txt"), fixture!("my.free.txt")),
        ("net", fixture!("net.taken.txt"), fixture!("net.free.txt")),
        ("nl", fixture!("nl.taken.txt"), fixture!("nl.free.txt")),
        ("no", fixture!("no.taken.txt"), fixture!("no.free.txt")),
        ("nz", fixture!("nz.taken.txt"), fixture!("nz.free.txt")),
        ("org", fixture!("org.taken.txt"), fixture!("org.free.txt")),
        ("pl", fixture!("pl.taken.txt"), fixture!("pl.free.txt")),
        ("pt", fixture!("pt.taken.txt"), fixture!("pt.free.txt")),
        ("ro", fixture!("ro.taken.txt"), fixture!("ro.free.txt")),
        ("ru", fixture!("ru.taken.txt"), fixture!("ru.free.txt")),
        ("se", fixture!("se.taken.txt"), fixture!("se.free.txt")),
        ("sk", fixture!("sk.taken.txt"), fixture!("sk.free.txt")),
        ("tr", fixture!("tr.taken.txt"), fixture!("tr.free.txt")),
        ("uk", fixture!("uk.taken.txt"), fixture!("uk.free.txt")),
        ("us", fixture!("us.taken.txt"), fixture!("us.free.txt")),
        ("xyz", fixture!("xyz.taken.txt"), fixture!("xyz.free.txt")),
    ];

    #[test]
    fn real_taken_replies_are_taken() {
        let wrong: Vec<_> = FIXTURES
            .iter()
            .filter_map(|(tld, taken, _)| {
                let v = classify(taken, &taken_domain(tld));
                (v != Verdict::Taken).then(|| format!("{tld}: {v:?}"))
            })
            .collect();
        assert!(wrong.is_empty(), "misread taken replies: {wrong:?}");
    }

    #[test]
    fn real_free_replies_are_available() {
        let wrong: Vec<_> = FIXTURES
            .iter()
            .filter_map(|(tld, _, free)| {
                let v = classify(free, &free_domain(tld));
                (v != Verdict::Available).then(|| format!("{tld}: {v:?}"))
            })
            .collect();
        assert!(wrong.is_empty(), "misread free replies: {wrong:?}");
    }

    #[test]
    fn taken_reply_is_never_available_for_another_name() {
        // A taken reply must not read as free just because the queried name
        // differs (e.g. the registry normalised it).
        for (tld, taken, _) in FIXTURES {
            assert_ne!(
                classify(taken, "other-name.example"),
                Verdict::Available,
                "{tld}"
            );
        }
    }

    #[test]
    fn refused_replies_are_unknown() {
        // .ch and .li only answer on their website.
        for reply in [fixture!("ch.taken.txt"), fixture!("li.free.txt")] {
            assert_eq!(
                classify(reply, "google.ch"),
                Verdict::Unknown("WHOIS server refused the query")
            );
        }
    }

    // ── classify: edge cases ────────────────────────────────────────────

    #[test]
    fn empty_reply_is_unknown_not_available() {
        // Used to be AVAILABLE (any reply under 50 characters counted as free).
        assert!(matches!(classify("", "x.com"), Verdict::Unknown(_)));
        assert!(matches!(classify("  \r\n", "x.com"), Verdict::Unknown(_)));
        assert!(matches!(
            classify("Some short text", "x.com"),
            Verdict::Unknown(_)
        ));
    }

    #[test]
    fn rate_limit_in_comment_is_detected() {
        let lu = "% WHOIS zq7x9k2m4ptest.lu\n%% Maximum query rate reached\n";
        assert_eq!(classify(lu, "zq7x9k2m4ptest.lu"), Verdict::RateLimited);
        assert_eq!(
            classify("Rate limit exceeded. Try again later.", "x.com"),
            Verdict::RateLimited
        );
    }

    #[test]
    fn disclaimer_phrases_do_not_override_registration_data() {
        let reply = "Domain Name: x.com\nRegistrar: Example\nCreation Date: 2020-01-01\n\
                     % If a domain is not found, it may be available.";
        assert_eq!(classify(reply, "x.com"), Verdict::Taken);
    }

    #[test]
    fn not_available_status_is_taken() {
        let be = "Domain:\tx.be\nStatus:\tNOT AVAILABLE\n";
        assert_eq!(classify(be, "x.be"), Verdict::Taken);
    }

    #[test]
    fn free_status_with_echo_is_available() {
        assert_eq!(
            classify("Domain: x.de\nStatus: free\n", "x.de"),
            Verdict::Available
        );
        assert_eq!(
            classify(
                "Domain:             x.it\nStatus:             AVAILABLE\n",
                "x.it"
            ),
            Verdict::Available
        );
    }

    #[test]
    fn single_field_without_echo_is_unknown() {
        let reply = "Registrar: SomeRegistrar\nSome other random text that is long enough";
        assert_eq!(classify(reply, "x.com"), Verdict::Unknown(UNDETERMINED));
    }

    #[test]
    fn whois_database_timestamp_is_not_evidence() {
        let reply = "No match for \"X.COM\".\n>>> Last update of whois database: 2026-10-10 <<<";
        assert_eq!(classify(reply, "x.com"), Verdict::Available);
    }

    // Found in review: each of these used to give a wrong verdict.

    #[test]
    fn registration_data_blocks_available_even_without_echo() {
        // Echo differs from the query (IDN/normalised) and a disclaimer
        // says "does not exist": must not read as free.
        let reply = "Domain Name: EXAMPLE.TLD\nDomain Status: ok\n\nIf the domain does not exist, contact us";
        assert_ne!(classify(reply, "other.tld"), Verdict::Available);
        let reply = "Registrar:\nNo match for nameserver ns1.example";
        assert_ne!(classify(reply, "other.tld"), Verdict::Available);
    }

    #[test]
    fn rate_limit_wins_over_free_phrase() {
        assert_eq!(
            classify(
                "Your query rate limit was exceeded; object not found",
                "x.com"
            ),
            Verdict::RateLimited
        );
        assert_eq!(
            classify(
                "% Error: 101: no entries found\n% Too many queries",
                "x.com"
            ),
            Verdict::RateLimited
        );
    }

    #[test]
    fn free_status_with_update_timestamp_is_available() {
        let reply = "Domain: example.be\nStatus: AVAILABLE\nLast update: 2026";
        assert_eq!(classify(reply, "example.be"), Verdict::Available);
    }

    #[test]
    fn disclaimer_rate_limit_wording_is_not_a_rate_limit() {
        // .ai/.io/.me and .uk disclaimers talk about throttling and query
        // rates; a reply without data must not trigger a retry because of it.
        let reply = "Queries to the Whois services are throttled. If too many queries are received from a single IP address within a specified time, the service will begin to reject further queries for a period of time to prevent disruption of Whois service access. Abuse of the Whois system through data mining is mitigated by detecting and limiting bulk query access from single sources.";
        assert_ne!(classify(reply, "x.ai"), Verdict::RateLimited);
    }

    #[test]
    fn jprs_query_uses_english_suffix() {
        assert_eq!(query_for("whois.jprs.jp", "google.jp"), "google.jp/e");
        assert_eq!(query_for("whois.nic.it", "google.it"), "google.it");
    }

    // ── Politeness: per-server concurrency cap ──────────────────────────

    /// Registries throttle bulk queries (whois.nic.it slows replies to 15 s+
    /// after a burst), so one server never gets more than
    /// MAX_QUERIES_PER_SERVER queries at a time, whatever the check
    /// concurrency (#39).
    #[tokio::test]
    async fn queries_to_one_server_are_capped() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let active = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let (a, p) = (active.clone(), peak.clone());
        tokio::spawn(async move {
            loop {
                let (mut sock, _) = listener.accept().await.unwrap();
                let (a, p) = (a.clone(), p.clone());
                tokio::spawn(async move {
                    let now = a.fetch_add(1, Ordering::SeqCst) + 1;
                    p.fetch_max(now, Ordering::SeqCst);
                    let mut buf = [0u8; 256];
                    let _ = sock.read(&mut buf).await;
                    tokio::time::sleep(Duration::from_millis(150)).await;
                    let reply = "Domain: x.test\nStatus: ok\nCreated: 2020-01-01\n";
                    let _ = sock.write_all(reply.as_bytes()).await;
                    a.fetch_sub(1, Ordering::SeqCst);
                });
            }
        });

        let client = WhoisClient::with_port(Duration::from_secs(5), port);
        let checks = (0..6).map(|_| client.check_domain_with_server("x.test", "127.0.0.1"));
        for result in futures_util::future::join_all(checks).await {
            assert_eq!(result.unwrap().available, Some(false));
        }
        let peak = peak.load(Ordering::SeqCst);
        assert!(
            peak <= MAX_QUERIES_PER_SERVER,
            "{peak} concurrent queries to one server"
        );
    }

    // ── IANA discovery: "no WHOIS" vs "couldn't ask" ───────────────────

    #[test]
    fn iana_reply_without_whois_means_none_listed() {
        // .dev/.app (Google) run RDAP only.
        let dev = "% IANA WHOIS server\n\ndomain:       DEV\norganisation: Charleston Road Registry Inc.\nstatus:       ACTIVE\n";
        assert_eq!(parse_iana_discovery(dev), WhoisServer::NoneListed);
        assert_eq!(
            parse_iana_discovery("refer:        whois.nic.it\n\ndomain:       IT\n"),
            WhoisServer::Known("whois.nic.it".into())
        );
    }

    #[test]
    fn unusable_iana_reply_is_unreachable_not_none_listed() {
        // A blocked port or a garbled reply must never read as "this
        // registry has no WHOIS": that would make RDAP 404 final.
        assert_eq!(parse_iana_discovery(""), WhoisServer::Unreachable);
        assert_eq!(
            parse_iana_discovery("% rate limit exceeded\n"),
            WhoisServer::Unreachable
        );
    }

    #[test]
    fn no_whois_service_error_is_recognised() {
        assert!(is_no_whois_service(&no_whois_service_error("x.dev")));
        assert!(!is_no_whois_service(&DomainCheckError::whois(
            "x.dev",
            UNDETERMINED
        )));
        assert!(!is_no_whois_service(&DomainCheckError::timeout(
            "WHOIS query",
            Duration::from_secs(5)
        )));
    }

    // ── parse_iana_refer_response ───────────────────────────────────────

    #[test]
    fn test_iana_refer_standard() {
        let response =
            "% IANA WHOIS server\n\nrefer:        whois.verisign-grs.com\n\ndomain:       COM\n";
        assert_eq!(
            parse_iana_refer_response(response),
            Some("whois.verisign-grs.com".to_string())
        );
    }

    #[test]
    fn test_iana_refer_none() {
        let response = "% IANA WHOIS server\ndomain: TEST\nstatus: ACTIVE\n";
        assert_eq!(parse_iana_refer_response(response), None);
    }

    #[test]
    fn test_iana_refer_empty_value() {
        let response = "refer:        \ndomain: COM\n";
        assert_eq!(parse_iana_refer_response(response), None);
    }

    #[test]
    fn test_iana_whois_field_fallback() {
        let response = "whois:        whois.verisign-grs.com\ndomain: COM\n";
        assert_eq!(
            parse_iana_refer_response(response),
            Some("whois.verisign-grs.com".to_string())
        );
    }

    #[test]
    fn test_iana_refer_takes_precedence_over_whois() {
        let response =
            "whois:        whois.old-server.com\nrefer:        whois.correct-server.com\n";
        assert_eq!(
            parse_iana_refer_response(response),
            Some("whois.correct-server.com".to_string())
        );
    }

    #[test]
    fn test_iana_empty_whois_field() {
        let response = "whois:        \ndomain: COM\n";
        assert_eq!(parse_iana_refer_response(response), None);
    }

    #[test]
    fn test_iana_empty_response() {
        assert_eq!(parse_iana_refer_response(""), None);
    }

    // ── Network-dependent tests ─────────────────────────────────────────

    #[tokio::test]
    async fn live_whois_over_tcp() {
        let client = WhoisClient::new();
        match client
            .check_domain_with_server("google.com", "whois.verisign-grs.com")
            .await
        {
            Ok(result) => assert_eq!(result.available, Some(false)),
            // Port 43 may be blocked on some networks; don't fail on that.
            Err(e) => eprintln!("skipped: WHOIS over TCP unavailable: {e}"),
        }
    }

    #[tokio::test]
    async fn live_iana_discovery() {
        match discover("it").await {
            WhoisServer::Known(server) => assert_eq!(server, "whois.nic.it"),
            WhoisServer::NoneListed => panic!("IANA lists whois.nic.it for .it"),
            WhoisServer::Unreachable => eprintln!("skipped: whois.iana.org unreachable"),
        }
        if let WhoisServer::Known(server) = discover("dev").await {
            panic!(".dev runs RDAP only, IANA listed {server}");
        }
    }
}