]> git.ipfire.org Git - dbl.git/commitdiff
util: Add a helper function to check if something is a valid FQDN
authorMichael Tremer <michael.tremer@ipfire.org>
Sat, 6 Dec 2025 15:47:49 +0000 (15:47 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Sat, 6 Dec 2025 15:47:49 +0000 (15:47 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/dnsbl/util.py

index a35aa3c66c30c04628b50a8c33baefdd173d7a9e..bd8e8cd249fcd886e42102044aee344297ad218a 100644 (file)
@@ -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