3 ;;; DNS zone generation
5 ;;; (c) 2005 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This program is free software; you can redistribute it and/or modify
11 ;;; it under the terms of the GNU General Public License as published by
12 ;;; the Free Software Foundation; either version 2 of the License, or
13 ;;; (at your option) any later version.
15 ;;; This program is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;;; GNU General Public License for more details.
20 ;;; You should have received a copy of the GNU General Public License
21 ;;; along with this program; if not, write to the Free Software Foundation,
22 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 ;;;--------------------------------------------------------------------------
29 #:mdw.base #:mdw.str #:collect #:safely
31 (:import-from #:net #:round-down #:round-up))
35 ;;;--------------------------------------------------------------------------
36 ;;; Various random utilities.
39 "Convert X to an integer in the most straightforward way."
42 (defun from-mixed-base (base val)
43 "BASE is a list of the ranges for the `digits' of a mixed-base
44 representation. Convert VAL, a list of digits, into an integer."
45 (do ((base base (cdr base))
46 (val (cdr val) (cdr val))
47 (a (car val) (+ (* a (car base)) (car val))))
48 ((or (null base) (null val)) a)))
50 (defun to-mixed-base (base val)
51 "BASE is a list of the ranges for the `digits' of a mixed-base
52 representation. Convert VAL, an integer, into a list of digits."
53 (let ((base (reverse base))
59 (multiple-value-bind (q r) (floor val (pop base))
63 (export 'timespec-seconds)
64 (defun timespec-seconds (ts)
65 "Convert a timespec TS to seconds.
67 A timespec may be a real count of seconds, or a list (COUNT UNIT). UNIT
68 may be any of a number of obvious time units."
70 ((realp ts) (floor ts))
72 (error "Unknown timespec format ~A" ts))
74 (timespec-seconds (car ts)))
75 (t (+ (to-integer (* (car ts)
76 (case (intern (string-upcase
77 (stringify (cadr ts)))
79 ((s sec secs second seconds) 1)
80 ((m min mins minute minutes) 60)
81 ((h hr hrs hour hours) #.(* 60 60))
82 ((d dy dys day days) #.(* 24 60 60))
83 ((w wk wks week weeks) #.(* 7 24 60 60))
84 ((y yr yrs year years) #.(* 365 24 60 60))
85 (t (error "Unknown time unit ~A"
87 (timespec-seconds (cddr ts))))))
89 (defun hash-table-keys (ht)
90 "Return a list of the keys in hashtable HT."
92 (maphash (lambda (key val) (declare (ignore val)) (collect key)) ht)))
94 (defun iso-date (&optional time &key datep timep (sep #\ ))
95 "Construct a textual date or time in ISO format.
97 The TIME is the universal time to convert, which defaults to now; DATEP is
98 whether to emit the date; TIMEP is whether to emit the time, and
99 SEP (default is space) is how to separate the two."
101 (sec min hr day mon yr dow dstp tz)
102 (decode-universal-time (if (or (null time) (eq time :now))
105 (declare (ignore dow dstp tz))
106 (with-output-to-string (s)
108 (format s "~4,'0D-~2,'0D-~2,'0D" yr mon day)
112 (format s "~2,'0D:~2,'0D:~2,'0D" hr min sec)))))
114 (defun natural-string< (string1 string2
115 &key (start1 0) (end1 nil)
116 (start2 0) (end2 nil))
117 "Answer whether STRING1 precedes STRING2 in a vaguely natural ordering.
119 In particular, digit sequences are handled in a moderately sensible way.
120 Split the strings into maximally long alternating sequences of non-numeric
121 and numeric characters, such that the non-numeric sequences are
122 non-empty. Compare these lexicographically; numeric sequences order
123 according to their integer values, non-numeric sequences in the usual
124 lexicographic ordering.
126 Returns two values: whether STRING1 strictly precedes STRING2, and whether
127 STRING1 strictly follows STRING2."
129 (let ((end1 (or end1 (length string1)))
130 (end2 (or end2 (length string2))))
132 (cond ((>= start1 end1)
133 (let ((eqp (>= start2 end2)))
134 (return (values (not eqp) nil))))
136 (return (values nil t)))
137 ((and (digit-char-p (char string1 start1))
138 (digit-char-p (char string2 start2)))
139 (let* ((lim1 (or (position-if-not #'digit-char-p string1
140 :start start1 :end end1)
142 (n1 (parse-integer string1 :start start1 :end lim1))
143 (lim2 (or (position-if-not #'digit-char-p string2
144 :start start2 :end end2)
146 (n2 (parse-integer string2 :start start2 :end lim2)))
147 (cond ((< n1 n2) (return (values t nil)))
148 ((> n1 n2) (return (values nil t))))
152 (let ((lim1 (or (position-if #'digit-char-p string1
153 :start start1 :end end1)
155 (lim2 (or (position-if #'digit-char-p string2
156 :start start2 :end end2)
158 (cond ((string< string1 string2
159 :start1 start1 :end1 lim1
160 :start2 start2 :end2 lim2)
161 (return (values t nil)))
162 ((string> string1 string2
163 :start1 start1 :end1 lim1
164 :start2 start2 :end2 lim2)
165 (return (values nil t))))
169 (defun domain-name< (name-a name-b)
170 "Answer whether NAME-A precedes NAME-B in an ordering of domain names.
172 Split the names into labels at the dots, and then lexicographically
173 compare the sequences of labels, right to left, using `natural-string<'.
175 Returns two values: whether NAME-A strictly precedes NAME-B, and whether
176 NAME-A strictly follows NAME-B."
177 (let ((pos-a (length name-a))
178 (pos-b (length name-b)))
179 (loop (let ((dot-a (or (position #\. name-a
180 :from-end t :end pos-a)
182 (dot-b (or (position #\. name-b
183 :from-end t :end pos-b)
185 (multiple-value-bind (precp follp)
186 (natural-string< name-a name-b
187 :start1 (1+ dot-a) :end1 pos-a
188 :start2 (1+ dot-b) :end2 pos-b)
190 (return (values t nil)))
192 (return (values nil t)))
194 (let ((eqp (= dot-b -1)))
195 (return (values (not eqp) nil))))
197 (return (values nil t)))
202 ;;;--------------------------------------------------------------------------
206 (defstruct (soa (:predicate soap))
207 "Start-of-authority record information."
217 (defstruct (mx (:predicate mxp))
218 "Mail-exchange record information."
223 (defstruct (zone (:predicate zonep))
230 ;;;--------------------------------------------------------------------------
231 ;;; Zone defaults. It is intended that scripts override these.
233 (export '*default-zone-source*)
234 (defvar *default-zone-source*
235 (let ((hn (gethostname)))
236 (and hn (concatenate 'string (canonify-hostname hn) ".")))
237 "The default zone source: the current host's name.")
239 (export '*default-zone-refresh*)
240 (defvar *default-zone-refresh* (* 24 60 60)
241 "Default zone refresh interval: one day.")
243 (export '*default-zone-admin*)
244 (defvar *default-zone-admin* nil
245 "Default zone administrator's email address.")
247 (export '*default-zone-retry*)
248 (defvar *default-zone-retry* (* 60 60)
249 "Default znoe retry interval: one hour.")
251 (export '*default-zone-expire*)
252 (defvar *default-zone-expire* (* 14 24 60 60)
253 "Default zone expiry time: two weeks.")
255 (export '*default-zone-min-ttl*)
256 (defvar *default-zone-min-ttl* (* 4 60 60)
257 "Default zone minimum TTL/negative TTL: four hours.")
259 (export '*default-zone-ttl*)
260 (defvar *default-zone-ttl* (* 8 60 60)
261 "Default zone TTL (for records without explicit TTLs): 8 hours.")
263 (export '*default-mx-priority*)
264 (defvar *default-mx-priority* 50
265 "Default MX priority.")
267 ;;;--------------------------------------------------------------------------
268 ;;; Zone variables and structures.
270 (defvar *zones* (make-hash-table :test #'equal)
271 "Map of known zones.")
274 (defun zone-find (name)
275 "Find a zone given its NAME."
276 (gethash (string-downcase (stringify name)) *zones*))
277 (defun (setf zone-find) (zone name)
278 "Make the zone NAME map to ZONE."
279 (setf (gethash (string-downcase (stringify name)) *zones*) zone))
281 (export 'zone-record)
282 (defstruct (zone-record (:conc-name zr-))
290 (export 'zone-subdomain)
291 (defstruct (zone-subdomain (:conc-name zs-))
294 Slightly weird. Used internally by `zone-process-records', and shouldn't
300 (export '*zone-output-path*)
301 (defvar *zone-output-path* nil
302 "Pathname defaults to merge into output files.
304 If this is nil then use the prevailing `*default-pathname-defaults*'.
305 This is not the same as capturing the `*default-pathname-defaults*' from
308 (export '*preferred-subnets*)
309 (defvar *preferred-subnets* nil
310 "Subnets to prefer when selecting defaults.")
312 ;;;--------------------------------------------------------------------------
313 ;;; Zone infrastructure.
315 (defun zone-file-name (zone type)
316 "Choose a file name for a given ZONE and TYPE."
317 (merge-pathnames (make-pathname :name (string-downcase zone)
318 :type (string-downcase type))
319 (or *zone-output-path* *default-pathname-defaults*)))
321 (export 'zone-preferred-subnet-p)
322 (defun zone-preferred-subnet-p (name)
323 "Answer whether NAME (a string or symbol) names a preferred subnet."
324 (member name *preferred-subnets* :test #'string-equal))
326 (export 'preferred-subnet-case)
327 (defmacro preferred-subnet-case (&body clauses)
328 "Execute a form based on which networks are considered preferred.
330 The CLAUSES have the form (SUBNETS . FORMS) -- evaluate the first FORMS
331 whose SUBNETS (a list or single symbol, not evaluated) are listed in
332 `*preferred-subnets*'. If SUBNETS is the symbol `t' then the clause
335 ,@(mapcar (lambda (clause)
336 (let ((subnets (car clause)))
337 (cons (cond ((eq subnets t)
340 `(or ,@(mapcar (lambda (subnet)
341 `(zone-preferred-subnet-p
345 `(zone-preferred-subnet-p ',subnets)))
349 (export 'zone-parse-host)
350 (defun zone-parse-host (f zname)
351 "Parse a host name F.
353 If F ends in a dot then it's considered absolute; otherwise it's relative
355 (setf f (stringify f))
356 (cond ((string= f "@") (stringify zname))
357 ((and (plusp (length f))
358 (char= (char f (1- (length f))) #\.))
359 (string-downcase (subseq f 0 (1- (length f)))))
360 (t (string-downcase (concatenate 'string f "."
361 (stringify zname))))))
363 (export 'zone-make-name)
364 (defun zone-make-name (prefix zone-name)
365 "Compute a full domain name from a PREFIX and a ZONE-NAME.
367 If the PREFIX ends with `.' then it's absolute already; otherwise, append
368 the ZONE-NAME, separated with a `.'. If PREFIX is nil, or `@', then
369 return the ZONE-NAME only."
370 (if (or (not prefix) (string= prefix "@"))
372 (let ((len (length prefix)))
373 (if (or (zerop len) (char/= (char prefix (1- len)) #\.))
374 (join-strings #\. (list prefix zone-name))
377 (export 'zone-records-sorted)
378 (defun zone-records-sorted (zone)
379 "Return the ZONE's records, in a pleasant sorted order."
380 (sort (copy-seq (zone-records zone))
382 (multiple-value-bind (precp follp)
383 (domain-name< (zr-name zr-a) (zr-name zr-b))
386 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
388 ;;;--------------------------------------------------------------------------
389 ;;; Serial numbering.
391 (export 'make-zone-serial)
392 (defun make-zone-serial (name)
393 "Given a zone NAME, come up with a new serial number.
395 This will (very carefully) update a file ZONE.serial in the current
397 (let* ((file (zone-file-name name :serial))
398 (last (with-open-file (in file
400 :if-does-not-exist nil)
403 (now (multiple-value-bind
404 (sec min hr dy mon yr dow dstp tz)
406 (declare (ignore sec min hr dow dstp tz))
408 (seq (cond ((not (equal now (cdr last))) 0)
409 ((< (car last) 99) (1+ (car last)))
410 (t (error "Run out of sequence numbers for ~A" name)))))
411 (safely-writing (out file)
413 ";; Serial number file for zone ~A~%~
414 ;; (LAST-SEQ DAY MONTH YEAR)~%~
418 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
420 ;;;--------------------------------------------------------------------------
421 ;;; Zone form parsing.
423 (defun zone-process-records (rec ttl func)
424 "Sort out the list of records in REC, calling FUNC for each one.
426 TTL is the default time-to-live for records which don't specify one.
428 REC is a list of records of the form
430 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
432 The various kinds of entries have the following meanings.
434 :ttl TTL Set the TTL for subsequent records (at this level of
437 TYPE DATA Define a record with a particular TYPE and DATA.
438 Record types are defined using `defzoneparse' and
439 the syntax of the data is idiosyncratic.
441 ((LABEL ...) . REC) Define records for labels within the zone. Any
442 records defined within REC will have their domains
443 prefixed by each of the LABELs. A singleton list
444 of labels may instead be written as a single
445 label. Note, therefore, that
447 (host (sub :a \"169.254.1.1\"))
449 defines a record for `host.sub' -- not `sub.host'.
451 If REC contains no top-level records, but it does define records for a
452 label listed in `*preferred-subnets*', then the records for the first such
453 label are also promoted to top-level.
455 The FUNC is called for each record encountered, represented as a
456 `zone-record' object. Zone parsers are not called: you get the record
457 types and data from the input form; see `zone-parse-records' if you want
460 (labels ((sift (rec ttl)
461 ;; Parse the record list REC into lists of `zone-record' and
462 ;; `zone-subdomain' objects, sorting out TTLs and so on.
463 ;; Returns them as two values.
465 (collecting (top sub)
471 (setf ttl (pop rec)))
473 (collect (make-zone-record :type r
478 (dolist (name (listify (car r)))
479 (collect (make-zone-subdomain :name name
484 (error "Unexpected record form ~A" (car r))))))))
486 (process (rec dom ttl)
487 ;; Recursirvely process the record list REC, with a list DOM of
488 ;; prefix labels, and a default TTL. Promote records for a
489 ;; preferred subnet to toplevel if there are no toplevel records
492 (multiple-value-bind (top sub) (sift rec ttl)
493 (if (and dom (null top) sub)
495 (or (find-if (lambda (s)
496 (some #'zone-preferred-subnet-p
497 (listify (zs-name s))))
501 (process (zs-records preferred)
503 (zs-ttl preferred))))
506 (join-strings #\. (reverse dom))))))
508 (setf (zr-name zr) name)
511 (process (zs-records s)
512 (cons (zs-name s) dom)
515 ;; Process the records we're given with no prefix.
516 (process rec nil ttl)))
518 (defun zone-parse-head (head)
519 "Parse the HEAD of a zone form.
523 (NAME &key :source :admin :refresh :retry
524 :expire :min-ttl :ttl :serial)
526 though a singleton NAME needn't be a list. Returns the default TTL and an
527 soa structure representing the zone head."
531 (source *default-zone-source*)
532 (admin (or *default-zone-admin*
533 (format nil "hostmaster@~A" zname)))
534 (refresh *default-zone-refresh*)
535 (retry *default-zone-retry*)
536 (expire *default-zone-expire*)
537 (min-ttl *default-zone-min-ttl*)
539 (serial (make-zone-serial zname)))
541 (values (string-downcase zname)
542 (timespec-seconds ttl)
543 (make-soa :admin admin
544 :source (zone-parse-host source zname)
545 :refresh (timespec-seconds refresh)
546 :retry (timespec-seconds retry)
547 :expire (timespec-seconds expire)
548 :min-ttl (timespec-seconds min-ttl)
551 (export 'defzoneparse)
552 (defmacro defzoneparse (types (name data list
553 &key (prefix (gensym "PREFIX"))
554 (zname (gensym "ZNAME"))
555 (ttl (gensym "TTL")))
557 "Define a new zone record type.
559 The arguments are as follows:
561 TYPES A singleton type symbol, or a list of aliases.
563 NAME The name of the record to be added.
565 DATA The content of the record to be added (a single object,
568 LIST A function to add a record to the zone. See below.
570 PREFIX The prefix tag used in the original form.
572 ZNAME The name of the zone being constructed.
574 TTL The TTL for this record.
576 You get to choose your own names for these. ZNAME, PREFIX and TTL are
577 optional: you don't have to accept them if you're not interested.
579 The LIST argument names a function to be bound in the body to add a new
580 low-level record to the zone. It has the prototype
582 (LIST &key :name :type :data :ttl :make-ptr-p)
584 These (except MAKE-PTR-P, which defaults to nil) default to the above
585 arguments (even if you didn't accept the arguments)."
586 (setf types (listify types))
587 (let* ((type (car types))
588 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
589 (with-parsed-body (body decls doc) body
590 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
593 (setf (get ,i 'zone-parse) ',func))
594 (defun ,func (,prefix ,zname ,data ,ttl ,col)
597 (let ((,name (zone-make-name ,prefix ,zname)))
598 (flet ((,list (&key ((:name ,tname) ,name)
599 ((:type ,ttype) ,type)
600 ((:data ,tdata) ,data)
602 ((:make-ptr-p ,tmakeptrp) nil))
603 #+cmu (declare (optimize ext:inhibit-warnings))
604 (collect (make-zone-record :name ,tname
608 :make-ptr-p ,tmakeptrp)
613 (export 'zone-parse-records)
614 (defun zone-parse-records (zname ttl records)
615 "Parse a sequence of RECORDS and return a list of raw records.
617 The records are parsed relative to the zone name ZNAME, and using the
620 (flet ((parse-record (zr)
621 (let ((func (or (get (zr-type zr) 'zone-parse)
622 (error "No parser for record ~A."
624 (name (and (zr-name zr) (stringify (zr-name zr)))))
625 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
626 (zone-process-records records ttl #'parse-record))))
629 (defun zone-parse (zf)
632 The syntax of a zone form is as follows:
635 ZONE-HEAD ZONE-RECORD*
638 ((NAME*) ZONE-RECORD*)
640 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
641 (make-zone :name zname
644 :records (zone-parse-records zname ttl (cdr zf)))))
646 (export 'zone-create)
647 (defun zone-create (zf)
648 "Zone construction function. Given a zone form ZF, construct the zone and
649 add it to the table."
650 (let* ((zone (zone-parse zf))
651 (name (zone-name zone)))
652 (setf (zone-find name) zone)
656 (defmacro defzone (soa &body zf)
657 "Zone definition macro."
658 `(zone-create '(,soa ,@zf)))
660 (export '*address-family*)
661 (defvar *address-family* t
662 "The default address family. This is bound by `defrevzone'.")
665 (defmacro defrevzone (head &body zf)
666 "Define a reverse zone, with the correct name."
667 (destructuring-bind (nets &rest args
668 &key &allow-other-keys
669 (family '*address-family*)
673 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
674 (let ((*address-family* (ipnet-family ,ipn)))
675 (zone-create `((,(reverse-domain ,ipn ,prefix-bits)
676 ,@',(loop for (k v) on args by #'cddr
678 '(:family :prefix-bits))
682 (export 'map-host-addresses)
683 (defun map-host-addresses (func addr &key (family *address-family*))
684 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
686 (dolist (a (host-addrs (host-parse addr family)))
690 (defmacro do-host ((addr spec &key (family *address-family*)) &body body)
691 "Evaluate BODY, binding ADDR to each address denoted by SPEC."
692 `(dolist (,addr (host-addrs (host-parse ,spec ,family)))
695 (export 'zone-set-address)
696 (defun zone-set-address (rec addrspec &rest args
697 &key (family *address-family*) name ttl make-ptr-p)
698 "Write records (using REC) defining addresses for ADDRSPEC."
699 (declare (ignore name ttl make-ptr-p))
700 (let ((key-args (loop for (k v) on args by #'cddr
701 unless (eq k :family)
703 (do-host (addr addrspec :family family)
704 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
706 ;;;--------------------------------------------------------------------------
707 ;;; Building raw record vectors.
709 (defvar *record-vector* nil
710 "The record vector under construction.")
712 (defun rec-ensure (n)
713 "Ensure that at least N octets are spare in the current record."
714 (let ((want (+ n (fill-pointer *record-vector*)))
715 (have (array-dimension *record-vector* 0)))
716 (unless (<= want have)
717 (adjust-array *record-vector*
718 (do ((new (* 2 have) (* 2 new)))
719 ((<= want new) new))))))
722 (defun rec-byte (octets value)
723 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
725 (do ((i (1- octets) (1- i)))
727 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
730 (defun rec-u8 (value)
731 "Append an 8-bit VALUE to the current record."
735 (defun rec-u16 (value)
736 "Append a 16-bit VALUE to the current record."
740 (defun rec-u32 (value)
741 "Append a 32-bit VALUE to the current record."
744 (export 'rec-raw-string)
745 (defun rec-raw-string (s &key (start 0) end)
746 "Append (a (substring of) a raw string S to the current record.
748 No arrangement is made for reporting the length of the string. That must
749 be done by the caller, if necessary."
750 (setf-default end (length s))
751 (rec-ensure (- end start))
752 (do ((i start (1+ i)))
754 (vector-push (char-code (char s i)) *record-vector*)))
757 (defun rec-string (s &key (start 0) end (max 255))
758 (let* ((end (or end (length s)))
761 (error "String `~A' too long" (subseq s start end)))
762 (rec-u8 (- end start))
763 (rec-raw-string s :start start :end end)))
767 "Append a domain name S.
769 No attempt is made to perform compression of the name."
770 (let ((i 0) (n (length s)))
771 (loop (let* ((dot (position #\. s :start i))
773 (rec-string s :start i :end lim :max 63)
780 (export 'build-record)
781 (defmacro build-record (&body body)
782 "Build a raw record, and return it as a vector of octets."
783 `(let ((*record-vector* (make-array 256
784 :element-type '(unsigned-byte 8)
788 (copy-seq *record-vector*)))
790 (export 'zone-record-rrdata)
791 (defgeneric zone-record-rrdata (type zr)
792 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
794 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
797 ;;;--------------------------------------------------------------------------
798 ;;; Zone record parsers.
800 (defzoneparse :a (name data rec)
802 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
804 (defmethod zone-record-rrdata ((type (eql :a)) zr)
805 (rec-u32 (ipaddr-addr (zr-data zr)))
808 (defzoneparse :aaaa (name data rec)
810 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
812 (defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
813 (rec-byte 16 (ipaddr-addr (zr-data zr)))
816 (defzoneparse :addr (name data rec)
818 (zone-set-address #'rec data :make-ptr-p t))
820 (defzoneparse :svc (name data rec)
822 (zone-set-address #'rec data))
824 (defzoneparse :ptr (name data rec :zname zname)
826 (rec :data (zone-parse-host data zname)))
828 (defmethod zone-record-rrdata ((type (eql :ptr)) zr)
829 (rec-name (zr-data zr))
832 (defzoneparse :cname (name data rec :zname zname)
834 (rec :data (zone-parse-host data zname)))
836 (defmethod zone-record-rrdata ((type (eql :cname)) zr)
837 (rec-name (zr-data zr))
840 (defzoneparse :txt (name data rec)
842 (rec :data (listify data)))
844 (defmethod zone-record-rrdata ((type (eql :txt)) zr)
845 (mapc #'rec-string (zr-data zr))
848 (export '*dkim-pathname-defaults*)
849 (defvar *dkim-pathname-defaults*
850 (make-pathname :directory '(:relative "keys")
853 (defzoneparse :dkim (name data rec)
854 ":dkim (KEYFILE {:TAG VALUE}*)"
855 (destructuring-bind (file &rest plist) (listify data)
856 (let ((things nil) (out nil))
859 (push (get-output-stream-string out) things)
862 (let ((len (length text)))
863 (when (and out (> (+ (file-position out)
869 (unless out (setf out (make-string-output-stream)))
870 (write-string text out))
875 (push (subseq text i (min j len)) things))))))))
876 (do ((p plist (cddr p)))
878 (emit (format nil "~(~A~)=~A;" (car p) (cadr p))))
879 (emit (with-output-to-string (out)
880 (write-string "p=" out)
883 (in (merge-pathnames file *dkim-pathname-defaults*))
885 (when (string= (read-line in)
886 "-----BEGIN PUBLIC KEY-----")
889 (let ((line (read-line in)))
890 (if (string= line "-----END PUBLIC KEY-----")
892 (write-string line out)))))))))
894 :data (nreverse things)))))
896 (eval-when (:load-toplevel :execute)
897 (dolist (item '((sshfp-algorithm rsa 1)
898 (sshfp-algorithm dsa 2)
899 (sshfp-algorithm ecdsa 3)
901 (sshfp-type sha-256 2)))
902 (destructuring-bind (prop sym val) item
903 (setf (get sym prop) val)
906 (export '*sshfp-pathname-defaults*)
907 (defvar *sshfp-pathname-defaults*
908 (make-pathname :directory '(:relative "keys")
911 (defzoneparse :sshfp (name data rec)
912 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
914 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
915 (loop (let ((line (read-line in nil)))
916 (unless line (return))
917 (let ((words (str-split-words line)))
919 (when (string= (car words) "IN") (pop words))
920 (unless (and (string= (car words) "SSHFP")
921 (= (length words) 4))
922 (error "Invalid SSHFP record."))
924 (destructuring-bind (alg type fpr) words
925 (rec :data (list (parse-integer alg)
928 (flet ((lookup (what prop)
931 (symbol (or (get what prop)
932 (error "~S is not a known ~A" what prop))))))
933 (dolist (item (listify data))
934 (destructuring-bind (fpr &key (alg 'rsa) (type 'sha-1))
936 (rec :data (list (lookup alg 'sshfp-algorithm)
937 (lookup type 'sshfp-type)
940 (defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
941 (destructuring-bind (alg type fpr) (zr-data zr)
947 (rec-u8 (parse-integer fpr :start i :end (+ i 2) :radix 16))))
950 (defzoneparse :mx (name data rec :zname zname)
951 ":mx ((HOST :prio INT :ip IPADDR)*)"
952 (dolist (mx (listify data))
954 (mxname &key (prio *default-mx-priority*) ip)
956 (let ((host (zone-parse-host mxname zname)))
957 (when ip (zone-set-address #'rec ip :name host))
958 (rec :data (cons host prio))))))
960 (defmethod zone-record-rrdata ((type (eql :mx)) zr)
961 (let ((name (car (zr-data zr)))
962 (prio (cdr (zr-data zr))))
967 (defzoneparse :ns (name data rec :zname zname)
968 ":ns ((HOST :ip IPADDR)*)"
969 (dolist (ns (listify data))
973 (let ((host (zone-parse-host nsname zname)))
974 (when ip (zone-set-address #'rec ip :name host))
977 (defmethod zone-record-rrdata ((type (eql :ns)) zr)
978 (rec-name (zr-data zr))
981 (defzoneparse :alias (name data rec :zname zname)
983 (dolist (a (listify data))
984 (rec :name (zone-parse-host a zname)
988 (defzoneparse :srv (name data rec :zname zname)
989 ":srv (((SERVICE &key :port) (PROVIDER &key :port :prio :weight :ip)*)*)"
991 (destructuring-bind (servopts &rest providers) srv
993 (service &key ((:port default-port)) (protocol :tcp))
996 (let ((serv (serv-by-name service protocol)))
997 (setf default-port (and serv (serv-port serv)))))
998 (let ((rname (format nil "~(_~A._~A~).~A" service protocol name)))
999 (dolist (prov providers)
1004 (prio *default-mx-priority*)
1008 (let ((host (zone-parse-host srvname zname)))
1009 (when ip (zone-set-address #'rec ip :name host))
1011 :data (list prio weight port host))))))))))
1013 (defmethod zone-record-rrdata ((type (eql :srv)) zr)
1014 (destructuring-bind (prio weight port host) (zr-data zr)
1021 (defzoneparse :net (name data rec)
1023 (dolist (net (listify data))
1024 (dolist (ipn (net-ipnets (net-must-find net)))
1025 (let* ((base (ipnet-net ipn))
1026 (rrtype (ipaddr-rrtype base)))
1027 (flet ((frob (kind addr)
1029 (rec :name (zone-parse-host kind name)
1033 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
1034 (frob "bcast" (ipnet-broadcast ipn)))))))
1036 (defzoneparse (:rev :reverse) (name data rec)
1037 ":reverse ((NET &key :prefix-bits :family) ZONE*)
1039 Add a reverse record each host in the ZONEs (or all zones) that lies
1041 (setf data (listify data))
1042 (destructuring-bind (net &key prefix-bits (family *address-family*))
1043 (listify (car data))
1045 (dolist (ipn (net-parse-to-ipnets net family))
1046 (let* ((seen (make-hash-table :test #'equal))
1047 (width (ipnet-width ipn))
1048 (frag-len (if prefix-bits (- width prefix-bits)
1049 (ipnet-changeable-bits width (ipnet-mask ipn)))))
1050 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
1051 (dolist (zr (zone-records (zone-find z)))
1052 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
1054 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
1055 (let* ((frag (reverse-domain-fragment (zr-data zr)
1057 (name (concatenate 'string frag "." name)))
1058 (unless (gethash name seen)
1059 (rec :name name :type :ptr
1060 :ttl (zr-ttl zr) :data (zr-name zr))
1061 (setf (gethash name seen) t))))))))))
1063 (defzoneparse :multi (name data rec :zname zname :ttl ttl)
1064 ":multi (((NET*) &key :start :end :family :suffix) . REC)
1066 Output multiple records covering a portion of the reverse-resolution
1067 namespace corresponding to the particular NETs. The START and END bounds
1068 default to the most significant variable component of the
1069 reverse-resolution domain.
1071 The REC tail is a sequence of record forms (as handled by
1072 `zone-process-records') to be emitted for each covered address. Within
1073 the bodies of these forms, the symbol `*' will be replaced by the
1074 domain-name fragment corresponding to the current host, optionally
1075 followed by the SUFFIX.
1079 (:multi ((delegated-subnet :start 8)
1080 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
1082 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
1085 Obviously, nested `:multi' records won't work well."
1087 (destructuring-bind (nets &key start end (family *address-family*) suffix)
1088 (listify (car data))
1089 (dolist (net (listify nets))
1090 (dolist (ipn (net-parse-to-ipnets net family))
1091 (let* ((addr (ipnet-net ipn))
1092 (width (ipaddr-width addr))
1093 (comp-width (reverse-domain-component-width addr))
1094 (end (round-up (or end
1095 (ipnet-changeable-bits width
1098 (start (round-down (or start (- end comp-width))
1100 (map (ipnet-host-map ipn)))
1101 (multiple-value-bind (host-step host-limit)
1102 (ipnet-index-bounds map start end)
1103 (do ((index 0 (+ index host-step)))
1104 ((> index host-limit))
1105 (let* ((addr (ipnet-index-host map index))
1106 (frag (reverse-domain-fragment addr start end))
1107 (target (concatenate 'string
1109 (if (not suffix) frag
1110 (concatenate 'string
1114 (dolist (zr (zone-parse-records (zone-make-name frag zname)
1118 (rec :name (zr-name zr)
1122 :make-ptr-p (zr-make-ptr-p zr)))))))))))
1124 ;;;--------------------------------------------------------------------------
1125 ;;; Zone file output.
1127 (export 'zone-write)
1128 (defgeneric zone-write (format zone stream)
1129 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1131 (defvar *writing-zone* nil
1132 "The zone currently being written.")
1134 (defvar *zone-output-stream* nil
1135 "Stream to write zone data on.")
1137 (export 'zone-write-raw-rrdata)
1138 (defgeneric zone-write-raw-rrdata (format zr type data)
1139 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1141 ZR gives the record object, which carries the name and TTL; the TYPE is
1142 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1143 This is used by the default `zone-write-record' method to handle record
1144 types which aren't directly supported by the format driver."))
1146 (export 'zone-write-header)
1147 (defgeneric zone-write-header (format zone)
1148 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1150 The header includes any kind of initial comment, the SOA record, and any
1151 other necessary preamble. There is no default implementation.
1153 This is part of the protocol used by the default method on `zone-write';
1154 if you override that method."))
1156 (export 'zone-write-trailer)
1157 (defgeneric zone-write-trailer (format zone)
1158 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1160 The footer may be empty, and is so by default.
1162 This is part of the protocol used by the default method on `zone-write';
1163 if you override that method.")
1164 (:method (format zone)
1165 (declare (ignore format zone))
1168 (export 'zone-write-record)
1169 (defgeneric zone-write-record (format type zr)
1170 (:documentation "Emit a record of the given TYPE (a keyword).
1172 The default implementation builds the raw RRDATA and passes it to
1173 `zone-write-raw-rrdata'.")
1174 (:method (format type zr)
1176 (data (build-record (setf code (zone-record-rrdata type zr)))))
1177 (zone-write-raw-rrdata format zr code data))))
1179 (defmethod zone-write (format zone stream)
1180 "This default method calls `zone-write-header', then `zone-write-record'
1181 for each record in the zone, and finally `zone-write-trailer'. While it's
1182 running, `*writing-zone*' is bound to the zone object, and
1183 `*zone-output-stream*' to the output stream."
1184 (let ((*writing-zone* zone)
1185 (*zone-output-stream* stream))
1186 (zone-write-header format zone)
1187 (dolist (zr (zone-records-sorted zone))
1188 (zone-write-record format (zr-type zr) zr))
1189 (zone-write-trailer format zone)))
1192 (defun zone-save (zones &key (format :bind))
1193 "Write the named ZONES to files. If no zones are given, write all the
1196 (setf zones (hash-table-keys *zones*)))
1199 (let ((zz (zone-find z)))
1201 (error "Unknown zone `~A'." z))
1202 (let ((stream (safely-open-output-stream safe
1203 (zone-file-name z :zone))))
1204 (zone-write format zz stream))))))
1206 ;;;--------------------------------------------------------------------------
1207 ;;; Bind format output.
1209 (defvar *bind-last-record-name* nil
1210 "The previously emitted record name.
1212 Used for eliding record names on output.")
1214 (export 'bind-hostname)
1215 (defun bind-hostname (hostname)
1216 (let* ((h (string-downcase (stringify hostname)))
1218 (r (string-downcase (zone-name *writing-zone*)))
1220 (cond ((string= r h) "@")
1222 (char= (char h (- hl rl 1)) #\.)
1223 (string= h r :start1 (- hl rl)))
1224 (subseq h 0 (- hl rl 1)))
1225 (t (concatenate 'string h ".")))))
1227 (export 'bind-output-hostname)
1228 (defun bind-output-hostname (hostname)
1229 (let ((name (bind-hostname hostname)))
1230 (cond ((and *bind-last-record-name*
1231 (string= name *bind-last-record-name*))
1234 (setf *bind-last-record-name* name)
1237 (defmethod zone-write :around ((format (eql :bind)) zone stream)
1238 (let ((*bind-last-record-name* nil))
1239 (call-next-method)))
1241 (defmethod zone-write-header ((format (eql :bind)) zone)
1242 (format *zone-output-stream* "~
1243 ;;; Zone file `~(~A~)'
1249 (iso-date :now :datep t :timep t)
1250 (zone-default-ttl zone))
1251 (let* ((soa (zone-soa zone))
1252 (admin (let* ((name (soa-admin soa))
1253 (at (position #\@ name))
1254 (copy (format nil "~(~A~)." name)))
1256 (setf (char copy at) #\.))
1258 (format *zone-output-stream* "~
1259 ~A~30TIN SOA~40T~A (
1260 ~55@A~60T ;administrator
1261 ~45T~10D~60T ;serial
1262 ~45T~10D~60T ;refresh
1264 ~45T~10D~60T ;expire
1265 ~45T~10D )~60T ;min-ttl~2%"
1266 (bind-output-hostname (zone-name zone))
1267 (bind-hostname (soa-source soa))
1273 (soa-min-ttl soa))))
1275 (export 'bind-format-record)
1276 (defun bind-format-record (zr format &rest args)
1277 (format *zone-output-stream*
1278 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
1279 (bind-output-hostname (zr-name zr))
1280 (let ((ttl (zr-ttl zr)))
1281 (and (/= ttl (zone-default-ttl *writing-zone*))
1283 (string-upcase (symbol-name (zr-type zr)))
1286 (defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1287 (format *zone-output-stream*
1288 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A"
1289 (bind-output-hostname (zr-name zr))
1290 (let ((ttl (zr-ttl zr)))
1291 (and (/= ttl (zone-default-ttl *writing-zone*))
1295 (let* ((hex (with-output-to-string (out)
1296 (dotimes (i (length data))
1297 (format out "~(~2,'0X~)" (aref data i)))))
1300 (format *zone-output-stream* " ~A~%" hex))
1302 (format *zone-output-stream* " (")
1305 (when (>= i len) (return))
1306 (let ((j (min (+ i 64) len)))
1307 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1309 (format *zone-output-stream* " )~%")))))
1311 (defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1312 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1314 (defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1315 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1317 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1318 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1320 (defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1321 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1323 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1324 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1326 (defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1327 (bind-format-record zr "~2D ~A"
1329 (bind-hostname (car (zr-data zr)))))
1331 (defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1332 (destructuring-bind (prio weight port host) (zr-data zr)
1333 (bind-format-record zr "~2D ~5D ~5D ~A"
1334 prio weight port (bind-hostname host))))
1336 (defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1337 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1339 (defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1340 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
1342 ;;;--------------------------------------------------------------------------
1343 ;;; tinydns-data output format.
1345 (export 'tinydns-output)
1346 (defun tinydns-output (code &rest fields)
1347 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1349 (defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
1350 (tinydns-output #\: (zr-name zr) type
1351 (with-output-to-string (out)
1352 (dotimes (i (length data))
1353 (let ((byte (aref data i)))
1354 (if (or (<= byte 32)
1356 (member byte '(#\: #\\) :key #'char-code))
1357 (format out "\\~3,'0O" byte)
1358 (write-char (code-char byte) out)))))
1361 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1362 (tinydns-output #\+ (zr-name zr)
1363 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1365 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1366 (tinydns-output #\3 (zr-name zr)
1367 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1370 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1371 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1373 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1374 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1376 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1377 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1379 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1380 (let ((name (car (zr-data zr)))
1381 (prio (cdr (zr-data zr))))
1382 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1384 (defmethod zone-write-header ((format (eql :tinydns)) zone)
1385 (format *zone-output-stream* "~
1386 ### Zone file `~(~A~)'
1390 (iso-date :now :datep t :timep t))
1391 (let ((soa (zone-soa zone)))
1395 (let* ((name (copy-seq (soa-admin soa)))
1396 (at (position #\@ name)))
1397 (when at (setf (char name at) #\.))
1403 (zone-default-ttl zone))))
1405 ;;;----- That's all, folks --------------------------------------------------