From: Michael Tremer Date: Sat, 6 Dec 2025 15:47:49 +0000 (+0000) Subject: util: Add a helper function to check if something is a valid FQDN X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e31b0b06904ad61749b8d1f499a9b5b94dad4050;p=dbl.git util: Add a helper function to check if something is a valid FQDN Signed-off-by: Michael Tremer --- diff --git a/src/dnsbl/util.py b/src/dnsbl/util.py index a35aa3c..bd8e8cd 100644 --- a/src/dnsbl/util.py +++ b/src/dnsbl/util.py @@ -18,6 +18,7 @@ # # ############################################################################### +import idna import re import unicodedata @@ -43,3 +44,37 @@ def slugify(text, iteration=None): text = re.sub(r"-+", "-", text) return text + +def is_fqdn(s): + """ + Checks if a string is a valid FQDN. + """ + # Decode any internationalized domains names + try: + s = idna.encode(s).decode("ascii") + except idna.IDNAError: + return False + + if len(s) > 253: + return False + + # Remove final dot, allowed in DNS but not in DB checks + if s.endswith("."): + s = s[:-1] + + labels = s.split(".") + + # FQDN must have at least two labels (e.g., example.com) + if len(labels) < 2: + return False + + for label in labels: + if not 1 <= len(label) <= 63: + return False + if not label[0].isalnum() or not label[-1].isalnum(): + return False + for ch in label: + if not (ch.isalnum() or ch == "-"): + return False + + return True