[PATCH consfigurator v2 3/6] add #'valid-hostname-p

David Bremner david at tethera.net
Thu Mar 10 00:28:57 GMT 2022


Initial intended application is checking data source IDEN1. This could be done
as a one-liner with a more complex regex, but that seems harder to debug.
---
 src/package.lisp |  2 ++
 src/util.lisp    | 13 +++++++++++++
 tests/util.lisp  | 30 ++++++++++++++++++++++++++++++
 3 files changed, 45 insertions(+)

diff --git a/src/package.lisp b/src/package.lisp
index d1c5836..ea2c580 100644
--- a/src/package.lisp
+++ b/src/package.lisp
@@ -106,6 +106,7 @@
            #:words
            #:unwords
            #:noop
+           #:starts-with-string
            #:symbol-named
            #:memstring=
            #:define-simple-error
@@ -127,6 +128,7 @@
            #:parse-cidr
            #:system
            #:random-alphanumeric
+           #:valid-hostname-p
 
            #:*consfigurator-debug-level*
            #:with-indented-inform
diff --git a/src/util.lisp b/src/util.lisp
index f0ca5cb..79d9d0b 100644
--- a/src/util.lisp
+++ b/src/util.lisp
@@ -742,3 +742,16 @@ Does not currently establish a PAM session."
     (when-let ((output-stream (stream->output-stream stream)))
       (when (open-stream-p output-stream)
         (funcall function output-stream)))))
+
+
+;;;; Hostnames
+
+(defun valid-hostname-p (string)
+  "Test whether STRING looks like a valid hostname."
+  (and
+   (<= (length string) 253)
+   (let ((parts (split-string string :separator ".")))
+     (every (lambda (part)
+              (and (<= (length part) 63)
+                   (re:scan "^[a-zA-Z0-9][a-zA-Z0-9-]*$" part)))
+            parts))))
diff --git a/tests/util.lisp b/tests/util.lisp
index bffda68..6b5cb62 100644
--- a/tests/util.lisp
+++ b/tests/util.lisp
@@ -17,3 +17,33 @@
 (deftest version<.4 (version< "1.a.1" "1.1") t)
 
 (deftest version<.5 (version< "1..1" "1.1") t)
+
+;; without domain
+(deftest valid-hostname-p.1 (valid-hostname-p "localhost") t)
+
+(deftest valid-hostname-p.2 (valid-hostname-p "host.example.com") t)
+
+;; case insensitive check
+(deftest valid-hostname-p.3 (valid-hostname-p "host.Example.Com") t)
+
+;; "total length too long"
+(deftest valid-hostname-p.4
+    (valid-hostname-p (format nil "~{~A~^.~}"
+                              (make-list 128 :initial-element "a"))) nil)
+
+;; label too long
+(deftest valid-hostname-p.5
+    (valid-hostname-p (strcat (make-string 64 :initial-element #\a) ".com"))
+  nil)
+
+;; valid use of `-'
+(deftest valid-hostname-p.6 (valid-hostname-p "host-name.example.com") t)
+
+;; invalid use of `-'
+(deftest valid-hostname-p.7 (valid-hostname-p "-hostname.example.com") nil)
+
+;; invalid character
+(deftest valid-hostname-p.8 (valid-hostname-p "_hostname.example.com") nil)
+
+;; invalid character 2
+(deftest valid-hostname-p.8 (valid-hostname-p "foo/bar") nil)
-- 
2.34.1




More information about the sgo-software-discuss mailing list