//! Reading a plain-text registry answer; the protocol has no status codes, so every signal is weighed.
use crate::lookup::outcome::{Reason, scrub};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TextVerdict {
Available,
Taken,
Unknown(Reason),
}
const TAKEN_MARKERS: &[&str] = &[
"already registered",
"is already in use",
"domain status: registered",
"status: registered",
"status: connect",
"status: active",
"registrant",
"registrar:",
"sponsoring registrar",
"creation date",
"created:",
"created on",
"registered on",
"activation date",
"expiry date",
"expiration date",
"registry expiry date",
"name server",
"nameserver",
"nserver",
"cannot be registered",
"can not be registered",
"not available for registration",
];
const AVAILABLE_MARKERS: &[&str] = &[
// @docgen Hungary answers a free name with "Nincs talalat / No match" and nothing else, so the trailing "for" cannot be required.
"no match",
"no matching record",
// @docgen Austria's whole answer for a free name is "% nothing found", which shares no substring with "not found".
"nothing found",
"no object found",
// @docgen Mexico joins its words with underscores, so "Object_Not_Found" shares no substring with the spaced form.
"object_not_found",
// @docgen Argentina answers only this sentence, with no newline and no field, so nothing else in the reply can carry the verdict.
"no se encuentra registrado",
"no entries found",
"no data found",
"not found",
"does not exist",
"no such domain",
"domain not found",
"not registered",
// @docgen Hong Kong's whole answer for a free name; "not registered" is not a substring of "has not been registered".
"not been registered",
// @docgen Israel's wording, which shares no substring with "no data found".
"no data was found",
"is available",
"domain status: available",
"status: free",
"status: available",
"available for registration",
];
/// @docgen A name the registry refuses to register is a real answer, never a free one.
const NOT_REGISTRABLE_MARKERS: &[&str] = &[
"reserved word",
"reserved name",
"is reserved",
"name is blocked",
"blocked name",
"prohibited name",
"restricted name",
"not permitted for registration",
// @docgen BTCL's own spelling of "uncensored"; both are carried because the reply is matched verbatim.
"contains unsensored word",
"contains uncensored word",
];
const DECLINED_MARKERS: &[&str] = &[
"tld is not supported",
"tld not supported",
"not supported by this registry",
"this tld has no whois server",
"no whois server is known",
"access denied",
"requests of this client are not permitted",
"queries are not permitted",
"not allowed for this domain category",
"use only approved characters",
];
/// @docgen A refusal says a limit was passed. Several registries also print a standing notice that the service *is* rate limited, on answers they served perfectly, so the bare phrase cannot be one of these.
const RATE_LIMIT_MARKERS: &[&str] = &[
"limit exceeded",
"rate limit exceeded",
"too many requests",
// @docgen HKIRC refuses a fast caller with this bare code and nothing else, so there is no sentence to match.
"cmm174",
"try again later",
"quota exceeded",
"quota has been exceeded",
"temporarily unavailable",
"service unavailable",
"connection refused",
"blocked",
];
/// @docgen A registry's closing notice repeats the very words a verdict is read from - "registrant", "available", "registered" - on answers it served perfectly, so the record above it is where the verdict lives.
const NOTICE_STARTS: &[&str] = &[
">>> last update of whois database",
"terms of use:",
"note: failure to locate a record",
"notice: the expiration date",
"by submitting this query",
"access to whois information is provided",
"the data in this record is provided",
];
fn record_of(text: &str) -> &str {
// @docgen Plenty of registries open with the notice instead of closing with it, and cutting there would throw away the answer that follows.
let cut = NOTICE_STARTS
.iter()
.filter_map(|marker| text.find(marker))
.filter(|at| carries_a_record(&text[..*at]))
.min();
match cut {
Some(at) => &text[..at],
None => text,
}
}
fn carries_a_record(head: &str) -> bool {
head.lines().any(|line| {
let line = line.trim();
!line.is_empty() && !line.starts_with('%') && !line.starts_with('#')
})
}
/// @docgen The registry's own free-name phrase is trusted only where it is not negated, or "not available" reads as free.
pub(crate) fn classify(raw: &str, available_phrase: &str, domain: &str) -> TextVerdict {
let text = normalize(raw);
if text.trim().is_empty() {
return TextVerdict::Unknown(Reason::Malformed {
detail: "the registry sent nothing back".to_owned(),
});
}
// @docgen Read from the record alone; a throttle or a refusal can sit anywhere, so those still scan the whole reply.
let record = record_of(&text);
let held = TAKEN_MARKERS.iter().any(|marker| unnegated(record, marker));
let absent = AVAILABLE_MARKERS
.iter()
.any(|marker| unnegated(record, marker));
let declined = DECLINED_MARKERS
.iter()
.find(|marker| text.contains(**marker));
let blocked = NOT_REGISTRABLE_MARKERS
.iter()
.any(|marker| text.contains(*marker));
let throttled = RATE_LIMIT_MARKERS
.iter()
.find(|marker| text.contains(**marker));
let by_needle =
!available_phrase.trim().is_empty() && unnegated(record, &normalize(available_phrase));
// @docgen Throttling never describes the name, so it is checked before anything that could be read as an answer.
if throttled.is_some() && !held {
return TextVerdict::Unknown(Reason::RateLimited);
}
if let Some(marker) = declined {
return TextVerdict::Unknown(Reason::Declined {
detail: (*marker).to_owned(),
});
}
if blocked {
return TextVerdict::Unknown(Reason::NotRegistrable);
}
// @docgen An answer about some other name proves nothing about the one asked, so it must not be read either way.
if let Some(subject) = subject_of(raw)
&& subject != domain.trim_end_matches('.').to_lowercase()
{
return TextVerdict::Unknown(Reason::WrongSubject {
answered_about: subject,
});
}
// @docgen In a full record "not available" usually refers to withheld contact data, so only a terse reply reads as taken.
let terse = record.trim().len() < 40;
if terse && !held && (record.contains("not available") || record.contains("unavailable")) {
return TextVerdict::Taken;
}
match (held, absent || by_needle) {
// @docgen A record that also carries an available phrase is still a record, so held wins and the name never reads as free.
(true, true) => TextVerdict::Taken,
(true, false) => TextVerdict::Taken,
(false, true) => TextVerdict::Available,
(false, false) => TextVerdict::Unknown(Reason::Malformed {
detail: "the answer matched nothing we recognise".to_owned(),
}),
}
}
fn unnegated(haystack: &str, needle: &str) -> bool {
if needle.is_empty() {
return false;
}
let mut from = 0;
while let Some(offset) = haystack.get(from..).and_then(|rest| rest.find(needle)) {
let at = from + offset;
let before = haystack.get(..at).unwrap_or_default();
let last_word = before
.trim_end()
.rsplit(|c: char| !c.is_alphanumeric() && c != '\'')
.next()
.unwrap_or_default();
let negated = matches!(last_word, "not" | "no" | "isn't" | "cannot" | "never")
|| before.ends_with("un")
|| before.ends_with("non");
if !negated {
return true;
}
from = at.saturating_add(needle.len().max(1));
}
false
}
fn subject_of(raw: &str) -> Option<String> {
for line in raw.lines() {
// @docgen Real replies open with a banner, so ending the scan on the first colonless line disables this guard.
let Some((key, value)) = line.trim().split_once(':') else {
continue;
};
let key = key.trim().to_lowercase();
if matches!(
key.as_str(),
"domain name" | "domain" | "domainname" | "internationalized domain name"
) {
let value = value.trim().trim_end_matches('.').to_lowercase();
if !value.is_empty() && value.contains('.') {
return Some(scrub(&value));
}
}
}
None
}
/// @docgen Collapsing spacing keeps marker matching independent of how a registry lays out its columns.
fn normalize(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut last_was_space = false;
for ch in raw.chars() {
let ch = if ch == '\t' { ' ' } else { ch };
if ch == ' ' {
if !last_was_space {
out.push(' ');
}
last_was_space = true;
} else {
last_was_space = false;
out.extend(ch.to_lowercase());
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// @docgen Every reply below was captured from the live registry, so a change that breaks one of these has broken a real lookup.
#[test]
fn a_standing_notice_that_a_service_is_rate_limited_is_not_a_refusal() {
let served = "The queried object does not exist: DOMAIN NOT FOUND\n\n >>> Last update of WHOIS database: 2026-08-19T20:01:25.0Z <<<\n\n Access to the whois service is rate limited. For more information, please\n see the referenced URL.\n";
assert_eq!(
classify(served, "", "probe.la"),
TextVerdict::Available,
"this answer was served, and the notice at the foot of it is policy text"
);
}
#[test]
fn a_refusal_that_says_a_limit_was_passed_is_still_a_refusal() {
for refusal in [
"% Quota exceeded",
"WHOIS LIMIT EXCEEDED - SEE WWW.PIR.ORG",
"Too many requests, please try again later",
] {
assert!(
matches!(
classify(refusal, "", "probe.test"),
TextVerdict::Unknown(Reason::RateLimited)
),
"{refusal} must never read as an answer"
);
}
}
/// @docgen Captured from the live registry: the free reply carries a terms-of-use notice that says "contact the registrant", which read as a record and marked a free name taken.
#[test]
fn a_closing_legal_notice_never_decides_the_verdict() {
let free = "Domain not found.\n\n >>> Last update of WHOIS database: 2026-08-19T20:02:00Z <<<\n\n Terms of Use: Access to WHOIS information is provided to assist persons in determining the contents of a domain name registration record in the registry database. Should you wish to contact the registrant, please refer to the Whois records available through the registrar URL listed above. Queries to the Whois services are throttled. By submitting this query, you agree to abide by this policy.\n";
assert_eq!(
classify(free, "Domain not found", "probe.bz"),
TextVerdict::Available,
"the notice mentions a registrant and throttling; the record says the name is free"
);
}
/// @docgen Captured live: these three open with the notice, so cutting at it would have thrown the answer away.
#[test]
fn a_notice_printed_before_the_answer_never_hides_it() {
for (reply, zone) in [
(
"% TCI Whois Service. Terms of use:\n% https://tcinet.ru/documents/whois_ru_rf.pdf (in Russian)\n\nNo entries found for the selected source(s).\n",
"probe.ru",
),
(
"% Access to RESTENA DNS-LU WHOIS information is provided to assist persons\n% in determining the content of a domain name registration record in the LU\n% registration database. The data in this record is provided by RESTENA DNS-LU\n% for information purposes only.\n\n% No such domain sazzad-reserve-probe-2026.lu\n",
"probe.lu",
),
] {
assert_eq!(
classify(reply, "", zone),
TextVerdict::Available,
"{zone} opens with its notice and answers underneath it"
);
}
}
#[test]
fn a_record_that_precedes_the_notice_is_still_read() {
let taken = "Domain Name: google.bz\nRegistrar: MarkMonitor Inc.\nCreation Date: 2006-02-12T18:08:52Z\n\n >>> Last update of WHOIS database: 2026-08-19T20:02:00Z <<<\n\n Terms of Use: Should you wish to contact the registrant, refer to the registrar.\n";
assert_eq!(
classify(taken, "Domain not found", "google.bz"),
TextVerdict::Taken
);
}
#[test]
fn a_free_name_is_recognised_in_each_registrys_own_wording() {
for (reply, zone) in [
("% nothing found", "probe.at"),
(
"% Whois server 4.1 serving the hu ccTLD\n\n\r\nNincs talalat / No match\r\n",
"probe.hu",
),
(
"El dominio no se encuentra registrado en NIC Argentina",
"probe.com.ar",
),
(
"\r\nNo_Se_Encontro_El_Objeto/Object_Not_Found\r\n",
"probe.mx",
),
("Domain not found.\n", "probe.bz"),
] {
assert_eq!(
classify(reply, "", zone),
TextVerdict::Available,
"{zone} was not read as free"
);
}
}
#[test]
fn a_registered_name_in_those_same_registries_is_never_read_as_free() {
for (reply, zone) in [
(
"% Whois server 4.1 serving the hu ccTLD\n\n\r\ndomain: index.hu\r\nrecord created: 1999-05-17\r\n",
"index.hu",
),
(
"domain:\t\tclarin.com.ar\nregistrant:\t30500124152\nregistrar:\tnicar\nnserver:\tcash.ns.cloudflare.com ()\n",
"clarin.com.ar",
),
(
"\r\nDomain Name: unam.mx\r\n\r\nCreated On: 1989-03-31\r\nExpiration Date: 2027-03-30\r\nRegistrar: AKKY ONLINE SOLUTIONS, S.A. DE C.V.\r\n",
"unam.mx",
),
(
"Domain Name: google.bz\nRegistry Domain ID: 461b9755-DONUTS\nCreation Date: 2006-02-12T18:08:52Z\nRegistry Expiry Date: 2027-02-12T18:08:52Z\nRegistrar: MarkMonitor Inc.\n",
"google.bz",
),
] {
assert_eq!(classify(reply, "", zone), TextVerdict::Taken, "{zone}");
}
}
#[test]
fn a_free_name_is_read_as_free() {
let raw = "Domain Name: example.bd\nDomain Status: Available\n\
Whois Server: whois.get.bd\nMessage: Domain is available";
assert_eq!(
classify(raw, "Domain is available", "example.bd"),
TextVerdict::Available
);
}
#[test]
fn a_held_name_wins_over_a_status_of_error() {
// @docgen A real registry answers a taken name with a status of error, and matching that first would call it unknown.
let raw = "Domain Name: sample.bd\nDomain Status: Error\n\
Whois Server: whois.get.bd\nMessage: Domain already registered";
assert_eq!(
classify(raw, "Domain is available", "sample.bd"),
TextVerdict::Taken
);
}
#[test]
fn a_full_record_reads_as_taken() {
let raw = "Domain Name: demo.bd\nDomain Status: Registered\n\
Registrant's Name: Someone\nActivation Date: 14/01/2026\n\
Expiry Date: 14/01/2028\nPrimary DNS: a.ns.example";
assert_eq!(
classify(raw, "Domain is available", "demo.bd"),
TextVerdict::Taken
);
}
#[test]
fn a_throttle_is_never_read_as_free() {
for raw in [
"Query rate limit exceeded, try again later",
"WHOIS LIMIT EXCEEDED - NOT FOUND",
"Too many requests from your address",
] {
match classify(raw, "", "x.com") {
TextVerdict::Unknown(Reason::RateLimited) => {}
other => panic!("{raw:?} became {other:?}"),
}
}
}
#[test]
fn a_negated_phrase_does_not_read_as_free() {
// @docgen A registry answering only "Available" or "Not Available" turns a plain substring test into a false free on every taken name.
assert_eq!(
classify("Not Available", "Available", "x.au"),
TextVerdict::Taken
);
assert_eq!(
classify("Available", "Available", "example.test"),
TextVerdict::Available
);
}
#[test]
fn attached_negation_is_caught() {
assert!(!unnegated("this name is unavailable", "available"));
assert!(!unnegated("this name is not available", "available"));
assert!(unnegated("this name is available", "available"));
assert!(!unnegated("nonavailable", "available"));
}
#[test]
fn an_answer_about_another_name_is_refused() {
let raw = "Domain Name: ac.bd\nStatus: active\nRegistrar: someone";
match classify(raw, "", "example.ac.bd") {
TextVerdict::Unknown(Reason::WrongSubject { answered_about }) => {
assert_eq!(answered_about, "ac.bd");
}
other => panic!("expected a refusal, got {other:?}"),
}
}
#[test]
fn a_banner_before_the_record_does_not_disable_the_wrong_subject_guard() {
// @docgen A banner or blank line opens real replies, and ending the scan there would let an answer about another name read as available.
let raw = "% This is the registry whois server.\n%\n\n\
Domain Name: ac.bd\nStatus: active\nRegistrar: someone";
match classify(raw, "", "example.ac.bd") {
TextVerdict::Unknown(Reason::WrongSubject { answered_about }) => {
assert_eq!(answered_about, "ac.bd");
}
other => panic!("a banner must not disable the guard, got {other:?}"),
}
}
#[test]
fn a_banner_before_a_no_match_still_reads_as_available() {
let raw = "% registry banner\n\nNo match for \"NOTHING.COM\".";
assert_eq!(classify(raw, "", "nothing.com"), TextVerdict::Available);
}
#[test]
fn a_declined_extension_is_unclear_not_free() {
let raw = "This TLD has no whois server, but you can access the whois database";
assert!(matches!(classify(raw, "", "x.zz"), TextVerdict::Unknown(_)));
}
#[test]
fn an_empty_answer_is_unclear() {
assert!(matches!(classify("", "", "x.com"), TextVerdict::Unknown(_)));
assert!(matches!(
classify(" \n ", "", "x.com"),
TextVerdict::Unknown(_)
));
}
#[test]
fn an_unrecognised_answer_is_unclear_not_free() {
assert!(matches!(
classify("something entirely unexpected", "", "x.com"),
TextVerdict::Unknown(_)
));
}
#[test]
fn a_classic_no_match_reads_as_free() {
assert_eq!(
classify("No match for \"NOTHING.COM\".", "", "nothing.com"),
TextVerdict::Available
);
assert_eq!(
classify("NOT FOUND", "", "nothing.com"),
TextVerdict::Available
);
assert_eq!(
classify("Status: free", "", "nothing.de"),
TextVerdict::Available
);
}
#[test]
fn layout_does_not_change_the_reading() {
let spaced = "Domain Status:\t\tAvailable\nMessage: Domain is available";
assert_eq!(
classify(spaced, "Domain is available", "x.bd"),
TextVerdict::Available
);
}
#[test]
fn a_record_that_also_says_available_still_reads_as_taken() {
// @docgen Contact data withheld for privacy often contains "not available", which must not read as free.
let raw = "Domain Name: x.com\nRegistrar: Example\nCreation Date: 2020-01-01\n\
Registrant Phone: not available";
assert_eq!(classify(raw, "", "x.com"), TextVerdict::Taken);
}
}