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 ;;;--------------------------------------------------------------------------
118 (defstruct (soa (:predicate soap))
119 "Start-of-authority record information."
128 (export 'zone-text-name)
129 (defun zone-text-name (zone)
130 (princ-to-string (zone-name zone)))
133 (defstruct (mx (:predicate mxp))
134 "Mail-exchange record information."
139 (defstruct (zone (:predicate zonep))
146 ;;;--------------------------------------------------------------------------
147 ;;; Zone defaults. It is intended that scripts override these.
149 (export '*default-zone-source*)
150 (defvar *default-zone-source*
151 (let ((hn (gethostname)))
152 (and hn (concatenate 'string (canonify-hostname hn) ".")))
153 "The default zone source: the current host's name.")
155 (export '*default-zone-refresh*)
156 (defvar *default-zone-refresh* (* 24 60 60)
157 "Default zone refresh interval: one day.")
159 (export '*default-zone-admin*)
160 (defvar *default-zone-admin* nil
161 "Default zone administrator's email address.")
163 (export '*default-zone-retry*)
164 (defvar *default-zone-retry* (* 60 60)
165 "Default znoe retry interval: one hour.")
167 (export '*default-zone-expire*)
168 (defvar *default-zone-expire* (* 14 24 60 60)
169 "Default zone expiry time: two weeks.")
171 (export '*default-zone-min-ttl*)
172 (defvar *default-zone-min-ttl* (* 4 60 60)
173 "Default zone minimum TTL/negative TTL: four hours.")
175 (export '*default-zone-ttl*)
176 (defvar *default-zone-ttl* (* 8 60 60)
177 "Default zone TTL (for records without explicit TTLs): 8 hours.")
179 (export '*default-mx-priority*)
180 (defvar *default-mx-priority* 50
181 "Default MX priority.")
183 ;;;--------------------------------------------------------------------------
184 ;;; Zone variables and structures.
186 (defvar *zones* (make-hash-table :test #'equal)
187 "Map of known zones.")
190 (defun zone-find (name)
191 "Find a zone given its NAME."
192 (gethash (string-downcase (stringify name)) *zones*))
193 (defun (setf zone-find) (zone name)
194 "Make the zone NAME map to ZONE."
195 (setf (gethash (string-downcase (stringify name)) *zones*) zone))
197 (export 'zone-record)
198 (defstruct (zone-record (:conc-name zr-))
206 (export 'zone-subdomain)
207 (defstruct (zone-subdomain (:conc-name zs-))
210 Slightly weird. Used internally by `zone-process-records', and shouldn't
216 (export '*zone-output-path*)
217 (defvar *zone-output-path* nil
218 "Pathname defaults to merge into output files.
220 If this is nil then use the prevailing `*default-pathname-defaults*'.
221 This is not the same as capturing the `*default-pathname-defaults*' from
224 (export '*preferred-subnets*)
225 (defvar *preferred-subnets* nil
226 "Subnets to prefer when selecting defaults.")
228 ;;;--------------------------------------------------------------------------
229 ;;; Zone infrastructure.
231 (defun zone-file-name (zone type)
232 "Choose a file name for a given ZONE and TYPE."
233 (merge-pathnames (make-pathname :name (string-downcase zone)
234 :type (string-downcase type))
235 (or *zone-output-path* *default-pathname-defaults*)))
237 (export 'zone-preferred-subnet-p)
238 (defun zone-preferred-subnet-p (name)
239 "Answer whether NAME (a string or symbol) names a preferred subnet."
240 (member name *preferred-subnets* :test #'string-equal))
242 (export 'preferred-subnet-case)
243 (defmacro preferred-subnet-case (&body clauses)
244 "Execute a form based on which networks are considered preferred.
246 The CLAUSES have the form (SUBNETS . FORMS) -- evaluate the first FORMS
247 whose SUBNETS (a list or single symbol, not evaluated) are listed in
248 `*preferred-subnets*'. If SUBNETS is the symbol `t' then the clause
251 ,@(mapcar (lambda (clause)
252 (let ((subnets (car clause)))
253 (cons (cond ((eq subnets t)
256 `(or ,@(mapcar (lambda (subnet)
257 `(zone-preferred-subnet-p
261 `(zone-preferred-subnet-p ',subnets)))
265 (export 'zone-parse-host)
266 (defun zone-parse-host (form &optional tail)
267 "Parse a host name FORM from a value in a zone form.
269 The underlying parsing is done using `parse-domain-name'. Here, we
270 interpret various kinds of Lisp object specially. In particular: `nil'
271 refers to the TAIL zone (just like a plain `@'); and a symbol is downcased
273 (let ((name (etypecase form
274 (null (make-domain-name :labels nil :absolutep nil))
276 (symbol (parse-domain-name (string-downcase form)))
277 (string (parse-domain-name form)))))
279 (domain-name-concat name tail))))
281 (export 'zone-records-sorted)
282 (defun zone-records-sorted (zone)
283 "Return the ZONE's records, in a pleasant sorted order."
284 (sort (copy-seq (zone-records zone))
286 (multiple-value-bind (precp follp)
287 (domain-name< (zr-name zr-a) (zr-name zr-b))
290 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
292 ;;;--------------------------------------------------------------------------
293 ;;; Serial numbering.
295 (export 'make-zone-serial)
296 (defun make-zone-serial (name)
297 "Given a zone NAME, come up with a new serial number.
299 This will (very carefully) update a file ZONE.serial in the current
301 (let* ((file (zone-file-name name :serial))
302 (last (with-open-file (in file
304 :if-does-not-exist nil)
307 (now (multiple-value-bind
308 (sec min hr dy mon yr dow dstp tz)
310 (declare (ignore sec min hr dow dstp tz))
312 (seq (cond ((not (equal now (cdr last))) 0)
313 ((< (car last) 99) (1+ (car last)))
314 (t (error "Run out of sequence numbers for ~A" name)))))
315 (safely-writing (out file)
317 ";; Serial number file for zone ~A~%~
318 ;; (LAST-SEQ DAY MONTH YEAR)~%~
322 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
324 ;;;--------------------------------------------------------------------------
325 ;;; Zone form parsing.
327 (defun zone-process-records (rec ttl func)
328 "Sort out the list of records in REC, calling FUNC for each one.
330 TTL is the default time-to-live for records which don't specify one.
332 REC is a list of records of the form
334 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
336 The various kinds of entries have the following meanings.
338 :ttl TTL Set the TTL for subsequent records (at this level of
341 TYPE DATA Define a record with a particular TYPE and DATA.
342 Record types are defined using `defzoneparse' and
343 the syntax of the data is idiosyncratic.
345 ((LABEL ...) . REC) Define records for labels within the zone. Any
346 records defined within REC will have their domains
347 prefixed by each of the LABELs. A singleton list
348 of labels may instead be written as a single
349 label. Note, therefore, that
351 (host (sub :a \"169.254.1.1\"))
353 defines a record for `host.sub' -- not `sub.host'.
355 If REC contains no top-level records, but it does define records for a
356 label listed in `*preferred-subnets*', then the records for the first such
357 label are also promoted to top-level.
359 The FUNC is called for each record encountered, represented as a
360 `zone-record' object. Zone parsers are not called: you get the record
361 types and data from the input form; see `zone-parse-records' if you want
364 (labels ((sift (rec ttl)
365 ;; Parse the record list REC into lists of `zone-record' and
366 ;; `zone-subdomain' objects, sorting out TTLs and so on.
367 ;; Returns them as two values.
369 (collecting (top sub)
375 (setf ttl (pop rec)))
377 (collect (make-zone-record :type r
382 (dolist (name (listify (car r)))
383 (collect (make-zone-subdomain
384 :name (zone-parse-host name)
385 :ttl ttl :records (cdr r))
388 (error "Unexpected record form ~A" (car r))))))))
390 (process (rec dom ttl)
391 ;; Recursirvely process the record list REC, with a list DOM of
392 ;; prefix labels, and a default TTL. Promote records for a
393 ;; preferred subnet to toplevel if there are no toplevel records
396 (multiple-value-bind (top sub) (sift rec ttl)
397 (if (and dom (null top) sub)
401 (let ((ll (domain-name-labels (zs-name s))))
402 (and (consp ll) (null (cdr ll))
403 (zone-preferred-subnet-p (car ll)))))
407 (process (zs-records preferred)
409 (zs-ttl preferred))))
412 (setf (zr-name zr) name)
415 (process (zs-records s)
416 (if (null dom) (zs-name s)
417 (domain-name-concat dom (zs-name s)))
420 ;; Process the records we're given with no prefix.
421 (process rec nil ttl)))
423 (defun zone-parse-head (head)
424 "Parse the HEAD of a zone form.
428 (NAME &key :source :admin :refresh :retry
429 :expire :min-ttl :ttl :serial)
431 though a singleton NAME needn't be a list. Returns the default TTL and an
432 soa structure representing the zone head."
436 (source *default-zone-source*)
437 (admin (or *default-zone-admin*
438 (format nil "hostmaster@~A" raw-zname)))
439 (refresh *default-zone-refresh*)
440 (retry *default-zone-retry*)
441 (expire *default-zone-expire*)
442 (min-ttl *default-zone-min-ttl*)
444 (serial (make-zone-serial raw-zname))
446 (zname (zone-parse-host raw-zname root-domain)))
449 (timespec-seconds ttl)
450 (make-soa :admin admin
451 :source (zone-parse-host source zname)
452 :refresh (timespec-seconds refresh)
453 :retry (timespec-seconds retry)
454 :expire (timespec-seconds expire)
455 :min-ttl (timespec-seconds min-ttl)
458 (export 'defzoneparse)
459 (defmacro defzoneparse (types (name data list
460 &key (prefix (gensym "PREFIX"))
461 (zname (gensym "ZNAME"))
462 (ttl (gensym "TTL")))
464 "Define a new zone record type.
466 The arguments are as follows:
468 TYPES A singleton type symbol, or a list of aliases.
470 NAME The name of the record to be added.
472 DATA The content of the record to be added (a single object,
475 LIST A function to add a record to the zone. See below.
477 PREFIX The prefix tag used in the original form.
479 ZNAME The name of the zone being constructed.
481 TTL The TTL for this record.
483 You get to choose your own names for these. ZNAME, PREFIX and TTL are
484 optional: you don't have to accept them if you're not interested.
486 The LIST argument names a function to be bound in the body to add a new
487 low-level record to the zone. It has the prototype
489 (LIST &key :name :type :data :ttl :make-ptr-p)
491 These (except MAKE-PTR-P, which defaults to nil) default to the above
492 arguments (even if you didn't accept the arguments)."
494 (setf types (listify types))
495 (let* ((type (car types))
496 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
497 (with-parsed-body (body decls doc) body
498 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
501 (setf (get ,i 'zone-parse) ',func))
502 (defun ,func (,prefix ,zname ,data ,ttl ,col)
505 (let ((,name (if (null ,prefix) ,zname
506 (domain-name-concat ,prefix ,zname))))
507 (flet ((,list (&key ((:name ,tname) ,name)
508 ((:type ,ttype) ,type)
509 ((:data ,tdata) ,data)
511 ((:make-ptr-p ,tmakeptrp) nil))
512 #+cmu (declare (optimize ext:inhibit-warnings))
513 (collect (make-zone-record :name ,tname
517 :make-ptr-p ,tmakeptrp)
522 (export 'zone-parse-records)
523 (defun zone-parse-records (zname ttl records)
524 "Parse a sequence of RECORDS and return a list of raw records.
526 The records are parsed relative to the zone name ZNAME, and using the
529 (flet ((parse-record (zr)
530 (let ((func (or (get (zr-type zr) 'zone-parse)
531 (error "No parser for record ~A."
533 (name (and (zr-name zr) (zr-name zr))))
534 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
535 (zone-process-records records ttl #'parse-record))))
538 (defun zone-parse (zf)
541 The syntax of a zone form is as follows:
544 ZONE-HEAD ZONE-RECORD*
547 ((NAME*) ZONE-RECORD*)
549 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
550 (make-zone :name zname
553 :records (zone-parse-records zname ttl (cdr zf)))))
555 (export 'zone-create)
556 (defun zone-create (zf)
557 "Zone construction function.
559 Given a zone form ZF, construct the zone and add it to the table."
560 (let* ((zone (zone-parse zf))
561 (name (zone-text-name zone)))
562 (setf (zone-find name) zone)
566 (defmacro defzone (soa &body zf)
567 "Zone definition macro."
568 `(zone-create '(,soa ,@zf)))
570 (export '*address-family*)
571 (defvar *address-family* t
572 "The default address family. This is bound by `defrevzone'.")
575 (defmacro defrevzone (head &body zf)
576 "Define a reverse zone, with the correct name."
577 (destructuring-bind (nets &rest args
578 &key &allow-other-keys
579 (family '*address-family*)
583 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
584 (let ((*address-family* (ipnet-family ,ipn)))
585 (zone-create `((,(format nil "~A." (reverse-domain ,ipn
587 ,@',(loop for (k v) on args by #'cddr
589 '(:family :prefix-bits))
593 (export 'map-host-addresses)
594 (defun map-host-addresses (func addr &key (family *address-family*))
595 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
597 (dolist (a (host-addrs (host-parse addr family)))
601 (defmacro do-host ((addr spec &key (family *address-family*)) &body body)
602 "Evaluate BODY, binding ADDR to each address denoted by SPEC."
603 `(dolist (,addr (host-addrs (host-parse ,spec ,family)))
606 (export 'zone-set-address)
607 (defun zone-set-address (rec addrspec &rest args
608 &key (family *address-family*) name ttl make-ptr-p)
609 "Write records (using REC) defining addresses for ADDRSPEC."
610 (declare (ignore name ttl make-ptr-p))
611 (let ((key-args (loop for (k v) on args by #'cddr
612 unless (eq k :family)
614 (do-host (addr addrspec :family family)
615 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
617 ;;;--------------------------------------------------------------------------
618 ;;; Building raw record vectors.
620 (defvar *record-vector* nil
621 "The record vector under construction.")
623 (defun rec-ensure (n)
624 "Ensure that at least N octets are spare in the current record."
625 (let ((want (+ n (fill-pointer *record-vector*)))
626 (have (array-dimension *record-vector* 0)))
627 (unless (<= want have)
628 (adjust-array *record-vector*
629 (do ((new (* 2 have) (* 2 new)))
630 ((<= want new) new))))))
633 (defun rec-byte (octets value)
634 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
636 (do ((i (1- octets) (1- i)))
638 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
641 (defun rec-u8 (value)
642 "Append an 8-bit VALUE to the current record."
646 (defun rec-u16 (value)
647 "Append a 16-bit VALUE to the current record."
651 (defun rec-u32 (value)
652 "Append a 32-bit VALUE to the current record."
655 (export 'rec-raw-string)
656 (defun rec-raw-string (s &key (start 0) end)
657 "Append (a (substring of) a raw string S to the current record.
659 No arrangement is made for reporting the length of the string. That must
660 be done by the caller, if necessary."
661 (setf-default end (length s))
662 (rec-ensure (- end start))
663 (do ((i start (1+ i)))
665 (vector-push (char-code (char s i)) *record-vector*)))
668 (defun rec-string (s &key (start 0) end (max 255))
669 (let* ((end (or end (length s)))
672 (error "String `~A' too long" (subseq s start end)))
673 (rec-u8 (- end start))
674 (rec-raw-string s :start start :end end)))
677 (defun rec-name (name)
678 "Append a domain NAME.
680 No attempt is made to perform compression of the name."
681 (dolist (label (reverse (domain-name-labels name)))
682 (rec-string label :max 63))
685 (export 'build-record)
686 (defmacro build-record (&body body)
687 "Build a raw record, and return it as a vector of octets."
688 `(let ((*record-vector* (make-array 256
689 :element-type '(unsigned-byte 8)
693 (copy-seq *record-vector*)))
695 (export 'zone-record-rrdata)
696 (defgeneric zone-record-rrdata (type zr)
697 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
699 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
702 ;;;--------------------------------------------------------------------------
703 ;;; Zone record parsers.
705 (defzoneparse :a (name data rec)
707 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
709 (defmethod zone-record-rrdata ((type (eql :a)) zr)
710 (rec-u32 (ipaddr-addr (zr-data zr)))
713 (defzoneparse :aaaa (name data rec)
715 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
717 (defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
718 (rec-byte 16 (ipaddr-addr (zr-data zr)))
721 (defzoneparse :addr (name data rec)
723 (zone-set-address #'rec data :make-ptr-p t))
725 (defzoneparse :svc (name data rec)
727 (zone-set-address #'rec data))
729 (defzoneparse :ptr (name data rec :zname zname)
731 (rec :data (zone-parse-host data zname)))
733 (defmethod zone-record-rrdata ((type (eql :ptr)) zr)
734 (rec-name (zr-data zr))
737 (defzoneparse :cname (name data rec :zname zname)
739 (rec :data (zone-parse-host data zname)))
741 (defmethod zone-record-rrdata ((type (eql :cname)) zr)
742 (rec-name (zr-data zr))
745 (defzoneparse :txt (name data rec)
747 (rec :data (listify data)))
749 (defmethod zone-record-rrdata ((type (eql :txt)) zr)
750 (mapc #'rec-string (zr-data zr))
753 (export '*dkim-pathname-defaults*)
754 (defvar *dkim-pathname-defaults*
755 (make-pathname :directory '(:relative "keys")
758 (defzoneparse :dkim (name data rec)
759 ":dkim (KEYFILE {:TAG VALUE}*)"
760 (destructuring-bind (file &rest plist) (listify data)
761 (let ((things nil) (out nil))
764 (push (get-output-stream-string out) things)
767 (let ((len (length text)))
768 (when (and out (> (+ (file-position out)
774 (unless out (setf out (make-string-output-stream)))
775 (write-string text out))
780 (push (subseq text i (min j len)) things))))))))
781 (do ((p plist (cddr p)))
783 (emit (format nil "~(~A~)=~A;" (car p) (cadr p))))
784 (emit (with-output-to-string (out)
785 (write-string "p=" out)
788 (in (merge-pathnames file *dkim-pathname-defaults*))
790 (when (string= (read-line in)
791 "-----BEGIN PUBLIC KEY-----")
794 (let ((line (read-line in)))
795 (if (string= line "-----END PUBLIC KEY-----")
797 (write-string line out)))))))))
799 :data (nreverse things)))))
801 (eval-when (:load-toplevel :execute)
802 (dolist (item '((sshfp-algorithm rsa 1)
803 (sshfp-algorithm dsa 2)
804 (sshfp-algorithm ecdsa 3)
806 (sshfp-type sha-256 2)))
807 (destructuring-bind (prop sym val) item
808 (setf (get sym prop) val)
811 (export '*sshfp-pathname-defaults*)
812 (defvar *sshfp-pathname-defaults*
813 (make-pathname :directory '(:relative "keys")
816 (defzoneparse :sshfp (name data rec)
817 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
819 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
820 (loop (let ((line (read-line in nil)))
821 (unless line (return))
822 (let ((words (str-split-words line)))
824 (when (string= (car words) "IN") (pop words))
825 (unless (and (string= (car words) "SSHFP")
826 (= (length words) 4))
827 (error "Invalid SSHFP record."))
829 (destructuring-bind (alg type fpr) words
830 (rec :data (list (parse-integer alg)
833 (flet ((lookup (what prop)
836 (symbol (or (get what prop)
837 (error "~S is not a known ~A" what prop))))))
838 (dolist (item (listify data))
839 (destructuring-bind (fpr &key (alg 'rsa) (type 'sha-1))
841 (rec :data (list (lookup alg 'sshfp-algorithm)
842 (lookup type 'sshfp-type)
845 (defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
846 (destructuring-bind (alg type fpr) (zr-data zr)
852 (rec-u8 (parse-integer fpr :start i :end (+ i 2) :radix 16))))
855 (defzoneparse :mx (name data rec :zname zname)
856 ":mx ((HOST :prio INT :ip IPADDR)*)"
857 (dolist (mx (listify data))
859 (mxname &key (prio *default-mx-priority*) ip)
861 (let ((host (zone-parse-host mxname zname)))
862 (when ip (zone-set-address #'rec ip :name host))
863 (rec :data (cons host prio))))))
865 (defmethod zone-record-rrdata ((type (eql :mx)) zr)
866 (let ((name (car (zr-data zr)))
867 (prio (cdr (zr-data zr))))
872 (defzoneparse :ns (name data rec :zname zname)
873 ":ns ((HOST :ip IPADDR)*)"
874 (dolist (ns (listify data))
878 (let ((host (zone-parse-host nsname zname)))
879 (when ip (zone-set-address #'rec ip :name host))
882 (defmethod zone-record-rrdata ((type (eql :ns)) zr)
883 (rec-name (zr-data zr))
886 (defzoneparse :alias (name data rec :zname zname)
888 (dolist (a (listify data))
889 (rec :name (zone-parse-host a zname)
893 (defzoneparse :srv (name data rec :zname zname)
894 ":srv (((SERVICE &key :port :protocol)
895 (PROVIDER &key :port :prio :weight :ip)*)*)"
897 (destructuring-bind (servopts &rest providers) srv
899 (service &key ((:port default-port)) (protocol :tcp))
902 (let ((serv (serv-by-name service protocol)))
903 (setf default-port (and serv (serv-port serv)))))
904 (let ((rname (flet ((prepend (tag tail)
907 :labels (list (format nil "_~(~A~)" tag)))
909 (prepend service (prepend protocol name)))))
910 (dolist (prov providers)
915 (prio *default-mx-priority*)
919 (let ((host (zone-parse-host srvname zname)))
920 (when ip (zone-set-address #'rec ip :name host))
922 :data (list prio weight port host))))))))))
924 (defmethod zone-record-rrdata ((type (eql :srv)) zr)
925 (destructuring-bind (prio weight port host) (zr-data zr)
932 (defzoneparse :net (name data rec)
934 (dolist (net (listify data))
935 (dolist (ipn (net-ipnets (net-must-find net)))
936 (let* ((base (ipnet-net ipn))
937 (rrtype (ipaddr-rrtype base)))
938 (flet ((frob (kind addr)
940 (rec :name (zone-parse-host kind name)
944 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
945 (frob "bcast" (ipnet-broadcast ipn)))))))
947 (defzoneparse (:rev :reverse) (name data rec)
948 ":reverse ((NET &key :prefix-bits :family) ZONE*)
950 Add a reverse record each host in the ZONEs (or all zones) that lies
952 (setf data (listify data))
953 (destructuring-bind (net &key prefix-bits (family *address-family*))
956 (dolist (ipn (net-parse-to-ipnets net family))
957 (let* ((seen (make-hash-table :test #'equal))
958 (width (ipnet-width ipn))
959 (frag-len (if prefix-bits (- width prefix-bits)
960 (ipnet-changeable-bits width (ipnet-mask ipn)))))
961 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
962 (dolist (zr (zone-records (zone-find z)))
963 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
965 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
966 (let* ((frag (reverse-domain-fragment (zr-data zr)
968 (name (domain-name-concat frag name))
969 (name-string (princ-to-string name)))
970 (unless (gethash name-string seen)
971 (rec :name name :type :ptr
972 :ttl (zr-ttl zr) :data (zr-name zr))
973 (setf (gethash name-string seen) t))))))))))
975 (defzoneparse :multi (name data rec :zname zname :ttl ttl)
976 ":multi (((NET*) &key :start :end :family :suffix) . REC)
978 Output multiple records covering a portion of the reverse-resolution
979 namespace corresponding to the particular NETs. The START and END bounds
980 default to the most significant variable component of the
981 reverse-resolution domain.
983 The REC tail is a sequence of record forms (as handled by
984 `zone-process-records') to be emitted for each covered address. Within
985 the bodies of these forms, the symbol `*' will be replaced by the
986 domain-name fragment corresponding to the current host, optionally
987 followed by the SUFFIX.
991 (:multi ((delegated-subnet :start 8)
992 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
994 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
997 Obviously, nested `:multi' records won't work well."
999 (destructuring-bind (nets
1000 &key start end ((:suffix raw-suffix))
1001 (family *address-family*))
1002 (listify (car data))
1003 (let ((suffix (if (not raw-suffix)
1004 (make-domain-name :labels nil :absolutep nil)
1005 (zone-parse-host raw-suffix))))
1006 (dolist (net (listify nets))
1007 (dolist (ipn (net-parse-to-ipnets net family))
1008 (let* ((addr (ipnet-net ipn))
1009 (width (ipaddr-width addr))
1010 (comp-width (reverse-domain-component-width addr))
1011 (end (round-up (or end
1012 (ipnet-changeable-bits width
1015 (start (round-down (or start (- end comp-width))
1017 (map (ipnet-host-map ipn)))
1018 (multiple-value-bind (host-step host-limit)
1019 (ipnet-index-bounds map start end)
1020 (do ((index 0 (+ index host-step)))
1021 ((> index host-limit))
1022 (let* ((addr (ipnet-index-host map index))
1023 (frag (reverse-domain-fragment addr start end))
1024 (target (reduce #'domain-name-concat
1025 (list frag suffix zname)
1027 :initial-value root-domain)))
1028 (dolist (zr (zone-parse-records (domain-name-concat frag
1033 (rec :name (zr-name zr)
1037 :make-ptr-p (zr-make-ptr-p zr))))))))))))
1039 ;;;--------------------------------------------------------------------------
1040 ;;; Zone file output.
1042 (export 'zone-write)
1043 (defgeneric zone-write (format zone stream)
1044 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1046 (defvar *writing-zone* nil
1047 "The zone currently being written.")
1049 (defvar *zone-output-stream* nil
1050 "Stream to write zone data on.")
1052 (export 'zone-write-raw-rrdata)
1053 (defgeneric zone-write-raw-rrdata (format zr type data)
1054 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1056 ZR gives the record object, which carries the name and TTL; the TYPE is
1057 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1058 This is used by the default `zone-write-record' method to handle record
1059 types which aren't directly supported by the format driver."))
1061 (export 'zone-write-header)
1062 (defgeneric zone-write-header (format zone)
1063 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1065 The header includes any kind of initial comment, the SOA record, and any
1066 other necessary preamble. There is no default implementation.
1068 This is part of the protocol used by the default method on `zone-write';
1069 if you override that method."))
1071 (export 'zone-write-trailer)
1072 (defgeneric zone-write-trailer (format zone)
1073 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1075 The footer may be empty, and is so by default.
1077 This is part of the protocol used by the default method on `zone-write';
1078 if you override that method.")
1079 (:method (format zone)
1080 (declare (ignore format zone))
1083 (export 'zone-write-record)
1084 (defgeneric zone-write-record (format type zr)
1085 (:documentation "Emit a record of the given TYPE (a keyword).
1087 The default implementation builds the raw RRDATA and passes it to
1088 `zone-write-raw-rrdata'.")
1089 (:method (format type zr)
1091 (data (build-record (setf code (zone-record-rrdata type zr)))))
1092 (zone-write-raw-rrdata format zr code data))))
1094 (defmethod zone-write (format zone stream)
1095 "This default method calls `zone-write-header', then `zone-write-record'
1096 for each record in the zone, and finally `zone-write-trailer'. While it's
1097 running, `*writing-zone*' is bound to the zone object, and
1098 `*zone-output-stream*' to the output stream."
1099 (let ((*writing-zone* zone)
1100 (*zone-output-stream* stream))
1101 (zone-write-header format zone)
1102 (dolist (zr (zone-records-sorted zone))
1103 (zone-write-record format (zr-type zr) zr))
1104 (zone-write-trailer format zone)))
1107 (defun zone-save (zones &key (format :bind))
1108 "Write the named ZONES to files. If no zones are given, write all the
1111 (setf zones (hash-table-keys *zones*)))
1114 (let ((zz (zone-find z)))
1116 (error "Unknown zone `~A'." z))
1117 (let ((stream (safely-open-output-stream safe
1118 (zone-file-name z :zone))))
1119 (zone-write format zz stream))))))
1121 ;;;--------------------------------------------------------------------------
1122 ;;; Bind format output.
1124 (defvar *bind-last-record-name* nil
1125 "The previously emitted record name.
1127 Used for eliding record names on output.")
1129 (export 'bind-hostname)
1130 (defun bind-hostname (hostname)
1131 (let ((zone (domain-name-labels (zone-name *writing-zone*)))
1132 (name (domain-name-labels hostname)))
1134 (unless (and zone name (string= (car zone) (car name)))
1136 (pop zone) (pop name))
1137 (flet ((stitch (labels absolutep)
1138 (format nil "~{~A~^.~}~@[.~]"
1139 (reverse (mapcar #'quotify-label labels))
1141 (cond (zone (stitch (domain-name-labels hostname) t))
1142 (name (stitch name nil))
1145 (export 'bind-output-hostname)
1146 (defun bind-output-hostname (hostname)
1147 (let ((name (bind-hostname hostname)))
1148 (cond ((and *bind-last-record-name*
1149 (string= name *bind-last-record-name*))
1152 (setf *bind-last-record-name* name)
1155 (defmethod zone-write :around ((format (eql :bind)) zone stream)
1156 (declare (ignorable zone stream))
1157 (let ((*bind-last-record-name* nil))
1158 (call-next-method)))
1160 (defmethod zone-write-header ((format (eql :bind)) zone)
1161 (format *zone-output-stream* "~
1162 ;;; Zone file `~(~A~)'
1168 (iso-date :now :datep t :timep t)
1169 (zone-default-ttl zone))
1170 (let* ((soa (zone-soa zone))
1171 (admin (let* ((name (soa-admin soa))
1172 (at (position #\@ name))
1173 (copy (format nil "~(~A~)." name)))
1175 (setf (char copy at) #\.))
1177 (format *zone-output-stream* "~
1178 ~A~30TIN SOA~40T~A (
1179 ~55@A~60T ;administrator
1180 ~45T~10D~60T ;serial
1181 ~45T~10D~60T ;refresh
1183 ~45T~10D~60T ;expire
1184 ~45T~10D )~60T ;min-ttl~2%"
1185 (bind-output-hostname (zone-name zone))
1186 (bind-hostname (soa-source soa))
1192 (soa-min-ttl soa))))
1194 (export 'bind-format-record)
1195 (defun bind-format-record (zr format &rest args)
1196 (format *zone-output-stream*
1197 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
1198 (bind-output-hostname (zr-name zr))
1199 (let ((ttl (zr-ttl zr)))
1200 (and (/= ttl (zone-default-ttl *writing-zone*))
1202 (string-upcase (symbol-name (zr-type zr)))
1205 (defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1206 (format *zone-output-stream*
1207 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A"
1208 (bind-output-hostname (zr-name zr))
1209 (let ((ttl (zr-ttl zr)))
1210 (and (/= ttl (zone-default-ttl *writing-zone*))
1214 (let* ((hex (with-output-to-string (out)
1215 (dotimes (i (length data))
1216 (format out "~(~2,'0X~)" (aref data i)))))
1219 (format *zone-output-stream* " ~A~%" hex))
1221 (format *zone-output-stream* " (")
1224 (when (>= i len) (return))
1225 (let ((j (min (+ i 64) len)))
1226 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1228 (format *zone-output-stream* " )~%")))))
1230 (defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1231 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1233 (defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1234 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1236 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1237 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1239 (defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1240 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1242 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1243 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1245 (defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1246 (bind-format-record zr "~2D ~A"
1248 (bind-hostname (car (zr-data zr)))))
1250 (defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1251 (destructuring-bind (prio weight port host) (zr-data zr)
1252 (bind-format-record zr "~2D ~5D ~5D ~A"
1253 prio weight port (bind-hostname host))))
1255 (defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1256 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1258 (defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1259 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
1261 ;;;--------------------------------------------------------------------------
1262 ;;; tinydns-data output format.
1264 (export 'tinydns-output)
1265 (defun tinydns-output (code &rest fields)
1266 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1268 (defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
1269 (tinydns-output #\: (zr-name zr) type
1270 (with-output-to-string (out)
1271 (dotimes (i (length data))
1272 (let ((byte (aref data i)))
1273 (if (or (<= byte 32)
1275 (member byte '(#\: #\\) :key #'char-code))
1276 (format out "\\~3,'0O" byte)
1277 (write-char (code-char byte) out)))))
1280 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1281 (tinydns-output #\+ (zr-name zr)
1282 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1284 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1285 (tinydns-output #\3 (zr-name zr)
1286 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1289 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1290 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1292 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1293 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1295 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1296 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1298 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1299 (let ((name (car (zr-data zr)))
1300 (prio (cdr (zr-data zr))))
1301 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1303 (defmethod zone-write-header ((format (eql :tinydns)) zone)
1304 (format *zone-output-stream* "~
1305 ### Zone file `~(~A~)'
1309 (iso-date :now :datep t :timep t))
1310 (let ((soa (zone-soa zone)))
1314 (let* ((name (copy-seq (soa-admin soa)))
1315 (at (position #\@ name)))
1316 (when at (setf (char name at) #\.))
1322 (zone-default-ttl zone))))
1324 ;;;----- That's all, folks --------------------------------------------------