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 (defmacro defenum (name (&key export) &body values)
115 "Set up symbol properties for manifest constants.
117 The VALUES are a list of (TAG VALUE) pairs. Each TAG is a symbol; we set
118 the NAME property on TAG to VALUE, and export TAG. There are also handy
119 hash-tables mapping in the forward and reverse directions, in the name
120 symbol's `enum-forward' and `enum-reverse' properties."
121 `(eval-when (:compile-toplevel :load-toplevel :execute)
122 ,(let*/gensyms (export)
123 (with-gensyms (forward reverse valtmp)
124 `(let ((,forward (make-hash-table))
125 (,reverse (make-hash-table)))
126 (when ,export (export ',name))
127 ,@(mapcar (lambda (item)
128 (destructuring-bind (tag value) item
130 (intern (concatenate 'string
133 (symbol-name tag)))))
134 `(let ((,valtmp ,value))
137 (when (eq (symbol-package ',tag) *package*)
139 (defconstant ,constant ,valtmp)
140 (setf (get ',tag ',name) ,value
141 (gethash ',tag ,forward) ,valtmp
142 (gethash ,valtmp ,reverse) ',tag)))))
144 (setf (get ',name 'enum-forward) ,forward
145 (get ',name 'enum-reverse) ,reverse))))))
147 (defun lookup-enum (name tag &key min max)
148 "Look up a TAG in an enumeration.
150 If TAG is a symbol, check its NAME property; if it's a fixnum then take it
151 as it is. Make sure that it's between MIN and MAX, if they're not nil."
152 (let ((value (etypecase tag
154 (symbol (or (get tag name)
155 (error "~S is not a known ~A" tag name))))))
156 (unless (and (or (null min) (<= min value))
157 (or (null max) (<= value max)))
158 (error "Value ~S out of range for ~A" value name))
161 (defun reverse-enum (name value)
162 "Reverse-lookup of a VALUE in enumeration NAME.
164 If a tag for the VALUE is found, return it and `t'; otherwise return VALUE
165 unchanged and `nil'."
166 (multiple-value-bind (tag foundp) (gethash value (get name 'enum-reverse))
169 (values value nil))))
171 (defun mapenum (func name)
172 "Call FUNC on TAG/VALUE pairs from the enumeration called NAME."
173 (maphash func (get name 'enum-forward)))
175 ;;;--------------------------------------------------------------------------
179 (defstruct (soa (:predicate soap))
180 "Start-of-authority record information."
189 (export 'zone-text-name)
190 (defun zone-text-name (zone)
191 (princ-to-string (zone-name zone)))
194 (defstruct (mx (:predicate mxp))
195 "Mail-exchange record information."
200 (defstruct (zone (:predicate zonep))
207 ;;;--------------------------------------------------------------------------
208 ;;; Zone defaults. It is intended that scripts override these.
210 (export '*default-zone-source*)
211 (defvar *default-zone-source*
212 (let ((hn (gethostname)))
213 (and hn (concatenate 'string (canonify-hostname hn) ".")))
214 "The default zone source: the current host's name.")
216 (export '*default-zone-refresh*)
217 (defvar *default-zone-refresh* (* 24 60 60)
218 "Default zone refresh interval: one day.")
220 (export '*default-zone-admin*)
221 (defvar *default-zone-admin* nil
222 "Default zone administrator's email address.")
224 (export '*default-zone-retry*)
225 (defvar *default-zone-retry* (* 60 60)
226 "Default znoe retry interval: one hour.")
228 (export '*default-zone-expire*)
229 (defvar *default-zone-expire* (* 14 24 60 60)
230 "Default zone expiry time: two weeks.")
232 (export '*default-zone-min-ttl*)
233 (defvar *default-zone-min-ttl* (* 4 60 60)
234 "Default zone minimum TTL/negative TTL: four hours.")
236 (export '*default-zone-ttl*)
237 (defvar *default-zone-ttl* (* 8 60 60)
238 "Default zone TTL (for records without explicit TTLs): 8 hours.")
240 (export '*default-mx-priority*)
241 (defvar *default-mx-priority* 50
242 "Default MX priority.")
244 ;;;--------------------------------------------------------------------------
245 ;;; Zone variables and structures.
247 (defvar *zones* (make-hash-table :test #'equal)
248 "Map of known zones.")
251 (defun zone-find (name)
252 "Find a zone given its NAME."
253 (gethash (string-downcase (stringify name)) *zones*))
254 (defun (setf zone-find) (zone name)
255 "Make the zone NAME map to ZONE."
256 (setf (gethash (string-downcase (stringify name)) *zones*) zone))
258 (export 'zone-record)
259 (defstruct (zone-record (:conc-name zr-))
267 (export 'zone-subdomain)
268 (defstruct (zone-subdomain (:conc-name zs-))
271 Slightly weird. Used internally by `zone-process-records', and shouldn't
277 (export '*zone-output-path*)
278 (defvar *zone-output-path* nil
279 "Pathname defaults to merge into output files.
281 If this is nil then use the prevailing `*default-pathname-defaults*'.
282 This is not the same as capturing the `*default-pathname-defaults*' from
285 (export '*preferred-subnets*)
286 (defvar *preferred-subnets* nil
287 "Subnets to prefer when selecting defaults.")
289 ;;;--------------------------------------------------------------------------
290 ;;; Zone infrastructure.
292 (defun zone-file-name (zone type)
293 "Choose a file name for a given ZONE and TYPE."
294 (merge-pathnames (make-pathname :name (string-downcase zone)
295 :type (string-downcase type))
296 (or *zone-output-path* *default-pathname-defaults*)))
298 (export 'zone-preferred-subnet-p)
299 (defun zone-preferred-subnet-p (name)
300 "Answer whether NAME (a string or symbol) names a preferred subnet."
301 (member name *preferred-subnets* :test #'string-equal))
303 (export 'preferred-subnet-case)
304 (defmacro preferred-subnet-case (&body clauses)
305 "Execute a form based on which networks are considered preferred.
307 The CLAUSES have the form (SUBNETS . FORMS) -- evaluate the first FORMS
308 whose SUBNETS (a list or single symbol, not evaluated) are listed in
309 `*preferred-subnets*'. If SUBNETS is the symbol `t' then the clause
312 ,@(mapcar (lambda (clause)
313 (let ((subnets (car clause)))
314 (cons (cond ((eq subnets t)
317 `(or ,@(mapcar (lambda (subnet)
318 `(zone-preferred-subnet-p
322 `(zone-preferred-subnet-p ',subnets)))
326 (export 'zone-parse-host)
327 (defun zone-parse-host (form &optional tail)
328 "Parse a host name FORM from a value in a zone form.
330 The underlying parsing is done using `parse-domain-name'. Here, we
331 interpret various kinds of Lisp object specially. In particular: `nil'
332 refers to the TAIL zone (just like a plain `@'); and a symbol is downcased
334 (let ((name (etypecase form
335 (null (make-domain-name :labels nil :absolutep nil))
337 (symbol (parse-domain-name (string-downcase form)))
338 (string (parse-domain-name form)))))
340 (domain-name-concat name tail))))
342 (export 'zone-records-sorted)
343 (defun zone-records-sorted (zone)
344 "Return the ZONE's records, in a pleasant sorted order."
345 (sort (copy-seq (zone-records zone))
347 (multiple-value-bind (precp follp)
348 (domain-name< (zr-name zr-a) (zr-name zr-b))
351 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
353 ;;;--------------------------------------------------------------------------
354 ;;; Serial numbering.
356 (export 'make-zone-serial)
357 (defun make-zone-serial (name)
358 "Given a zone NAME, come up with a new serial number.
360 This will (very carefully) update a file ZONE.serial in the current
362 (let* ((file (zone-file-name name :serial))
363 (last (with-open-file (in file
365 :if-does-not-exist nil)
368 (now (multiple-value-bind
369 (sec min hr dy mon yr dow dstp tz)
371 (declare (ignore sec min hr dow dstp tz))
373 (seq (cond ((not (equal now (cdr last))) 0)
374 ((< (car last) 99) (1+ (car last)))
375 (t (error "Run out of sequence numbers for ~A" name)))))
376 (safely-writing (out file)
378 ";; Serial number file for zone ~A~%~
379 ;; (LAST-SEQ DAY MONTH YEAR)~%~
383 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
385 ;;;--------------------------------------------------------------------------
386 ;;; Zone form parsing.
388 (defun zone-process-records (rec ttl func)
389 "Sort out the list of records in REC, calling FUNC for each one.
391 TTL is the default time-to-live for records which don't specify one.
393 REC is a list of records of the form
395 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
397 The various kinds of entries have the following meanings.
399 :ttl TTL Set the TTL for subsequent records (at this level of
402 TYPE DATA Define a record with a particular TYPE and DATA.
403 Record types are defined using `defzoneparse' and
404 the syntax of the data is idiosyncratic.
406 ((LABEL ...) . REC) Define records for labels within the zone. Any
407 records defined within REC will have their domains
408 prefixed by each of the LABELs. A singleton list
409 of labels may instead be written as a single
410 label. Note, therefore, that
412 (host (sub :a \"169.254.1.1\"))
414 defines a record for `host.sub' -- not `sub.host'.
416 If REC contains no top-level records, but it does define records for a
417 label listed in `*preferred-subnets*', then the records for the first such
418 label are also promoted to top-level.
420 The FUNC is called for each record encountered, represented as a
421 `zone-record' object. Zone parsers are not called: you get the record
422 types and data from the input form; see `zone-parse-records' if you want
425 (labels ((sift (rec ttl)
426 ;; Parse the record list REC into lists of `zone-record' and
427 ;; `zone-subdomain' objects, sorting out TTLs and so on.
428 ;; Returns them as two values.
430 (collecting (top sub)
436 (setf ttl (pop rec)))
438 (collect (make-zone-record :type r
443 (dolist (name (listify (car r)))
444 (collect (make-zone-subdomain
445 :name (zone-parse-host name)
446 :ttl ttl :records (cdr r))
449 (error "Unexpected record form ~A" (car r))))))))
451 (process (rec dom ttl)
452 ;; Recursirvely process the record list REC, with a list DOM of
453 ;; prefix labels, and a default TTL. Promote records for a
454 ;; preferred subnet to toplevel if there are no toplevel records
457 (multiple-value-bind (top sub) (sift rec ttl)
458 (if (and dom (null top) sub)
462 (let ((ll (domain-name-labels (zs-name s))))
463 (and (consp ll) (null (cdr ll))
464 (zone-preferred-subnet-p (car ll)))))
468 (process (zs-records preferred)
470 (zs-ttl preferred))))
473 (setf (zr-name zr) name)
476 (process (zs-records s)
477 (if (null dom) (zs-name s)
478 (domain-name-concat dom (zs-name s)))
481 ;; Process the records we're given with no prefix.
482 (process rec nil ttl)))
484 (defun zone-parse-head (head)
485 "Parse the HEAD of a zone form.
489 (NAME &key :source :admin :refresh :retry
490 :expire :min-ttl :ttl :serial)
492 though a singleton NAME needn't be a list. Returns the default TTL and an
493 soa structure representing the zone head."
497 (source *default-zone-source*)
498 (admin (or *default-zone-admin*
499 (format nil "hostmaster@~A" raw-zname)))
500 (refresh *default-zone-refresh*)
501 (retry *default-zone-retry*)
502 (expire *default-zone-expire*)
503 (min-ttl *default-zone-min-ttl*)
505 (serial (make-zone-serial raw-zname))
507 (zname (zone-parse-host raw-zname root-domain)))
510 (timespec-seconds ttl)
511 (make-soa :admin admin
512 :source (zone-parse-host source zname)
513 :refresh (timespec-seconds refresh)
514 :retry (timespec-seconds retry)
515 :expire (timespec-seconds expire)
516 :min-ttl (timespec-seconds min-ttl)
519 (export 'defzoneparse)
520 (defmacro defzoneparse (types (name data list
521 &key (prefix (gensym "PREFIX"))
522 (zname (gensym "ZNAME"))
523 (ttl (gensym "TTL")))
525 "Define a new zone record type.
527 The arguments are as follows:
529 TYPES A singleton type symbol, or a list of aliases.
531 NAME The name of the record to be added.
533 DATA The content of the record to be added (a single object,
536 LIST A function to add a record to the zone. See below.
538 PREFIX The prefix tag used in the original form.
540 ZNAME The name of the zone being constructed.
542 TTL The TTL for this record.
544 You get to choose your own names for these. ZNAME, PREFIX and TTL are
545 optional: you don't have to accept them if you're not interested.
547 The LIST argument names a function to be bound in the body to add a new
548 low-level record to the zone. It has the prototype
550 (LIST &key :name :type :data :ttl :make-ptr-p)
552 These (except MAKE-PTR-P, which defaults to nil) default to the above
553 arguments (even if you didn't accept the arguments)."
555 (setf types (listify types))
556 (let* ((type (car types))
557 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
558 (with-parsed-body (body decls doc) body
559 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
562 (setf (get ,i 'zone-parse) ',func))
563 (defun ,func (,prefix ,zname ,data ,ttl ,col)
566 (let ((,name (if (null ,prefix) ,zname
567 (domain-name-concat ,prefix ,zname))))
568 (flet ((,list (&key ((:name ,tname) ,name)
569 ((:type ,ttype) ,type)
570 ((:data ,tdata) ,data)
572 ((:make-ptr-p ,tmakeptrp) nil))
573 #+cmu (declare (optimize ext:inhibit-warnings))
574 (collect (make-zone-record :name ,tname
578 :make-ptr-p ,tmakeptrp)
583 (export 'zone-parse-records)
584 (defun zone-parse-records (zname ttl records)
585 "Parse a sequence of RECORDS and return a list of raw records.
587 The records are parsed relative to the zone name ZNAME, and using the
590 (flet ((parse-record (zr)
591 (let ((func (or (get (zr-type zr) 'zone-parse)
592 (error "No parser for record ~A."
594 (name (and (zr-name zr) (zr-name zr))))
595 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
596 (zone-process-records records ttl #'parse-record))))
599 (defun zone-parse (zf)
602 The syntax of a zone form is as follows:
605 ZONE-HEAD ZONE-RECORD*
608 ((NAME*) ZONE-RECORD*)
610 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
611 (make-zone :name zname
614 :records (zone-parse-records zname ttl (cdr zf)))))
616 (export 'zone-create)
617 (defun zone-create (zf)
618 "Zone construction function.
620 Given a zone form ZF, construct the zone and add it to the table."
621 (let* ((zone (zone-parse zf))
622 (name (zone-text-name zone)))
623 (setf (zone-find name) zone)
627 (defmacro defzone (soa &body zf)
628 "Zone definition macro."
629 `(zone-create '(,soa ,@zf)))
631 (export '*address-family*)
632 (defvar *address-family* t
633 "The default address family. This is bound by `defrevzone'.")
636 (defmacro defrevzone (head &body zf)
637 "Define a reverse zone, with the correct name."
638 (destructuring-bind (nets &rest args
639 &key &allow-other-keys
640 (family '*address-family*)
644 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
645 (let ((*address-family* (ipnet-family ,ipn)))
646 (zone-create `((,(format nil "~A." (reverse-domain ,ipn
648 ,@',(loop for (k v) on args by #'cddr
650 '(:family :prefix-bits))
654 (export 'map-host-addresses)
655 (defun map-host-addresses (func addr &key (family *address-family*))
656 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
658 (dolist (a (host-addrs (host-parse addr family)))
662 (defmacro do-host ((addr spec &key (family *address-family*)) &body body)
663 "Evaluate BODY, binding ADDR to each address denoted by SPEC."
664 `(dolist (,addr (host-addrs (host-parse ,spec ,family)))
667 (export 'zone-set-address)
668 (defun zone-set-address (rec addrspec &rest args
669 &key (family *address-family*) name ttl make-ptr-p)
670 "Write records (using REC) defining addresses for ADDRSPEC."
671 (declare (ignore name ttl make-ptr-p))
672 (let ((key-args (loop for (k v) on args by #'cddr
673 unless (eq k :family)
675 (do-host (addr addrspec :family family)
676 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
678 ;;;--------------------------------------------------------------------------
679 ;;; Building raw record vectors.
681 (defvar *record-vector* nil
682 "The record vector under construction.")
684 (defun rec-ensure (n)
685 "Ensure that at least N octets are spare in the current record."
686 (let ((want (+ n (fill-pointer *record-vector*)))
687 (have (array-dimension *record-vector* 0)))
688 (unless (<= want have)
689 (adjust-array *record-vector*
690 (do ((new (* 2 have) (* 2 new)))
691 ((<= want new) new))))))
694 (defun rec-byte (octets value)
695 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
697 (do ((i (1- octets) (1- i)))
699 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
702 (defun rec-u8 (value)
703 "Append an 8-bit VALUE to the current record."
707 (defun rec-u16 (value)
708 "Append a 16-bit VALUE to the current record."
712 (defun rec-u32 (value)
713 "Append a 32-bit VALUE to the current record."
716 (export 'rec-raw-string)
717 (defun rec-raw-string (s &key (start 0) end)
718 "Append (a (substring of) a raw string S to the current record.
720 No arrangement is made for reporting the length of the string. That must
721 be done by the caller, if necessary."
722 (setf-default end (length s))
723 (rec-ensure (- end start))
724 (do ((i start (1+ i)))
726 (vector-push (char-code (char s i)) *record-vector*)))
729 (defun rec-string (s &key (start 0) end (max 255))
730 (let* ((end (or end (length s)))
733 (error "String `~A' too long" (subseq s start end)))
734 (rec-u8 (- end start))
735 (rec-raw-string s :start start :end end)))
738 (defun rec-name (name)
739 "Append a domain NAME.
741 No attempt is made to perform compression of the name."
742 (dolist (label (reverse (domain-name-labels name)))
743 (rec-string label :max 63))
746 (export 'build-record)
747 (defmacro build-record (&body body)
748 "Build a raw record, and return it as a vector of octets."
749 `(let ((*record-vector* (make-array 256
750 :element-type '(unsigned-byte 8)
754 (copy-seq *record-vector*)))
756 (export 'zone-record-rrdata)
757 (defgeneric zone-record-rrdata (type zr)
758 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
760 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
763 ;;;--------------------------------------------------------------------------
764 ;;; Zone record parsers.
766 (defzoneparse :a (name data rec)
768 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
770 (defmethod zone-record-rrdata ((type (eql :a)) zr)
771 (rec-u32 (ipaddr-addr (zr-data zr)))
774 (defzoneparse :aaaa (name data rec)
776 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
778 (defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
779 (rec-byte 16 (ipaddr-addr (zr-data zr)))
782 (defzoneparse :addr (name data rec)
784 (zone-set-address #'rec data :make-ptr-p t))
786 (defzoneparse :svc (name data rec)
788 (zone-set-address #'rec data))
790 (defzoneparse :ptr (name data rec :zname zname)
792 (rec :data (zone-parse-host data zname)))
794 (defmethod zone-record-rrdata ((type (eql :ptr)) zr)
795 (rec-name (zr-data zr))
798 (defzoneparse :cname (name data rec :zname zname)
800 (rec :data (zone-parse-host data zname)))
802 (defmethod zone-record-rrdata ((type (eql :cname)) zr)
803 (rec-name (zr-data zr))
806 (defzoneparse :txt (name data rec)
808 (rec :data (listify data)))
810 (defmethod zone-record-rrdata ((type (eql :txt)) zr)
811 (mapc #'rec-string (zr-data zr))
814 (export '*dkim-pathname-defaults*)
815 (defvar *dkim-pathname-defaults*
816 (make-pathname :directory '(:relative "keys")
819 (defzoneparse :dkim (name data rec)
820 ":dkim (KEYFILE {:TAG VALUE}*)"
821 (destructuring-bind (file &rest plist) (listify data)
822 (let ((things nil) (out nil))
825 (push (get-output-stream-string out) things)
828 (let ((len (length text)))
829 (when (and out (> (+ (file-position out)
835 (unless out (setf out (make-string-output-stream)))
836 (write-string text out))
841 (push (subseq text i (min j len)) things))))))))
842 (do ((p plist (cddr p)))
844 (emit (format nil "~(~A~)=~A;" (car p) (cadr p))))
845 (emit (with-output-to-string (out)
846 (write-string "p=" out)
849 (in (merge-pathnames file *dkim-pathname-defaults*))
851 (when (string= (read-line in)
852 "-----BEGIN PUBLIC KEY-----")
855 (let ((line (read-line in)))
856 (if (string= line "-----END PUBLIC KEY-----")
858 (write-string line out)))))))))
860 :data (nreverse things)))))
862 (defenum sshfp-algorithm (rsa 1) (dsa 2) (ecdsa 3))
863 (defenum sshfp-type (sha-1 1) (sha-256 2))
865 (export '*sshfp-pathname-defaults*)
866 (defvar *sshfp-pathname-defaults*
867 (make-pathname :directory '(:relative "keys")
870 (defzoneparse :sshfp (name data rec)
871 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
873 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
874 (loop (let ((line (read-line in nil)))
875 (unless line (return))
876 (let ((words (str-split-words line)))
878 (when (string= (car words) "IN") (pop words))
879 (unless (and (string= (car words) "SSHFP")
880 (= (length words) 4))
881 (error "Invalid SSHFP record."))
883 (destructuring-bind (alg type fpr) words
884 (rec :data (list (parse-integer alg)
887 (dolist (item (listify data))
888 (destructuring-bind (fpr &key (alg 'rsa) (type 'sha-1))
890 (rec :data (list (lookup-enum alg 'sshfp-algorithm :min 0 :max 255)
891 (lookup-enum type 'sshfp-type :min 0 :max 255)
894 (defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
895 (destructuring-bind (alg type fpr) (zr-data zr)
901 (rec-u8 (parse-integer fpr :start i :end (+ i 2) :radix 16))))
904 (defzoneparse :mx (name data rec :zname zname)
905 ":mx ((HOST :prio INT :ip IPADDR)*)"
906 (dolist (mx (listify data))
908 (mxname &key (prio *default-mx-priority*) ip)
910 (let ((host (zone-parse-host mxname zname)))
911 (when ip (zone-set-address #'rec ip :name host))
912 (rec :data (cons host prio))))))
914 (defmethod zone-record-rrdata ((type (eql :mx)) zr)
915 (let ((name (car (zr-data zr)))
916 (prio (cdr (zr-data zr))))
921 (defzoneparse :ns (name data rec :zname zname)
922 ":ns ((HOST :ip IPADDR)*)"
923 (dolist (ns (listify data))
927 (let ((host (zone-parse-host nsname zname)))
928 (when ip (zone-set-address #'rec ip :name host))
931 (defmethod zone-record-rrdata ((type (eql :ns)) zr)
932 (rec-name (zr-data zr))
935 (defzoneparse :alias (name data rec :zname zname)
937 (dolist (a (listify data))
938 (rec :name (zone-parse-host a zname)
942 (defzoneparse :srv (name data rec :zname zname)
943 ":srv (((SERVICE &key :port :protocol)
944 (PROVIDER &key :port :prio :weight :ip)*)*)"
946 (destructuring-bind (servopts &rest providers) srv
948 (service &key ((:port default-port)) (protocol :tcp))
951 (let ((serv (serv-by-name service protocol)))
952 (setf default-port (and serv (serv-port serv)))))
953 (let ((rname (flet ((prepend (tag tail)
956 :labels (list (format nil "_~(~A~)" tag)))
958 (prepend service (prepend protocol name)))))
959 (dolist (prov providers)
964 (prio *default-mx-priority*)
968 (let ((host (zone-parse-host srvname zname)))
969 (when ip (zone-set-address #'rec ip :name host))
971 :data (list prio weight port host))))))))))
973 (defmethod zone-record-rrdata ((type (eql :srv)) zr)
974 (destructuring-bind (prio weight port host) (zr-data zr)
981 (defzoneparse :net (name data rec)
983 (dolist (net (listify data))
984 (dolist (ipn (net-ipnets (net-must-find net)))
985 (let* ((base (ipnet-net ipn))
986 (rrtype (ipaddr-rrtype base)))
987 (flet ((frob (kind addr)
989 (rec :name (zone-parse-host kind name)
993 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
994 (frob "bcast" (ipnet-broadcast ipn)))))))
996 (defzoneparse (:rev :reverse) (name data rec)
997 ":reverse ((NET &key :prefix-bits :family) ZONE*)
999 Add a reverse record each host in the ZONEs (or all zones) that lies
1001 (setf data (listify data))
1002 (destructuring-bind (net &key prefix-bits (family *address-family*))
1003 (listify (car data))
1005 (dolist (ipn (net-parse-to-ipnets net family))
1006 (let* ((seen (make-hash-table :test #'equal))
1007 (width (ipnet-width ipn))
1008 (frag-len (if prefix-bits (- width prefix-bits)
1009 (ipnet-changeable-bits width (ipnet-mask ipn)))))
1010 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
1011 (dolist (zr (zone-records (zone-find z)))
1012 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
1014 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
1015 (let* ((frag (reverse-domain-fragment (zr-data zr)
1017 (name (domain-name-concat frag name))
1018 (name-string (princ-to-string name)))
1019 (unless (gethash name-string seen)
1020 (rec :name name :type :ptr
1021 :ttl (zr-ttl zr) :data (zr-name zr))
1022 (setf (gethash name-string seen) t))))))))))
1024 (defzoneparse :multi (name data rec :zname zname :ttl ttl)
1025 ":multi (((NET*) &key :start :end :family :suffix) . REC)
1027 Output multiple records covering a portion of the reverse-resolution
1028 namespace corresponding to the particular NETs. The START and END bounds
1029 default to the most significant variable component of the
1030 reverse-resolution domain.
1032 The REC tail is a sequence of record forms (as handled by
1033 `zone-process-records') to be emitted for each covered address. Within
1034 the bodies of these forms, the symbol `*' will be replaced by the
1035 domain-name fragment corresponding to the current host, optionally
1036 followed by the SUFFIX.
1040 (:multi ((delegated-subnet :start 8)
1041 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
1043 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
1046 Obviously, nested `:multi' records won't work well."
1048 (destructuring-bind (nets
1049 &key start end ((:suffix raw-suffix))
1050 (family *address-family*))
1051 (listify (car data))
1052 (let ((suffix (if (not raw-suffix)
1053 (make-domain-name :labels nil :absolutep nil)
1054 (zone-parse-host raw-suffix))))
1055 (dolist (net (listify nets))
1056 (dolist (ipn (net-parse-to-ipnets net family))
1057 (let* ((addr (ipnet-net ipn))
1058 (width (ipaddr-width addr))
1059 (comp-width (reverse-domain-component-width addr))
1060 (end (round-up (or end
1061 (ipnet-changeable-bits width
1064 (start (round-down (or start (- end comp-width))
1066 (map (ipnet-host-map ipn)))
1067 (multiple-value-bind (host-step host-limit)
1068 (ipnet-index-bounds map start end)
1069 (do ((index 0 (+ index host-step)))
1070 ((> index host-limit))
1071 (let* ((addr (ipnet-index-host map index))
1072 (frag (reverse-domain-fragment addr start end))
1073 (target (reduce #'domain-name-concat
1074 (list frag suffix zname)
1076 :initial-value root-domain)))
1077 (dolist (zr (zone-parse-records (domain-name-concat frag
1082 (rec :name (zr-name zr)
1086 :make-ptr-p (zr-make-ptr-p zr))))))))))))
1088 ;;;--------------------------------------------------------------------------
1089 ;;; Zone file output.
1091 (export 'zone-write)
1092 (defgeneric zone-write (format zone stream)
1093 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1095 (defvar *writing-zone* nil
1096 "The zone currently being written.")
1098 (defvar *zone-output-stream* nil
1099 "Stream to write zone data on.")
1101 (export 'zone-write-raw-rrdata)
1102 (defgeneric zone-write-raw-rrdata (format zr type data)
1103 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1105 ZR gives the record object, which carries the name and TTL; the TYPE is
1106 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1107 This is used by the default `zone-write-record' method to handle record
1108 types which aren't directly supported by the format driver."))
1110 (export 'zone-write-header)
1111 (defgeneric zone-write-header (format zone)
1112 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1114 The header includes any kind of initial comment, the SOA record, and any
1115 other necessary preamble. There is no default implementation.
1117 This is part of the protocol used by the default method on `zone-write';
1118 if you override that method."))
1120 (export 'zone-write-trailer)
1121 (defgeneric zone-write-trailer (format zone)
1122 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1124 The footer may be empty, and is so by default.
1126 This is part of the protocol used by the default method on `zone-write';
1127 if you override that method.")
1128 (:method (format zone)
1129 (declare (ignore format zone))
1132 (export 'zone-write-record)
1133 (defgeneric zone-write-record (format type zr)
1134 (:documentation "Emit a record of the given TYPE (a keyword).
1136 The default implementation builds the raw RRDATA and passes it to
1137 `zone-write-raw-rrdata'.")
1138 (:method (format type zr)
1140 (data (build-record (setf code (zone-record-rrdata type zr)))))
1141 (zone-write-raw-rrdata format zr code data))))
1143 (defmethod zone-write (format zone stream)
1144 "This default method calls `zone-write-header', then `zone-write-record'
1145 for each record in the zone, and finally `zone-write-trailer'. While it's
1146 running, `*writing-zone*' is bound to the zone object, and
1147 `*zone-output-stream*' to the output stream."
1148 (let ((*writing-zone* zone)
1149 (*zone-output-stream* stream))
1150 (zone-write-header format zone)
1151 (dolist (zr (zone-records-sorted zone))
1152 (zone-write-record format (zr-type zr) zr))
1153 (zone-write-trailer format zone)))
1156 (defun zone-save (zones &key (format :bind))
1157 "Write the named ZONES to files. If no zones are given, write all the
1160 (setf zones (hash-table-keys *zones*)))
1163 (let ((zz (zone-find z)))
1165 (error "Unknown zone `~A'." z))
1166 (let ((stream (safely-open-output-stream safe
1167 (zone-file-name z :zone))))
1168 (zone-write format zz stream))))))
1170 ;;;--------------------------------------------------------------------------
1171 ;;; Bind format output.
1173 (defvar *bind-last-record-name* nil
1174 "The previously emitted record name.
1176 Used for eliding record names on output.")
1178 (export 'bind-hostname)
1179 (defun bind-hostname (hostname)
1180 (let ((zone (domain-name-labels (zone-name *writing-zone*)))
1181 (name (domain-name-labels hostname)))
1183 (unless (and zone name (string= (car zone) (car name)))
1185 (pop zone) (pop name))
1186 (flet ((stitch (labels absolutep)
1187 (format nil "~{~A~^.~}~@[.~]"
1188 (reverse (mapcar #'quotify-label labels))
1190 (cond (zone (stitch (domain-name-labels hostname) t))
1191 (name (stitch name nil))
1194 (export 'bind-output-hostname)
1195 (defun bind-output-hostname (hostname)
1196 (let ((name (bind-hostname hostname)))
1197 (cond ((and *bind-last-record-name*
1198 (string= name *bind-last-record-name*))
1201 (setf *bind-last-record-name* name)
1204 (defmethod zone-write :around ((format (eql :bind)) zone stream)
1205 (declare (ignorable zone stream))
1206 (let ((*bind-last-record-name* nil))
1207 (call-next-method)))
1209 (defmethod zone-write-header ((format (eql :bind)) zone)
1210 (format *zone-output-stream* "~
1211 ;;; Zone file `~(~A~)'
1217 (iso-date :now :datep t :timep t)
1218 (zone-default-ttl zone))
1219 (let* ((soa (zone-soa zone))
1220 (admin (let* ((name (soa-admin soa))
1221 (at (position #\@ name))
1222 (copy (format nil "~(~A~)." name)))
1224 (setf (char copy at) #\.))
1226 (format *zone-output-stream* "~
1227 ~A~30TIN SOA~40T~A (
1228 ~55@A~60T ;administrator
1229 ~45T~10D~60T ;serial
1230 ~45T~10D~60T ;refresh
1232 ~45T~10D~60T ;expire
1233 ~45T~10D )~60T ;min-ttl~2%"
1234 (bind-output-hostname (zone-name zone))
1235 (bind-hostname (soa-source soa))
1241 (soa-min-ttl soa))))
1243 (export 'bind-format-record)
1244 (defun bind-format-record (zr format &rest args)
1245 (format *zone-output-stream*
1246 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
1247 (bind-output-hostname (zr-name zr))
1248 (let ((ttl (zr-ttl zr)))
1249 (and (/= ttl (zone-default-ttl *writing-zone*))
1251 (string-upcase (symbol-name (zr-type zr)))
1254 (defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1255 (format *zone-output-stream*
1256 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A"
1257 (bind-output-hostname (zr-name zr))
1258 (let ((ttl (zr-ttl zr)))
1259 (and (/= ttl (zone-default-ttl *writing-zone*))
1263 (let* ((hex (with-output-to-string (out)
1264 (dotimes (i (length data))
1265 (format out "~(~2,'0X~)" (aref data i)))))
1268 (format *zone-output-stream* " ~A~%" hex))
1270 (format *zone-output-stream* " (")
1273 (when (>= i len) (return))
1274 (let ((j (min (+ i 64) len)))
1275 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1277 (format *zone-output-stream* " )~%")))))
1279 (defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1280 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1282 (defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1283 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1285 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1286 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1288 (defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1289 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1291 (defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1292 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1294 (defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1295 (bind-format-record zr "~2D ~A"
1297 (bind-hostname (car (zr-data zr)))))
1299 (defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1300 (destructuring-bind (prio weight port host) (zr-data zr)
1301 (bind-format-record zr "~2D ~5D ~5D ~A"
1302 prio weight port (bind-hostname host))))
1304 (defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1305 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1307 (defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1308 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
1310 ;;;--------------------------------------------------------------------------
1311 ;;; tinydns-data output format.
1313 (export 'tinydns-output)
1314 (defun tinydns-output (code &rest fields)
1315 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1317 (defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
1318 (tinydns-output #\: (zr-name zr) type
1319 (with-output-to-string (out)
1320 (dotimes (i (length data))
1321 (let ((byte (aref data i)))
1322 (if (or (<= byte 32)
1324 (member byte '(#\: #\\) :key #'char-code))
1325 (format out "\\~3,'0O" byte)
1326 (write-char (code-char byte) out)))))
1329 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1330 (tinydns-output #\+ (zr-name zr)
1331 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1333 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1334 (tinydns-output #\3 (zr-name zr)
1335 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1338 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1339 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1341 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1342 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1344 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1345 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1347 (defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1348 (let ((name (car (zr-data zr)))
1349 (prio (cdr (zr-data zr))))
1350 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1352 (defmethod zone-write-header ((format (eql :tinydns)) zone)
1353 (format *zone-output-stream* "~
1354 ### Zone file `~(~A~)'
1358 (iso-date :now :datep t :timep t))
1359 (let ((soa (zone-soa zone)))
1363 (let* ((name (copy-seq (soa-admin soa)))
1364 (at (position #\@ name)))
1365 (when at (setf (char name at) #\.))
1371 (zone-default-ttl zone))))
1373 ;;;----- That's all, folks --------------------------------------------------