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 #:anaphora #:collect #:safely
31 (:import-from #:net #:round-down #:round-up))
35 ;;;--------------------------------------------------------------------------
36 ;;; Various random utilities.
38 (export '*zone-config*)
39 (defparameter *zone-config* nil
40 "A list of configuration variables.
42 This is for the benefit of the frontend, which will dynamically bind them
43 so that input files can override them independently. Not intended for use
47 "Convert X to an integer in the most straightforward way."
50 (defun from-mixed-base (base val)
51 "BASE is a list of the ranges for the `digits' of a mixed-base
52 representation. Convert VAL, a list of digits, into an integer."
53 (do ((base base (cdr base))
54 (val (cdr val) (cdr val))
55 (a (car val) (+ (* a (car base)) (car val))))
56 ((or (null base) (null val)) a)))
58 (defun to-mixed-base (base val)
59 "BASE is a list of the ranges for the `digits' of a mixed-base
60 representation. Convert VAL, an integer, into a list of digits."
61 (let ((base (reverse base))
67 (multiple-value-bind (q r) (floor val (pop base))
71 (let ((unit-scale (make-hash-table)))
73 (dolist (item `(((:second :seconds :sec :secs :s) ,1)
74 ((:minute :minutes :min :mins :m) ,60)
75 ((:hour :hours :hr :hrs :h) ,(* 60 60))
76 ((:day :days :dy :dys :d) ,(* 24 60 60))
77 ((:week :weeks :wk :wks :w) ,(* 7 24 60 60))))
78 (destructuring-bind (units scale) item
79 (dolist (unit units) (setf (gethash unit unit-scale) scale))))
81 (export 'timespec-seconds)
82 (defun timespec-seconds (ts)
83 "Convert a timespec TS to seconds.
85 A timespec may be a real count of seconds, or a list ({COUNT UNIT}*).
86 UNIT may be any of a number of obvious time units."
87 (labels ((convert (acc ts)
89 ((realp ts) (+ acc (floor ts)))
90 ((atom ts) (error "Unknown timespec format ~A" ts))
93 (count &optional unit &rest tail) ts
95 (acond ((null unit) 1)
96 ((gethash (intern (string-upcase
102 (error "Unknown time unit ~S"
104 (convert (+ acc (to-integer (* count scale)))
108 (defun hash-table-keys (ht)
109 "Return a list of the keys in hashtable HT."
111 (maphash (lambda (key val) (declare (ignore val)) (collect key)) ht)))
113 (defun iso-date (&optional time &key datep timep (sep #\ ))
114 "Construct a textual date or time in ISO format.
116 The TIME is the universal time to convert, which defaults to now; DATEP is
117 whether to emit the date; TIMEP is whether to emit the time, and
118 SEP (default is space) is how to separate the two."
120 (sec min hr day mon yr dow dstp tz)
121 (decode-universal-time (if (or (null time) (eq time :now))
124 (declare (ignore dow dstp tz))
125 (with-output-to-string (s)
127 (format s "~4,'0D-~2,'0D-~2,'0D" yr mon day)
131 (format s "~2,'0D:~2,'0D:~2,'0D" hr min sec)))))
133 (deftype octet () '(unsigned-byte 8))
134 (deftype octet-vector (&optional n) `(array octet (,n)))
136 (defun decode-hex (hex &key (start 0) end)
137 "Decode a hexadecimal-encoded string, returning a vector of octets."
138 (let* ((end (or end (length hex)))
140 (raw (make-array (floor len 2) :element-type 'octet)))
142 (error "Invalid hex string `~A' (odd length)" hex))
143 (do ((i start (+ i 2)))
145 (let ((high (digit-char-p (char hex i) 16))
146 (low (digit-char-p (char hex (1+ i)) 16)))
147 (unless (and high low)
148 (error "Invalid hex string `~A' (bad digit)" hex))
149 (setf (aref raw (/ (- i start) 2)) (+ (* 16 high) low))))))
151 (defun slurp-file (file &optional (element-type 'character))
152 "Read and return the contents of FILE as a vector."
153 (with-open-file (in file :element-type element-type)
154 (let ((buf (make-array 1024 :element-type element-type))
157 (let ((end (read-sequence buf in :start pos)))
158 (when (< end (length buf))
159 (return (adjust-array buf end)))
161 buf (adjust-array buf (* 2 pos))))))))
163 (defmacro defenum (name (&key export) &body values)
164 "Set up symbol properties for manifest constants.
166 The VALUES are a list of (TAG VALUE) pairs. Each TAG is a symbol; we set
167 the NAME property on TAG to VALUE, and export TAG. There are also handy
168 hash-tables mapping in the forward and reverse directions, in the name
169 symbol's `enum-forward' and `enum-reverse' properties."
170 `(eval-when (:compile-toplevel :load-toplevel :execute)
171 ,(let*/gensyms (export)
172 (with-gensyms (forward reverse valtmp)
173 `(let ((,forward (make-hash-table))
174 (,reverse (make-hash-table)))
175 (when ,export (export ',name))
176 ,@(mapcar (lambda (item)
177 (destructuring-bind (tag value) item
179 (intern (concatenate 'string
182 (symbol-name tag)))))
183 `(let ((,valtmp ,value))
186 (when (eq (symbol-package ',tag) *package*)
188 (defconstant ,constant ,valtmp)
189 (setf (get ',tag ',name) ,value
190 (gethash ',tag ,forward) ,valtmp
191 (gethash ,valtmp ,reverse) ',tag)))))
193 (setf (get ',name 'enum-forward) ,forward
194 (get ',name 'enum-reverse) ,reverse))))))
196 (defun lookup-enum (name tag &key min max)
197 "Look up a TAG in an enumeration.
199 If TAG is a symbol, check its NAME property; if it's a fixnum then take it
200 as it is. Make sure that it's between MIN and MAX, if they're not nil."
201 (let ((value (etypecase tag
203 (symbol (or (get tag name)
204 (error "~S is not a known ~A" tag name))))))
205 (unless (and (or (null min) (<= min value))
206 (or (null max) (<= value max)))
207 (error "Value ~S out of range for ~A" value name))
210 (defun reverse-enum (name value)
211 "Reverse-lookup of a VALUE in enumeration NAME.
213 If a tag for the VALUE is found, return it and `t'; otherwise return VALUE
214 unchanged and `nil'."
215 (multiple-value-bind (tag foundp) (gethash value (get name 'enum-reverse))
218 (values value nil))))
220 (defun mapenum (func name)
221 "Call FUNC on TAG/VALUE pairs from the enumeration called NAME."
222 (maphash func (get name 'enum-forward)))
224 (defun hash-file (hash file context)
225 "Hash the FILE using the OpenSSL HASH function, returning an octet string.
227 CONTEXT is a temporary-files context."
228 (let ((temp (temporary-file context "hash")))
229 (run-program (list "openssl" "dgst" (concatenate 'string "-" hash))
230 :input file :output temp)
231 (with-open-file (in temp)
232 (let ((line (read-line in)))
233 (assert (and (>= (length line) 9)
234 (string= line "(stdin)= " :end1 9)))
235 (decode-hex line :start 9)))))
237 ;;;--------------------------------------------------------------------------
241 (defstruct (soa (:predicate soap))
242 "Start-of-authority record information."
252 (defstruct (mx (:predicate mxp))
253 "Mail-exchange record information."
258 (defstruct (zone (:predicate zonep))
265 (export 'zone-text-name)
266 (defun zone-text-name (zone)
267 (princ-to-string (zone-name zone)))
269 ;;;--------------------------------------------------------------------------
270 ;;; Zone defaults. It is intended that scripts override these.
272 (export '*default-zone-source*)
273 (defvar *default-zone-source*
274 (let ((hn (gethostname)))
275 (and hn (concatenate 'string (canonify-hostname hn) ".")))
276 "The default zone source: the current host's name.")
278 (export '*default-zone-refresh*)
279 (defvar *default-zone-refresh* (* 8 60 60)
280 "Default zone refresh interval: eight hours.")
282 (export '*default-zone-admin*)
283 (defvar *default-zone-admin* nil
284 "Default zone administrator's email address.")
286 (export '*default-zone-retry*)
287 (defvar *default-zone-retry* (* 20 60)
288 "Default zone retry interval: twenty minutes.")
290 (export '*default-zone-expire*)
291 (defvar *default-zone-expire* (* 3 24 60 60)
292 "Default zone expiry time: three days.")
294 (export '*default-zone-min-ttl*)
295 (defvar *default-zone-min-ttl* (* 4 60 60)
296 "Default zone minimum/negative TTL: four hours.")
298 (export '*default-zone-ttl*)
299 (defvar *default-zone-ttl* (* 4 60 60)
300 "Default zone TTL (for records without explicit TTLs): four hours.")
302 (export '*default-mx-priority*)
303 (defvar *default-mx-priority* 50
304 "Default MX priority.")
306 ;;;--------------------------------------------------------------------------
307 ;;; Zone variables and structures.
309 (defvar *zones* (make-hash-table :test #'equal)
310 "Map of known zones.")
313 (defun zone-find (name)
314 "Find a zone given its NAME."
315 (gethash (string-downcase (stringify name)) *zones*))
316 (defun (setf zone-find) (zone name)
317 "Make the zone NAME map to ZONE."
318 (setf (gethash (string-downcase (stringify name)) *zones*) zone))
320 (export 'zone-record)
321 (defstruct (zone-record (:conc-name zr-))
329 (export 'zone-subdomain)
330 (defstruct (zone-subdomain (:conc-name zs-))
333 Slightly weird. Used internally by `zone-process-records', and shouldn't
339 (export '*zone-output-path*)
340 (defvar *zone-output-path* nil
341 "Pathname defaults to merge into output files.
343 If this is nil then use the prevailing `*default-pathname-defaults*'.
344 This is not the same as capturing the `*default-pathname-defaults*' from
347 (export '*preferred-subnets*)
348 (defvar *preferred-subnets* nil
349 "Subnets to prefer when selecting defaults.")
351 ;;;--------------------------------------------------------------------------
352 ;;; Zone infrastructure.
354 (defun zone-file-name (zone type)
355 "Choose a file name for a given ZONE and TYPE."
356 (merge-pathnames (make-pathname :name (string-downcase zone)
357 :type (string-downcase type))
358 (or *zone-output-path* *default-pathname-defaults*)))
360 (export 'zone-preferred-subnet-p)
361 (defun zone-preferred-subnet-p (name)
362 "Answer whether NAME (a string or symbol) names a preferred subnet."
363 (member name *preferred-subnets* :test #'string-equal))
365 (export 'preferred-subnet-case)
366 (defmacro preferred-subnet-case (&body clauses)
367 "Execute a form based on which networks are considered preferred.
369 The CLAUSES have the form (SUBNETS . FORMS) -- evaluate the first FORMS
370 whose SUBNETS (a list or single symbol, not evaluated) are listed in
371 `*preferred-subnets*'. If SUBNETS is the symbol `t' then the clause
374 ,@(mapcar (lambda (clause)
375 (let ((subnets (car clause)))
376 (cons (cond ((eq subnets t)
379 `(or ,@(mapcar (lambda (subnet)
380 `(zone-preferred-subnet-p
384 `(zone-preferred-subnet-p ',subnets)))
388 (export 'zone-parse-host)
389 (defun zone-parse-host (form &optional tail)
390 "Parse a host name FORM from a value in a zone form.
392 The underlying parsing is done using `parse-domain-name'. Here, we
393 interpret various kinds of Lisp object specially. In particular: `nil'
394 refers to the TAIL zone (just like a plain `@'); and a symbol is downcased
396 (let ((name (etypecase form
397 (null (make-domain-name :labels nil :absolutep nil))
399 (symbol (parse-domain-name (string-downcase form)))
400 (string (parse-domain-name form)))))
402 (domain-name-concat name tail))))
404 (export 'zone-records-sorted)
405 (defun zone-records-sorted (zone)
406 "Return the ZONE's records, in a pleasant sorted order."
407 (sort (copy-seq (zone-records zone))
409 (multiple-value-bind (precp follp)
410 (domain-name< (zr-name zr-a) (zr-name zr-b))
413 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
415 ;;;--------------------------------------------------------------------------
416 ;;; Serial numbering.
418 (export 'make-zone-serial)
419 (defun make-zone-serial (name)
420 "Given a zone NAME, come up with a new serial number.
422 This will (very carefully) update a file ZONE.serial in the current
424 (let* ((file (zone-file-name name :serial))
425 (last (with-open-file (in file
427 :if-does-not-exist nil)
430 (now (multiple-value-bind
431 (sec min hr dy mon yr dow dstp tz)
433 (declare (ignore sec min hr dow dstp tz))
435 (seq (cond ((not (equal now (cdr last))) 0)
436 ((< (car last) 99) (1+ (car last)))
437 (t (error "Run out of sequence numbers for ~A" name)))))
438 (safely-writing (out file)
440 ";; Serial number file for zone ~A~%~
441 ;; (LAST-SEQ DAY MONTH YEAR)~%~
445 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
447 ;;;--------------------------------------------------------------------------
448 ;;; Zone form parsing.
450 (defun zone-process-records (rec ttl func)
451 "Sort out the list of records in REC, calling FUNC for each one.
453 TTL is the default time-to-live for records which don't specify one.
455 REC is a list of records of the form
457 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
459 The various kinds of entries have the following meanings.
461 :ttl TTL Set the TTL for subsequent records (at this level of
464 TYPE DATA Define a record with a particular TYPE and DATA.
465 Record types are defined using `defzoneparse' and
466 the syntax of the data is idiosyncratic.
468 ((LABEL ...) . REC) Define records for labels within the zone. Any
469 records defined within REC will have their domains
470 prefixed by each of the LABELs. A singleton list
471 of labels may instead be written as a single
472 label. Note, therefore, that
474 (host (sub :a \"169.254.1.1\"))
476 defines a record for `host.sub' -- not `sub.host'.
478 If REC contains no top-level records, but it does define records for a
479 label listed in `*preferred-subnets*', then the records for the first such
480 label are also promoted to top-level.
482 The FUNC is called for each record encountered, represented as a
483 `zone-record' object. Zone parsers are not called: you get the record
484 types and data from the input form; see `zone-parse-records' if you want
487 (labels ((sift (rec ttl)
488 ;; Parse the record list REC into lists of `zone-record' and
489 ;; `zone-subdomain' objects, sorting out TTLs and so on.
490 ;; Returns them as two values.
492 (collecting (top sub)
498 (setf ttl (pop rec)))
500 (collect (make-zone-record :type r
505 (dolist (name (listify (car r)))
506 (collect (make-zone-subdomain
507 :name (zone-parse-host name)
508 :ttl ttl :records (cdr r))
511 (error "Unexpected record form ~A" r)))))))
513 (process (rec dom ttl)
514 ;; Recursirvely process the record list REC, with a list DOM of
515 ;; prefix labels, and a default TTL. Promote records for a
516 ;; preferred subnet to toplevel if there are no toplevel records
519 (multiple-value-bind (top sub) (sift rec ttl)
520 (if (and dom (null top) sub)
524 (let ((ll (domain-name-labels (zs-name s))))
525 (and (consp ll) (null (cdr ll))
526 (zone-preferred-subnet-p (car ll)))))
530 (process (zs-records preferred)
532 (zs-ttl preferred))))
535 (setf (zr-name zr) name)
538 (process (zs-records s)
539 (if (null dom) (zs-name s)
540 (domain-name-concat dom (zs-name s)))
543 ;; Process the records we're given with no prefix.
544 (process rec nil ttl)))
546 (defun zone-parse-head (head)
547 "Parse the HEAD of a zone form.
551 (NAME &key :source :admin :refresh :retry
552 :expire :min-ttl :ttl :serial)
554 though a singleton NAME needn't be a list. Returns the default TTL and an
555 soa structure representing the zone head."
559 (source *default-zone-source*)
560 (admin (or *default-zone-admin*
561 (format nil "hostmaster@~A" raw-zname)))
562 (refresh *default-zone-refresh*)
563 (retry *default-zone-retry*)
564 (expire *default-zone-expire*)
565 (min-ttl *default-zone-min-ttl*)
566 (ttl *default-zone-ttl*)
567 (serial (make-zone-serial raw-zname))
569 (zname (zone-parse-host raw-zname root-domain)))
572 (timespec-seconds ttl)
573 (make-soa :admin admin
574 :source (zone-parse-host source zname)
575 :refresh (timespec-seconds refresh)
576 :retry (timespec-seconds retry)
577 :expire (timespec-seconds expire)
578 :min-ttl (timespec-seconds min-ttl)
581 (export 'defzoneparse)
582 (defmacro defzoneparse (types (name data list
583 &key (prefix (gensym "PREFIX"))
584 (zname (gensym "ZNAME"))
585 (ttl (gensym "TTL")))
587 "Define a new zone record type.
589 The arguments are as follows:
591 TYPES A singleton type symbol, or a list of aliases.
593 NAME The name of the record to be added.
595 DATA The content of the record to be added (a single object,
598 LIST A function to add a record to the zone. See below.
600 PREFIX The prefix tag used in the original form.
602 ZNAME The name of the zone being constructed.
604 TTL The TTL for this record.
606 You get to choose your own names for these. ZNAME, PREFIX and TTL are
607 optional: you don't have to accept them if you're not interested.
609 The LIST argument names a function to be bound in the body to add a new
610 low-level record to the zone. It has the prototype
612 (LIST &key :name :type :data :ttl :make-ptr-p)
614 These (except MAKE-PTR-P, which defaults to nil) default to the above
615 arguments (even if you didn't accept the arguments)."
617 (setf types (listify types))
618 (let* ((type (car types))
619 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
620 (with-parsed-body (body decls doc) body
621 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
624 (setf (get ,i 'zone-parse) ',func))
625 (defun ,func (,prefix ,zname ,data ,ttl ,col)
628 (let ((,name (if (null ,prefix) ,zname
629 (domain-name-concat ,prefix ,zname))))
630 (flet ((,list (&key ((:name ,tname) ,name)
631 ((:type ,ttype) ,type)
632 ((:data ,tdata) ,data)
634 ((:make-ptr-p ,tmakeptrp) nil))
635 #+cmu (declare (optimize ext:inhibit-warnings))
636 (collect (make-zone-record :name ,tname
640 :make-ptr-p ,tmakeptrp)
645 (export 'zone-parse-records)
646 (defun zone-parse-records (zname ttl records)
647 "Parse a sequence of RECORDS and return a list of raw records.
649 The records are parsed relative to the zone name ZNAME, and using the
652 (flet ((parse-record (zr)
653 (let ((func (or (get (zr-type zr) 'zone-parse)
654 (error "No parser for record ~A."
656 (name (and (zr-name zr) (zr-name zr))))
657 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
658 (zone-process-records records ttl #'parse-record))))
661 (defun zone-parse (zf)
664 The syntax of a zone form is as follows:
667 ZONE-HEAD ZONE-RECORD*
670 ((NAME*) ZONE-RECORD*)
672 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
673 (make-zone :name zname
676 :records (zone-parse-records zname ttl (cdr zf)))))
678 (export 'zone-create)
679 (defun zone-create (zf)
680 "Zone construction function.
682 Given a zone form ZF, construct the zone and add it to the table."
683 (let* ((zone (zone-parse zf))
684 (name (zone-text-name zone)))
685 (setf (zone-find name) zone)
689 (defmacro defzone (soa &body zf)
690 "Zone definition macro."
691 `(zone-create '(,soa ,@zf)))
693 (export '*address-family*)
694 (defvar *address-family* t
695 "The default address family. This is bound by `defrevzone'.")
698 (defmacro defrevzone (head &body zf)
699 "Define a reverse zone, with the correct name."
700 (destructuring-bind (nets &rest args
701 &key (family '*address-family*)
706 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
707 (let ((*address-family* (ipnet-family ,ipn)))
708 (zone-create `((,(format nil "~A" (reverse-domain ,ipn
710 ,@',(loop for (k v) on args by #'cddr
712 '(:family :prefix-bits))
716 (export 'map-host-addresses)
717 (defun map-host-addresses (func addr &key (family *address-family*))
718 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
720 (dolist (a (host-addrs (host-parse addr family)))
724 (defmacro do-host ((addr spec &key (family *address-family*)) &body body)
725 "Evaluate BODY, binding ADDR to each address denoted by SPEC."
726 `(dolist (,addr (host-addrs (host-parse ,spec ,family)))
729 (export 'zone-set-address)
730 (defun zone-set-address (rec addrspec &rest args
731 &key (family *address-family*) name ttl make-ptr-p)
732 "Write records (using REC) defining addresses for ADDRSPEC."
733 (declare (ignore name ttl make-ptr-p))
734 (let ((key-args (loop for (k v) on args by #'cddr
735 unless (eq k :family)
737 (do-host (addr addrspec :family family)
738 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
740 ;;;--------------------------------------------------------------------------
741 ;;; Building raw record vectors.
743 (defvar *record-vector* nil
744 "The record vector under construction.")
746 (defun rec-ensure (n)
747 "Ensure that at least N octets are spare in the current record."
748 (let ((want (+ n (fill-pointer *record-vector*)))
749 (have (array-dimension *record-vector* 0)))
750 (unless (<= want have)
751 (adjust-array *record-vector*
752 (do ((new (* 2 have) (* 2 new)))
753 ((<= want new) new))))))
755 (export 'rec-octet-vector)
756 (defun rec-octet-vector (vector &key (start 0) end)
757 "Copy (part of) the VECTOR to the output."
758 (let* ((end (or end (length vector)))
761 (do ((i start (1+ i)))
763 (vector-push (aref vector i) *record-vector*))))
766 (defun rec-byte (octets value)
767 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
769 (do ((i (1- octets) (1- i)))
771 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
774 (defun rec-u8 (value)
775 "Append an 8-bit VALUE to the current record."
779 (defun rec-u16 (value)
780 "Append a 16-bit VALUE to the current record."
784 (defun rec-u32 (value)
785 "Append a 32-bit VALUE to the current record."
788 (export 'rec-raw-string)
789 (defun rec-raw-string (s &key (start 0) end)
790 "Append (a substring of) a raw string S to the current record.
792 No arrangement is made for reporting the length of the string. That must
793 be done by the caller, if necessary."
794 (setf-default end (length s))
795 (rec-ensure (- end start))
796 (do ((i start (1+ i)))
798 (vector-push (char-code (char s i)) *record-vector*)))
801 (defun rec-string (s &key (start 0) end (max 255))
802 (let* ((end (or end (length s)))
805 (error "String `~A' too long" (subseq s start end)))
806 (rec-u8 (- end start))
807 (rec-raw-string s :start start :end end)))
810 (defun rec-name (name)
811 "Append a domain NAME.
813 No attempt is made to perform compression of the name."
814 (dolist (label (reverse (domain-name-labels name)))
815 (rec-string label :max 63))
818 (export 'build-record)
819 (defmacro build-record (&body body)
820 "Build a raw record, and return it as a vector of octets."
821 `(let ((*record-vector* (make-array 256
822 :element-type '(unsigned-byte 8)
826 (copy-seq *record-vector*)))
828 (export 'zone-record-rrdata)
829 (defgeneric zone-record-rrdata (type zr)
830 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
832 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
835 ;;;--------------------------------------------------------------------------
836 ;;; Zone record parsers.
838 (defzoneparse :a (name data rec)
840 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
842 (defmethod zone-record-rrdata ((type (eql :a)) zr)
843 (rec-u32 (ipaddr-addr (zr-data zr)))
846 (defzoneparse :aaaa (name data rec)
848 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
850 (defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
851 (rec-byte 16 (ipaddr-addr (zr-data zr)))
854 (defzoneparse :addr (name data rec)
856 (zone-set-address #'rec data :make-ptr-p t))
858 (defzoneparse :svc (name data rec)
860 (zone-set-address #'rec data))
862 (defzoneparse :ptr (name data rec :zname zname)
864 (rec :data (zone-parse-host data zname)))
866 (defmethod zone-record-rrdata ((type (eql :ptr)) zr)
867 (rec-name (zr-data zr))
870 (defzoneparse :cname (name data rec :zname zname)
872 (rec :data (zone-parse-host data zname)))
874 (defzoneparse :dname (name data rec :zname zname)
876 (rec :data (zone-parse-host data zname)))
878 (defmethod zone-record-rrdata ((type (eql :cname)) zr)
879 (rec-name (zr-data zr))
882 (defun split-txt-data (data)
883 "Split the string DATA into pieces small enough to fit in a TXT record.
885 Return a list of strings L such that (a) (apply #'concatenate 'string L)
886 is equal to the original string DATA, and (b) (every (lambda (s) (<=
887 (length s) 255)) L) is true."
889 (let ((i 0) (n (length data)))
891 (let ((end (+ i 255)))
892 (when (<= n end) (return))
893 (let ((split (acond ((position #\; data :from-end t
896 ((position #\space data :from-end t
901 (when (or (>= split end)
902 (char/= (char data split) #\space))
905 (collect (subseq data i split))
907 (collect (subseq data i)))))
909 (defzoneparse :txt (name data rec)
911 (rec :data (cond ((stringp data) (split-txt-data data))
914 (unless (<= (length piece) 255)
915 (error "`:txt' record piece `~A' too long" piece)))
918 (defmethod zone-record-rrdata ((type (eql :txt)) zr)
919 (mapc #'rec-string (zr-data zr))
922 (defzoneparse :spf (name data rec :zname zname)
923 ":spf ([[ (:version STRING) |
924 ({:pass | :fail | :soft | :shrug}
927 :a [[ :label LABEL | :v4mask MASK | :v6mask MASK ]] |
929 {:ip | :ip4 | :ip6} {STRING | NET | HOST}}) |
935 (with-output-to-string (out)
938 (if firstp (setf firstp nil)
939 (write-char #\space out))
940 (let ((head (car item))
943 (:version (destructuring-bind (ver) tail
944 (format out "v=~A" ver)))
945 ((:pass :fail :soft :shrug)
946 (let ((qual (ecase head
951 (setf head (pop tail))
954 (destructuring-bind () tail
955 (format out "~Aall" qual)))
957 (destructuring-bind (label) tail
958 (format out "~A~(~A~):~A"
960 (if (stringp label) label
961 (zone-parse-host label zname)))))
963 (destructuring-bind (&key label v4mask v6mask) tail
964 (format out "~A~(~A~)~@[:~A~]~@[/~D~]~@[//~D~]"
966 (cond ((null label) nil)
967 ((stringp label) label)
968 (t (zone-parse-host label zname)))
972 (destructuring-bind (&optional label) tail
973 (format out "~Aptr~@[:~A~]"
975 (cond ((null label) nil)
976 ((stringp label) label)
977 (t (zone-parse-host label zname))))))
979 (let* ((family (ecase head
989 (dolist (addr (host-addrs it))
990 (when (or (eq family t)
992 (ipaddr-family addr)))
996 (ipaddr-width addr)))))
999 "No matching addresses for `~A'"
1003 (net-parse-to-ipnets net family))))))))
1006 (if firstp (setf firstp nil)
1007 (write-char #\space out))
1008 (let* ((width (ipnet-width net))
1009 (mask (ipnet-mask net))
1010 (plen (ipmask-cidl-slash width mask)))
1012 (error "invalid netmask in network ~A" net))
1013 (format out "~A~A:~A~@[/~D~]"
1015 (ecase (ipnet-family net)
1019 (and (/= plen width) plen)))))))))
1021 (destructuring-bind (label) tail
1022 (format out "~(~A~)=~A"
1024 (if (stringp label) label
1025 (zone-parse-host label zname)))))))))))))
1028 (export '*dkim-pathname-defaults*)
1029 (defvar *dkim-pathname-defaults*
1030 (make-pathname :directory '(:relative "keys")
1032 (pushnew '*dkim-pathname-defaults* *zone-config*)
1034 (defzoneparse :dkim (name data rec)
1035 ":dkim (KEYFILE {:TAG VALUE}*)"
1036 (destructuring-bind (file &rest plist) (listify data)
1040 (with-output-to-string (out)
1041 (format out "~{~(~A~)=~A; ~}" plist)
1042 (write-string "p=" out)
1045 (in (merge-pathnames file *dkim-pathname-defaults*))
1047 (when (string= (read-line in)
1048 "-----BEGIN PUBLIC KEY-----")
1051 (let ((line (read-line in)))
1052 (when (string= line "-----END PUBLIC KEY-----")
1054 (write-string line out))))))))))
1056 (defzoneparse :dmarc (name data rec)
1057 ":dmarc ({:TAG VALUE}*)"
1059 :data (split-txt-data (format nil "~{~(~A~)=~A~^; ~}" data))))
1061 (defenum sshfp-algorithm () (:rsa 1) (:dsa 2) (:ecdsa 3) (:ed25519 4))
1062 (defenum sshfp-type () (:sha-1 1) (:sha-256 2))
1064 (export '*sshfp-pathname-defaults*)
1065 (defvar *sshfp-pathname-defaults*
1066 (make-pathname :directory '(:relative "keys") :type "sshfp")
1067 "Default pathname components for SSHFP records.")
1068 (pushnew '*sshfp-pathname-defaults* *zone-config*)
1070 (defzoneparse :sshfp (name data rec)
1071 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
1073 ((or string pathname)
1074 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
1075 (loop (let ((line (read-line in nil)))
1076 (unless line (return))
1077 (let ((words (str-split-words line)))
1079 (when (string= (car words) "IN") (pop words))
1080 (unless (and (string= (car words) "SSHFP")
1081 (= (length words) 4))
1082 (error "Invalid SSHFP record."))
1084 (destructuring-bind (alg type fprhex) words
1085 (rec :data (list (parse-integer alg)
1086 (parse-integer type)
1087 (decode-hex fprhex)))))))))
1089 (dolist (item (listify data))
1090 (destructuring-bind (fprhex &key (alg 'rsa) (type 'sha-1))
1092 (rec :data (list (lookup-enum alg 'sshfp-algorithm :min 0 :max 255)
1093 (lookup-enum type 'sshfp-type :min 0 :max 255)
1094 (decode-hex fprhex))))))))
1096 (defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
1097 (destructuring-bind (alg type fpr) (zr-data zr)
1100 (rec-octet-vector fpr))
1103 (defenum tlsa-usage ()
1105 (:service-certificate-constraint 1)
1106 (:trust-anchor-assertion 2)
1107 (:domain-issued-certificate 3))
1109 (defenum tlsa-selector ()
1113 (defenum tlsa-match ()
1118 (defparameter tlsa-pem-alist
1119 `(("CERTIFICATE" . ,tlsa-selector/certificate)
1120 ("PUBLIC-KEY" . ,tlsa-selector/public-key)))
1122 (defgeneric raw-tlsa-assoc-data (have want file context)
1124 "Convert FILE, and strip off PEM encoding.
1126 The FILE contains PEM-encoded data of type HAVE -- one of the
1127 `tlsa-selector' codes. Return the name of a file containing binary
1128 DER-encoded data of type WANT instead. The CONTEXT is a temporary-files
1131 (:method (have want file context)
1132 (declare (ignore context))
1133 (error "Can't convert `~A' from selector type ~S to type ~S" file
1134 (reverse-enum 'tlsa-selector have)
1135 (reverse-enum 'tlsa-selector want)))
1137 (:method ((have (eql tlsa-selector/certificate))
1138 (want (eql tlsa-selector/certificate))
1140 (let ((temp (temporary-file context "cert")))
1141 (run-program (list "openssl" "x509" "-outform" "der")
1142 :input file :output temp)
1145 (:method ((have (eql tlsa-selector/public-key))
1146 (want (eql tlsa-selector/public-key))
1148 (let ((temp (temporary-file context "pubkey-der")))
1149 (run-program (list "openssl" "pkey" "-pubin" "-outform" "der")
1150 :input file :output temp)
1153 (:method ((have (eql tlsa-selector/certificate))
1154 (want (eql tlsa-selector/public-key))
1156 (let ((temp (temporary-file context "pubkey")))
1157 (run-program (list "openssl" "x509" "-noout" "-pubkey")
1158 :input file :output temp)
1159 (raw-tlsa-assoc-data want want temp context))))
1161 (defgeneric tlsa-match-data-valid-p (match data)
1163 "Check whether the DATA (an octet vector) is valid for the MATCH type.")
1165 (:method (match data)
1166 (declare (ignore match data))
1167 ;; We don't know: assume the user knows what they're doing.
1170 (:method ((match (eql tlsa-match/sha-256)) data) (= (length data) 32))
1171 (:method ((match (eql tlsa-match/sha-512)) data) (= (length data) 64)))
1173 (defgeneric read-tlsa-match-data (match file context)
1175 "Read FILE, and return an octet vector for the correct MATCH type.
1177 CONTEXT is a temporary-files context.")
1178 (:method ((match (eql tlsa-match/exact)) file context)
1179 (declare (ignore context))
1180 (slurp-file file 'octet))
1181 (:method ((match (eql tlsa-match/sha-256)) file context)
1182 (hash-file "sha256" file context))
1183 (:method ((match (eql tlsa-match/sha-512)) file context)
1184 (hash-file "sha512" file context)))
1186 (defgeneric tlsa-selector-pem-boundary (selector)
1188 "Return the PEM boundary string for objects of the SELECTOR type")
1189 (:method ((selector (eql tlsa-selector/certificate))) "CERTIFICATE")
1190 (:method ((selector (eql tlsa-selector/public-key))) "PUBLIC KEY")
1191 (:method (selector) (declare (ignore selector)) nil))
1193 (defun identify-tlsa-selector-file (file)
1194 "Return the selector type for the data stored in a PEM-format FILE."
1195 (with-open-file (in file)
1197 (let* ((line (read-line in nil))
1198 (len (length line)))
1200 (error "No PEM boundary in `~A'" file))
1201 (when (and (>= len 11)
1202 (string= line "-----BEGIN " :end1 11)
1203 (string= line "-----" :start1 (- len 5)))
1204 (mapenum (lambda (tag value)
1205 (declare (ignore tag))
1207 (tlsa-selector-pem-boundary value)
1208 :start1 11 :end1 (- len 5))
1210 'tlsa-selector))))))
1212 (export '*tlsa-pathname-defaults*)
1213 (defvar *tlsa-pathname-defaults*
1214 (list (make-pathname :directory '(:relative "certs") :type "cert")
1215 (make-pathname :directory '(:relative "keys") :type "pub"))
1216 "Default pathname components for TLSA records.")
1217 (pushnew '*tlsa-pathname-defaults* *zone-config*)
1219 (defparameter *tlsa-data-cache* (make-hash-table :test #'equal)
1220 "Cache for TLSA association data; keys are (DATA SELECTOR MATCH).")
1222 (defun convert-tlsa-selector-data (data selector match)
1223 "Convert certificate association DATA as required by SELECTOR and MATCH.
1225 If DATA is a hex string, we assume that it's already in the appropriate
1226 form (but if MATCH specifies a hash then we check that it's the right
1227 length). If DATA is a pathname, then it should name a PEM file: we
1228 identify the kind of object stored in the file from the PEM header, and
1229 convert as necessary.
1231 The output is an octet vector containing the raw certificate association
1232 data to include in rrdata."
1236 (let ((bin (decode-hex data)))
1237 (unless (tlsa-match-data-valid-p match bin)
1238 (error "Invalid data for match type ~S"
1239 (reverse-enum 'tlsa-match match)))
1242 (let ((key (list data selector match)))
1243 (or (gethash key *tlsa-data-cache*)
1244 (with-temporary-files (context :base (make-pathname :type "tmp"))
1245 (let* ((file (or (find-if #'probe-file
1246 (mapcar (lambda (template)
1247 (merge-pathnames data
1249 *tlsa-pathname-defaults*))
1250 (error "Couldn't find TLSA file `~A'" data)))
1251 (kind (identify-tlsa-selector-file file))
1252 (raw (raw-tlsa-assoc-data kind selector file context))
1253 (binary (read-tlsa-match-data match raw context)))
1254 (setf (gethash key *tlsa-data-cache*) binary))))))))
1256 (defzoneparse :tlsa (name data rec)
1257 ":tlsa (((SERVICE|PORT &key :protocol)*) (USAGE SELECTOR MATCH DATA)*)"
1259 (destructuring-bind (services &rest certinfos) data
1261 ;; First pass: build the raw-format TLSA record data.
1262 (let ((records nil))
1263 (dolist (certinfo certinfos)
1264 (destructuring-bind (usage-tag selector-tag match-tag data) certinfo
1265 (let* ((usage (lookup-enum 'tlsa-usage usage-tag :min 0 :max 255))
1266 (selector (lookup-enum 'tlsa-selector selector-tag
1268 (match (lookup-enum 'tlsa-match match-tag :min 0 :max 255))
1269 (raw (convert-tlsa-selector-data data selector match)))
1270 (push (list usage selector match raw) records))))
1271 (setf records (nreverse records))
1273 ;; Second pass: attach records for the requested services.
1274 (dolist (service (listify services))
1275 (destructuring-bind (svc &key (protocol :tcp)) (listify service)
1276 (let* ((port (etypecase svc
1278 (keyword (let ((serv (serv-by-name svc protocol)))
1280 (error "Unknown service `~A'" svc))
1281 (serv-port serv)))))
1282 (prefixed (domain-name-concat
1284 :labels (list (format nil "_~(~A~)" protocol)
1285 (format nil "_~A" port)))
1287 (dolist (record records)
1288 (rec :name prefixed :data record))))))))
1290 (defmethod zone-record-rrdata ((type (eql :tlsa)) zr)
1291 (destructuring-bind (usage selector match data) (zr-data zr)
1295 (rec-octet-vector data))
1298 (defenum dnssec-algorithm ()
1304 (:rsasha1-nsec3-sha1 7)
1308 (:ecdsap256sha256 13)
1309 (:ecdsap384sha384 14))
1311 (defenum dnssec-digest ()
1315 (defzoneparse :ds (name data rec)
1316 ":ds ((TAG ALGORITHM DIGEST-TYPE DIGEST)*)"
1318 (destructuring-bind (tag alg hashtype hash) ds
1319 (rec :data (list tag
1320 (lookup-enum 'dnssec-algorithm alg :min 0 :max 255)
1321 (lookup-enum 'dnssec-digest hashtype :min 0 :max 255)
1322 (decode-hex hash))))))
1324 (defmethod zone-record-rrdata ((type (eql :ds)) zr)
1325 (destructuring-bind (tag alg hashtype hash) zr
1329 (rec-octet-vector hash)))
1331 (defzoneparse :mx (name data rec :zname zname)
1332 ":mx ((HOST :prio INT :ip IPADDR)*)"
1333 (dolist (mx (listify data))
1335 (mxname &key (prio *default-mx-priority*) ip)
1337 (let ((host (zone-parse-host mxname zname)))
1338 (when ip (zone-set-address #'rec ip :name host))
1339 (rec :data (cons host prio))))))
1341 (defmethod zone-record-rrdata ((type (eql :mx)) zr)
1342 (let ((name (car (zr-data zr)))
1343 (prio (cdr (zr-data zr))))
1348 (defzoneparse :ns (name data rec :zname zname)
1349 ":ns ((HOST :ip IPADDR)*)"
1350 (dolist (ns (listify data))
1354 (let ((host (zone-parse-host nsname zname)))
1355 (when ip (zone-set-address #'rec ip :name host))
1356 (rec :data host)))))
1358 (defmethod zone-record-rrdata ((type (eql :ns)) zr)
1359 (rec-name (zr-data zr))
1362 (defzoneparse :alias (name data rec :zname zname)
1364 (dolist (a (listify data))
1365 (rec :name (zone-parse-host a zname)
1369 (defzoneparse :srv (name data rec :zname zname)
1370 ":srv (((SERVICE &key :port :protocol)
1371 (PROVIDER &key :port :prio :weight :ip)*)*)"
1373 (destructuring-bind (servopts &rest providers) srv
1375 (service &key ((:port default-port)) (protocol :tcp))
1377 (unless default-port
1378 (let ((serv (serv-by-name service protocol)))
1379 (setf default-port (and serv (serv-port serv)))))
1380 (let ((rname (flet ((prepend (tag tail)
1383 :labels (list (format nil "_~(~A~)" tag)))
1385 (prepend service (prepend protocol name)))))
1386 (dolist (prov providers)
1391 (prio *default-mx-priority*)
1395 (let ((host (zone-parse-host srvname zname)))
1396 (when ip (zone-set-address #'rec ip :name host))
1398 :data (list prio weight port host))))))))))
1400 (defmethod zone-record-rrdata ((type (eql :srv)) zr)
1401 (destructuring-bind (prio weight port host) (zr-data zr)
1408 (defenum caa-flag () (:critical 128))
1410 (defzoneparse :caa (name data rec)
1411 ":caa ((TAG VALUE FLAG*)*)"
1413 (destructuring-bind (tag value &rest flags) prop
1414 (setf flags (reduce #'logior
1415 (mapcar (lambda (item)
1416 (lookup-enum 'caa-flag item
1420 ((:issue :issuewild :iodef)
1422 :data (list flags tag value)))))))
1424 (defmethod zone-record-rrdata ((type (eql :caa)) zr)
1425 (destructuring-bind (flags tag value) (zr-data zr)
1427 (rec-string (string-downcase tag))
1428 (rec-raw-string value))
1431 (defzoneparse :net (name data rec)
1433 (dolist (net (listify data))
1434 (dolist (ipn (net-ipnets (net-must-find net)))
1435 (let* ((base (ipnet-net ipn))
1436 (rrtype (ipaddr-rrtype base)))
1437 (flet ((frob (kind addr)
1439 (rec :name (zone-parse-host kind name)
1443 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
1444 (frob "bcast" (ipnet-broadcast ipn)))))))
1446 (defzoneparse (:rev :reverse) (name data rec)
1447 ":reverse ((NET &key :prefix-bits :family) ZONE*)
1449 Add a reverse record each host in the ZONEs (or all zones) that lies
1451 (setf data (listify data))
1452 (destructuring-bind (net &key prefix-bits (family *address-family*))
1453 (listify (car data))
1455 (dolist (ipn (net-parse-to-ipnets net family))
1456 (let* ((seen (make-hash-table :test #'equal))
1457 (width (ipnet-width ipn))
1458 (frag-len (if prefix-bits (- width prefix-bits)
1459 (ipnet-changeable-bits width (ipnet-mask ipn)))))
1460 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
1461 (dolist (zr (zone-records (zone-find z)))
1462 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
1464 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
1465 (let* ((frag (reverse-domain-fragment (zr-data zr)
1467 (name (domain-name-concat frag name))
1468 (name-string (princ-to-string name)))
1469 (unless (gethash name-string seen)
1470 (rec :name name :type :ptr
1471 :ttl (zr-ttl zr) :data (zr-name zr))
1472 (setf (gethash name-string seen) t))))))))))
1474 (defzoneparse :multi (name data rec :zname zname :ttl ttl)
1475 ":multi (((NET*) &key :start :end :family :suffix) . REC)
1477 Output multiple records covering a portion of the reverse-resolution
1478 namespace corresponding to the particular NETs. The START and END bounds
1479 default to the most significant variable component of the
1480 reverse-resolution domain.
1482 The REC tail is a sequence of record forms (as handled by
1483 `zone-process-records') to be emitted for each covered address. Within
1484 the bodies of these forms, the symbol `*' will be replaced by the
1485 domain-name fragment corresponding to the current host, optionally
1486 followed by the SUFFIX.
1490 (:multi ((delegated-subnet :start 8)
1491 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
1493 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
1496 Obviously, nested `:multi' records won't work well."
1498 (destructuring-bind (nets
1499 &key start end ((:suffix raw-suffix))
1500 (family *address-family*))
1501 (listify (car data))
1502 (let ((suffix (if (not raw-suffix)
1503 (make-domain-name :labels nil :absolutep nil)
1504 (zone-parse-host raw-suffix))))
1505 (dolist (net (listify nets))
1506 (dolist (ipn (net-parse-to-ipnets net family))
1507 (let* ((addr (ipnet-net ipn))
1508 (width (ipaddr-width addr))
1509 (comp-width (reverse-domain-component-width addr))
1510 (end (round-up (or end
1511 (ipnet-changeable-bits width
1514 (start (round-down (or start (- end comp-width))
1516 (map (ipnet-host-map ipn)))
1517 (multiple-value-bind (host-step host-limit)
1518 (ipnet-index-bounds map start end)
1519 (do ((index 0 (+ index host-step)))
1520 ((> index host-limit))
1521 (let* ((addr (ipnet-index-host map index))
1522 (frag (reverse-domain-fragment addr start end))
1523 (target (reduce #'domain-name-concat
1524 (list frag suffix zname)
1526 :initial-value root-domain)))
1527 (dolist (zr (zone-parse-records (domain-name-concat frag
1532 (rec :name (zr-name zr)
1536 :make-ptr-p (zr-make-ptr-p zr))))))))))))
1538 ;;;--------------------------------------------------------------------------
1539 ;;; Zone file output.
1541 (export 'zone-write)
1542 (defgeneric zone-write (format zone stream)
1543 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1545 (defvar *writing-zone* nil
1546 "The zone currently being written.")
1548 (defvar *zone-output-stream* nil
1549 "Stream to write zone data on.")
1551 (export 'zone-write-raw-rrdata)
1552 (defgeneric zone-write-raw-rrdata (format zr type data)
1553 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1555 ZR gives the record object, which carries the name and TTL; the TYPE is
1556 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1557 This is used by the default `zone-write-record' method to handle record
1558 types which aren't directly supported by the format driver."))
1560 (export 'zone-write-header)
1561 (defgeneric zone-write-header (format zone)
1562 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1564 The header includes any kind of initial comment, the SOA record, and any
1565 other necessary preamble. There is no default implementation.
1567 This is part of the protocol used by the default method on `zone-write';
1568 if you override that method."))
1570 (export 'zone-write-trailer)
1571 (defgeneric zone-write-trailer (format zone)
1572 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1574 The footer may be empty, and is so by default.
1576 This is part of the protocol used by the default method on `zone-write';
1577 if you override that method.")
1578 (:method (format zone)
1579 (declare (ignore format zone))
1582 (export 'zone-write-record)
1583 (defgeneric zone-write-record (format type zr)
1584 (:documentation "Emit a record of the given TYPE (a keyword).
1586 The default implementation builds the raw RRDATA and passes it to
1587 `zone-write-raw-rrdata'.")
1588 (:method (format type zr)
1590 (data (build-record (setf code (zone-record-rrdata type zr)))))
1591 (zone-write-raw-rrdata format zr code data))))
1593 (defmethod zone-write (format zone stream)
1594 "This default method calls `zone-write-header', then `zone-write-record'
1595 for each record in the zone, and finally `zone-write-trailer'. While it's
1596 running, `*writing-zone*' is bound to the zone object, and
1597 `*zone-output-stream*' to the output stream."
1598 (let ((*writing-zone* zone)
1599 (*zone-output-stream* stream))
1600 (zone-write-header format zone)
1601 (dolist (zr (zone-records-sorted zone))
1602 (zone-write-record format (zr-type zr) zr))
1603 (zone-write-trailer format zone)))
1606 (defun zone-save (zones &key (format :bind))
1607 "Write the named ZONES to files. If no zones are given, write all the
1610 (setf zones (hash-table-keys *zones*)))
1613 (let ((zz (zone-find z)))
1615 (error "Unknown zone `~A'." z))
1616 (let ((stream (safely-open-output-stream safe
1617 (zone-file-name z :zone))))
1618 (zone-write format zz stream)
1621 ;;;--------------------------------------------------------------------------
1622 ;;; Bind format output.
1624 (defvar *bind-last-record-name* nil
1625 "The previously emitted record name.
1627 Used for eliding record names on output.")
1629 (export 'bind-hostname)
1630 (defun bind-hostname (hostname)
1631 (let ((zone (domain-name-labels (zone-name *writing-zone*)))
1632 (name (domain-name-labels hostname)))
1634 (unless (and zone name (string= (car zone) (car name)))
1636 (pop zone) (pop name))
1637 (flet ((stitch (labels absolutep)
1638 (format nil "~{~A~^.~}~@[.~]"
1639 (reverse (mapcar #'quotify-label labels))
1641 (cond (zone (stitch (domain-name-labels hostname) t))
1642 (name (stitch name nil))
1645 (export 'bind-output-hostname)
1646 (defun bind-output-hostname (hostname)
1647 (let ((name (bind-hostname hostname)))
1648 (cond ((and *bind-last-record-name*
1649 (string= name *bind-last-record-name*))
1652 (setf *bind-last-record-name* name)
1655 (defmethod zone-write :around ((format (eql :bind)) zone stream)
1656 (declare (ignorable zone stream))
1657 (let ((*bind-last-record-name* nil))
1658 (call-next-method)))
1660 (defmethod zone-write-header ((format (eql :bind)) zone)
1661 (format *zone-output-stream* "~
1662 ;;; Zone file `~(~A~)'
1668 (iso-date :now :datep t :timep t)
1669 (zone-default-ttl zone))
1670 (let* ((soa (zone-soa zone))
1671 (admin (let* ((name (soa-admin soa))
1672 (at (position #\@ name))
1673 (copy (format nil "~(~A~)." name)))
1675 (setf (char copy at) #\.))
1677 (format *zone-output-stream* "~
1678 ~A~30TIN SOA~40T~A (
1679 ~55@A~60T ;administrator
1680 ~45T~10D~60T ;serial
1681 ~45T~10D~60T ;refresh
1683 ~45T~10D~60T ;expire
1684 ~45T~10D )~60T ;min-ttl~2%"
1685 (bind-output-hostname (zone-name zone))
1686 (bind-hostname (soa-source soa))
1692 (soa-min-ttl soa))))
1694 (export 'bind-format-record)
1695 (defun bind-format-record (zr format &rest args)
1696 (format *zone-output-stream*
1697 "~A~20T~@[~8D~]~30TIN ~A~40T~?"
1698 (bind-output-hostname (zr-name zr))
1699 (let ((ttl (zr-ttl zr)))
1700 (and (/= ttl (zone-default-ttl *writing-zone*))
1702 (string-upcase (symbol-name (zr-type zr)))
1705 (export 'bind-write-hex)
1706 (defun bind-write-hex (vector remain)
1707 "Output the VECTOR as hex, in Bind format.
1709 If the length (in bytes) is less than REMAIN then it's placed on the
1710 current line; otherwise the Bind line-continuation syntax is used."
1711 (flet ((output-octet (octet)
1712 (format *zone-output-stream* "~(~2,'0X~)" octet)))
1713 (let ((len (length vector)))
1714 (cond ((< len remain)
1715 (dotimes (i len) (output-octet (aref vector i)))
1716 (terpri *zone-output-stream*))
1718 (format *zone-output-stream* "(")
1721 (when (>= i len) (return))
1722 (let ((limit (min len (+ i 64))))
1723 (format *zone-output-stream* "~%~8T")
1725 (when (>= i limit) (return))
1726 (output-octet (aref vector i))
1728 (format *zone-output-stream* " )~%"))))))
1730 (defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1731 (format *zone-output-stream*
1732 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A "
1733 (bind-output-hostname (zr-name zr))
1734 (let ((ttl (zr-ttl zr)))
1735 (and (/= ttl (zone-default-ttl *writing-zone*))
1739 (bind-write-hex data 12))
1741 (defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1742 (bind-format-record zr "~A~%" (ipaddr-string (zr-data zr))))
1744 (defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1745 (bind-format-record zr "~A~%" (ipaddr-string (zr-data zr))))
1747 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1748 (bind-format-record zr "~A~%" (bind-hostname (zr-data zr))))
1750 (defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1751 (bind-format-record zr "~A~%" (bind-hostname (zr-data zr))))
1753 (defmethod zone-write-record ((format (eql :bind)) (type (eql :dname)) zr)
1754 (bind-format-record zr "~A~%" (bind-hostname (zr-data zr))))
1756 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1757 (bind-format-record zr "~A~%" (bind-hostname (zr-data zr))))
1759 (defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1760 (bind-format-record zr "~2D ~A~%"
1762 (bind-hostname (car (zr-data zr)))))
1764 (defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1765 (destructuring-bind (prio weight port host) (zr-data zr)
1766 (bind-format-record zr "~2D ~5D ~5D ~A~%"
1767 prio weight port (bind-hostname host))))
1769 (defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1770 (destructuring-bind (alg type fpr) (zr-data zr)
1771 (bind-format-record zr "~2D ~2D " alg type)
1772 (bind-write-hex fpr 12)))
1774 (defmethod zone-write-record ((format (eql :bind)) (type (eql :tlsa)) zr)
1775 (destructuring-bind (usage selector match data) (zr-data zr)
1776 (bind-format-record zr "~2D ~2D ~2D " usage selector match)
1777 (bind-write-hex data 12)))
1779 (defmethod zone-write-record ((format (eql :bind)) (type (eql :caa)) zr)
1780 (destructuring-bind (flags tag value) (zr-data zr)
1781 (bind-format-record zr "~3D ~(~A~) ~S~%" flags tag value)))
1783 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ds)) zr)
1784 (destructuring-bind (tag alg hashtype hash) (zr-data zr)
1785 (bind-format-record zr "~5D ~2D ~2D " tag alg hashtype)
1786 (bind-write-hex hash 12)))
1788 (defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1789 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}~%"
1792 ;;;--------------------------------------------------------------------------
1793 ;;; tinydns-data output format.
1795 (export 'tinydns-output)
1796 (defun tinydns-output (code &rest fields)
1797 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1799 (defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
1800 (tinydns-output #\: (zr-name zr) type
1801 (with-output-to-string (out)
1802 (dotimes (i (length data))
1803 (let ((byte (aref data i)))
1804 (if (or (<= byte 32)
1806 (member byte '(#\: #\\) :key #'char-code))
1807 (format out "\\~3,'0O" byte)
1808 (write-char (code-char byte) out)))))
1811 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1812 (tinydns-output #\+ (zr-name zr)
1813 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1815 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1816 (tinydns-output #\3 (zr-name zr)
1817 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1820 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1821 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1823 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1824 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1826 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1827 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1829 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1830 (let ((name (car (zr-data zr)))
1831 (prio (cdr (zr-data zr))))
1832 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1834 (defmethod zone-write-header ((format (eql :tinydns)) zone)
1835 (format *zone-output-stream* "~
1836 ### Zone file `~(~A~)'
1840 (iso-date :now :datep t :timep t))
1841 (let ((soa (zone-soa zone)))
1845 (let* ((name (copy-seq (soa-admin soa)))
1846 (at (position #\@ name)))
1847 (when at (setf (char name at) #\.))
1853 (zone-default-ttl zone))))
1855 ;;;----- That's all, folks --------------------------------------------------