chiark / gitweb /
zone.lisp: Export `tinydns-output', because it looks handy.
[zone] / zone.lisp
CommitLineData
7e282fb5 1;;; -*-lisp-*-
2;;;
7e282fb5 3;;; DNS zone generation
4;;;
5;;; (c) 2005 Straylight/Edgeware
6;;;
7
8;;;----- Licensing notice ---------------------------------------------------
9;;;
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.
7fff3797 14;;;
7e282fb5 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.
7fff3797 19;;;
7e282fb5 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.
23
fe5fb85a
MW
24;;;--------------------------------------------------------------------------
25;;; Packaging.
26
7e282fb5 27(defpackage #:zone
716105aa
MW
28 (:use #:common-lisp
29 #:mdw.base #:mdw.str #:collect #:safely
32ebbe9b
MW
30 #:net #:services)
31 (:import-from #:net #:round-down #:round-up))
fe5fb85a 32
7e282fb5 33(in-package #:zone)
34
fe5fb85a
MW
35;;;--------------------------------------------------------------------------
36;;; Various random utilities.
37
38(defun to-integer (x)
39 "Convert X to an integer in the most straightforward way."
40 (floor (rational x)))
41
42(defun from-mixed-base (base val)
43 "BASE is a list of the ranges for the `digits' of a mixed-base
2f1d381d 44 representation. Convert VAL, a list of digits, into an integer."
fe5fb85a
MW
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)))
49
50(defun to-mixed-base (base val)
51 "BASE is a list of the ranges for the `digits' of a mixed-base
2f1d381d 52 representation. Convert VAL, an integer, into a list of digits."
fe5fb85a
MW
53 (let ((base (reverse base))
54 (a nil))
55 (loop
56 (unless base
57 (push val a)
58 (return a))
59 (multiple-value-bind (q r) (floor val (pop base))
60 (push r a)
61 (setf val q)))))
62
afa2e2f1 63(export 'timespec-seconds)
fe5fb85a 64(defun timespec-seconds (ts)
f38bc59e
MW
65 "Convert a timespec TS to seconds.
66
f4e0c48f 67 A timespec may be a real count of seconds, or a list (COUNT UNIT). UNIT
f38bc59e 68 may be any of a number of obvious time units."
fe5fb85a
MW
69 (cond ((null ts) 0)
70 ((realp ts) (floor ts))
71 ((atom ts)
72 (error "Unknown timespec format ~A" ts))
73 ((null (cdr ts))
74 (timespec-seconds (car ts)))
75 (t (+ (to-integer (* (car ts)
76 (case (intern (string-upcase
77 (stringify (cadr ts)))
78 '#:zone)
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"
86 (cadr ts))))))
87 (timespec-seconds (cddr ts))))))
88
89(defun hash-table-keys (ht)
90 "Return a list of the keys in hashtable HT."
91 (collecting ()
92 (maphash (lambda (key val) (declare (ignore val)) (collect key)) ht)))
93
94(defun iso-date (&optional time &key datep timep (sep #\ ))
f38bc59e
MW
95 "Construct a textual date or time in ISO format.
96
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."
fe5fb85a
MW
100 (multiple-value-bind
101 (sec min hr day mon yr dow dstp tz)
102 (decode-universal-time (if (or (null time) (eq time :now))
103 (get-universal-time)
104 time))
105 (declare (ignore dow dstp tz))
106 (with-output-to-string (s)
107 (when datep
108 (format s "~4,'0D-~2,'0D-~2,'0D" yr mon day)
109 (when timep
110 (write-char sep s)))
111 (when timep
112 (format s "~2,'0D:~2,'0D:~2,'0D" hr min sec)))))
113
05e83012
MW
114(defun natural-string< (string1 string2
115 &key (start1 0) (end1 nil)
116 (start2 0) (end2 nil))
117 "Answer whether STRING1 precedes STRING2 in a vaguely natural ordering.
118
119 In particular, digit sequences are handled in a moderately sensible way.
120 Split the strings into maximally long alternating sequences of non-numeric
121 and numeric characters, such that the non-numeric sequences are
122 non-empty. Compare these lexicographically; numeric sequences order
123 according to their integer values, non-numeric sequences in the usual
124 lexicographic ordering.
125
126 Returns two values: whether STRING1 strictly precedes STRING2, and whether
127 STRING1 strictly follows STRING2."
128
129 (let ((end1 (or end1 (length string1)))
130 (end2 (or end2 (length string2))))
131 (loop
132 (cond ((>= start1 end1)
133 (let ((eqp (>= start2 end2)))
134 (return (values (not eqp) nil))))
135 ((>= start2 end2)
136 (return (values nil t)))
137 ((and (digit-char-p (char string1 start1))
138 (digit-char-p (char string2 start2)))
139 (let* ((lim1 (or (position-if-not #'digit-char-p string1
140 :start start1 :end end1)
141 end1))
142 (n1 (parse-integer string1 :start start1 :end lim1))
143 (lim2 (or (position-if-not #'digit-char-p string2
144 :start start2 :end end2)
145 end2))
146 (n2 (parse-integer string2 :start start2 :end lim2)))
147 (cond ((< n1 n2) (return (values t nil)))
148 ((> n1 n2) (return (values nil t))))
149 (setf start1 lim1
150 start2 lim2)))
151 (t
152 (let ((lim1 (or (position-if #'digit-char-p string1
153 :start start1 :end end1)
154 end1))
155 (lim2 (or (position-if #'digit-char-p string2
156 :start start2 :end end2)
157 end2)))
158 (cond ((string< string1 string2
159 :start1 start1 :end1 lim1
160 :start2 start2 :end2 lim2)
161 (return (values t nil)))
162 ((string> string1 string2
163 :start1 start1 :end1 lim1
164 :start2 start2 :end2 lim2)
165 (return (values nil t))))
166 (setf start1 lim1
167 start2 lim2)))))))
168
169(defun domain-name< (name-a name-b)
170 "Answer whether NAME-A precedes NAME-B in an ordering of domain names.
171
172 Split the names into labels at the dots, and then lexicographically
173 compare the sequences of labels, right to left, using `natural-string<'.
174
175 Returns two values: whether NAME-A strictly precedes NAME-B, and whether
176 NAME-A strictly follows NAME-B."
177 (let ((pos-a (length name-a))
178 (pos-b (length name-b)))
179 (loop (let ((dot-a (or (position #\. name-a
180 :from-end t :end pos-a)
181 -1))
182 (dot-b (or (position #\. name-b
183 :from-end t :end pos-b)
184 -1)))
185 (multiple-value-bind (precp follp)
186 (natural-string< name-a name-b
187 :start1 (1+ dot-a) :end1 pos-a
188 :start2 (1+ dot-b) :end2 pos-b)
189 (cond (precp
190 (return (values t nil)))
191 (follp
192 (return (values nil t)))
193 ((= dot-a -1)
194 (let ((eqp (= dot-b -1)))
195 (return (values (not eqp) nil))))
196 ((= dot-b -1)
197 (return (values nil t)))
198 (t
199 (setf pos-a dot-a
200 pos-b dot-b))))))))
201
fe5fb85a
MW
202;;;--------------------------------------------------------------------------
203;;; Zone types.
7e282fb5 204
afa2e2f1 205(export 'soa)
7e282fb5 206(defstruct (soa (:predicate soap))
207 "Start-of-authority record information."
208 source
209 admin
210 refresh
211 retry
212 expire
213 min-ttl
214 serial)
fe5fb85a 215
afa2e2f1 216(export 'mx)
7e282fb5 217(defstruct (mx (:predicate mxp))
218 "Mail-exchange record information."
219 priority
220 domain)
fe5fb85a 221
afa2e2f1 222(export 'zone)
7e282fb5 223(defstruct (zone (:predicate zonep))
224 "Zone information."
225 soa
226 default-ttl
227 name
228 records)
229
fe5fb85a
MW
230;;;--------------------------------------------------------------------------
231;;; Zone defaults. It is intended that scripts override these.
232
afa2e2f1 233(export '*default-zone-source*)
7e282fb5 234(defvar *default-zone-source*
8e7c1366 235 (let ((hn (gethostname)))
8a4f9a18 236 (and hn (concatenate 'string (canonify-hostname hn) ".")))
7e282fb5 237 "The default zone source: the current host's name.")
fe5fb85a 238
afa2e2f1 239(export '*default-zone-refresh*)
7e282fb5 240(defvar *default-zone-refresh* (* 24 60 60)
241 "Default zone refresh interval: one day.")
fe5fb85a 242
afa2e2f1 243(export '*default-zone-admin*)
7e282fb5 244(defvar *default-zone-admin* nil
245 "Default zone administrator's email address.")
fe5fb85a 246
afa2e2f1 247(export '*default-zone-retry*)
7e282fb5 248(defvar *default-zone-retry* (* 60 60)
249 "Default znoe retry interval: one hour.")
fe5fb85a 250
afa2e2f1 251(export '*default-zone-expire*)
7e282fb5 252(defvar *default-zone-expire* (* 14 24 60 60)
253 "Default zone expiry time: two weeks.")
fe5fb85a 254
afa2e2f1 255(export '*default-zone-min-ttl*)
7e282fb5 256(defvar *default-zone-min-ttl* (* 4 60 60)
257 "Default zone minimum TTL/negative TTL: four hours.")
fe5fb85a 258
afa2e2f1 259(export '*default-zone-ttl*)
7e282fb5 260(defvar *default-zone-ttl* (* 8 60 60)
261 "Default zone TTL (for records without explicit TTLs): 8 hours.")
fe5fb85a 262
afa2e2f1 263(export '*default-mx-priority*)
7e282fb5 264(defvar *default-mx-priority* 50
265 "Default MX priority.")
266
fe5fb85a
MW
267;;;--------------------------------------------------------------------------
268;;; Zone variables and structures.
269
7e282fb5 270(defvar *zones* (make-hash-table :test #'equal)
271 "Map of known zones.")
fe5fb85a 272
afa2e2f1 273(export 'zone-find)
7e282fb5 274(defun zone-find (name)
275 "Find a zone given its NAME."
276 (gethash (string-downcase (stringify name)) *zones*))
277(defun (setf zone-find) (zone name)
278 "Make the zone NAME map to ZONE."
279 (setf (gethash (string-downcase (stringify name)) *zones*) zone))
280
afa2e2f1 281(export 'zone-record)
7e282fb5 282(defstruct (zone-record (:conc-name zr-))
283 "A zone record."
284 (name '<unnamed>)
285 ttl
286 type
590ad961 287 (make-ptr-p nil)
7e282fb5 288 data)
289
afa2e2f1 290(export 'zone-subdomain)
7e282fb5 291(defstruct (zone-subdomain (:conc-name zs-))
f4e0c48f
MW
292 "A subdomain.
293
294 Slightly weird. Used internally by `zone-process-records', and shouldn't
295 escape."
7e282fb5 296 name
297 ttl
298 records)
299
afa2e2f1 300(export '*zone-output-path*)
3d7852d9
MW
301(defvar *zone-output-path* nil
302 "Pathname defaults to merge into output files.
303
304 If this is nil then use the prevailing `*default-pathname-defaults*'.
305 This is not the same as capturing the `*default-pathname-defaults*' from
306 load time.")
ab87c7bf 307
afa2e2f1 308(export '*preferred-subnets*)
8ce7eb9b
MW
309(defvar *preferred-subnets* nil
310 "Subnets to prefer when selecting defaults.")
311
fe5fb85a
MW
312;;;--------------------------------------------------------------------------
313;;; Zone infrastructure.
314
ab87c7bf
MW
315(defun zone-file-name (zone type)
316 "Choose a file name for a given ZONE and TYPE."
317 (merge-pathnames (make-pathname :name (string-downcase zone)
318 :type (string-downcase type))
3d7852d9 319 (or *zone-output-path* *default-pathname-defaults*)))
ab87c7bf 320
afa2e2f1 321(export 'zone-preferred-subnet-p)
8ce7eb9b
MW
322(defun zone-preferred-subnet-p (name)
323 "Answer whether NAME (a string or symbol) names a preferred subnet."
324 (member name *preferred-subnets* :test #'string-equal))
325
afa2e2f1 326(export 'preferred-subnet-case)
8bd2576e 327(defmacro preferred-subnet-case (&body clauses)
f4e0c48f 328 "Execute a form based on which networks are considered preferred.
f38bc59e 329
f4e0c48f
MW
330 The CLAUSES have the form (SUBNETS . FORMS) -- evaluate the first FORMS
331 whose SUBNETS (a list or single symbol, not evaluated) are listed in
332 `*preferred-subnets*'. If SUBNETS is the symbol `t' then the clause
333 always matches."
8bd2576e
MW
334 `(cond
335 ,@(mapcar (lambda (clause)
336 (let ((subnets (car clause)))
337 (cons (cond ((eq subnets t)
338 t)
339 ((listp subnets)
340 `(or ,@(mapcar (lambda (subnet)
341 `(zone-preferred-subnet-p
342 ',subnet))
343 subnets)))
344 (t
345 `(zone-preferred-subnet-p ',subnets)))
346 (cdr clause))))
347 clauses)))
348
32ebbe9b
MW
349(export 'zone-parse-host)
350(defun zone-parse-host (f zname)
351 "Parse a host name F.
352
353 If F ends in a dot then it's considered absolute; otherwise it's relative
354 to ZNAME."
355 (setf f (stringify f))
356 (cond ((string= f "@") (stringify zname))
357 ((and (plusp (length f))
358 (char= (char f (1- (length f))) #\.))
359 (string-downcase (subseq f 0 (1- (length f)))))
360 (t (string-downcase (concatenate 'string f "."
361 (stringify zname))))))
362
363(export 'zone-make-name)
364(defun zone-make-name (prefix zone-name)
365 "Compute a full domain name from a PREFIX and a ZONE-NAME.
366
367 If the PREFIX ends with `.' then it's absolute already; otherwise, append
368 the ZONE-NAME, separated with a `.'. If PREFIX is nil, or `@', then
369 return the ZONE-NAME only."
370 (if (or (not prefix) (string= prefix "@"))
371 zone-name
372 (let ((len (length prefix)))
373 (if (or (zerop len) (char/= (char prefix (1- len)) #\.))
374 (join-strings #\. (list prefix zone-name))
375 prefix))))
376
aac45ff7
MW
377(export 'zone-records-sorted)
378(defun zone-records-sorted (zone)
379 "Return the ZONE's records, in a pleasant sorted order."
380 (sort (copy-seq (zone-records zone))
381 (lambda (zr-a zr-b)
05e83012
MW
382 (multiple-value-bind (precp follp)
383 (domain-name< (zr-name zr-a) (zr-name zr-b))
384 (cond (precp t)
385 (follp nil)
386 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
aac45ff7 387
32ebbe9b
MW
388;;;--------------------------------------------------------------------------
389;;; Serial numbering.
390
391(export 'make-zone-serial)
392(defun make-zone-serial (name)
393 "Given a zone NAME, come up with a new serial number.
394
395 This will (very carefully) update a file ZONE.serial in the current
396 directory."
397 (let* ((file (zone-file-name name :serial))
398 (last (with-open-file (in file
399 :direction :input
400 :if-does-not-exist nil)
401 (if in (read in)
402 (list 0 0 0 0))))
403 (now (multiple-value-bind
404 (sec min hr dy mon yr dow dstp tz)
405 (get-decoded-time)
406 (declare (ignore sec min hr dow dstp tz))
407 (list dy mon yr)))
408 (seq (cond ((not (equal now (cdr last))) 0)
409 ((< (car last) 99) (1+ (car last)))
410 (t (error "Run out of sequence numbers for ~A" name)))))
411 (safely-writing (out file)
412 (format out
413 ";; Serial number file for zone ~A~%~
414 ;; (LAST-SEQ DAY MONTH YEAR)~%~
415 ~S~%"
416 name
417 (cons seq now)))
418 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
419
420;;;--------------------------------------------------------------------------
421;;; Zone form parsing.
422
7e282fb5 423(defun zone-process-records (rec ttl func)
f38bc59e
MW
424 "Sort out the list of records in REC, calling FUNC for each one.
425
baad8564
MW
426 TTL is the default time-to-live for records which don't specify one.
427
f4e0c48f
MW
428 REC is a list of records of the form
429
430 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
431
432 The various kinds of entries have the following meanings.
433
434 :ttl TTL Set the TTL for subsequent records (at this level of
435 nesting only).
436
437 TYPE DATA Define a record with a particular TYPE and DATA.
438 Record types are defined using `defzoneparse' and
439 the syntax of the data is idiosyncratic.
440
441 ((LABEL ...) . REC) Define records for labels within the zone. Any
442 records defined within REC will have their domains
443 prefixed by each of the LABELs. A singleton list
444 of labels may instead be written as a single
445 label. Note, therefore, that
446
447 (host (sub :a \"169.254.1.1\"))
baad8564 448
f4e0c48f 449 defines a record for `host.sub' -- not `sub.host'.
baad8564 450
f4e0c48f
MW
451 If REC contains no top-level records, but it does define records for a
452 label listed in `*preferred-subnets*', then the records for the first such
453 label are also promoted to top-level.
baad8564 454
f4e0c48f
MW
455 The FUNC is called for each record encountered, represented as a
456 `zone-record' object. Zone parsers are not called: you get the record
457 types and data from the input form; see `zone-parse-records' if you want
458 the raw output."
baad8564 459
7e282fb5 460 (labels ((sift (rec ttl)
f4e0c48f
MW
461 ;; Parse the record list REC into lists of `zone-record' and
462 ;; `zone-subdomain' objects, sorting out TTLs and so on.
463 ;; Returns them as two values.
464
7e282fb5 465 (collecting (top sub)
466 (loop
467 (unless rec
468 (return))
469 (let ((r (pop rec)))
470 (cond ((eq r :ttl)
471 (setf ttl (pop rec)))
472 ((symbolp r)
473 (collect (make-zone-record :type r
474 :ttl ttl
475 :data (pop rec))
476 top))
477 ((listp r)
478 (dolist (name (listify (car r)))
479 (collect (make-zone-subdomain :name name
480 :ttl ttl
481 :records (cdr r))
482 sub)))
483 (t
484 (error "Unexpected record form ~A" (car r))))))))
f4e0c48f 485
4e7e3780 486 (process (rec dom ttl)
f4e0c48f
MW
487 ;; Recursirvely process the record list REC, with a list DOM of
488 ;; prefix labels, and a default TTL. Promote records for a
489 ;; preferred subnet to toplevel if there are no toplevel records
490 ;; already.
491
7e282fb5 492 (multiple-value-bind (top sub) (sift rec ttl)
493 (if (and dom (null top) sub)
64e34a97
MW
494 (let ((preferred
495 (or (find-if (lambda (s)
496 (some #'zone-preferred-subnet-p
497 (listify (zs-name s))))
498 sub)
499 (car sub))))
8ce7eb9b
MW
500 (when preferred
501 (process (zs-records preferred)
502 dom
503 (zs-ttl preferred))))
504 (let ((name (and dom
505 (string-downcase
506 (join-strings #\. (reverse dom))))))
507 (dolist (zr top)
508 (setf (zr-name zr) name)
509 (funcall func zr))))
7e282fb5 510 (dolist (s sub)
511 (process (zs-records s)
512 (cons (zs-name s) dom)
4e7e3780 513 (zs-ttl s))))))
f4e0c48f
MW
514
515 ;; Process the records we're given with no prefix.
4e7e3780 516 (process rec nil ttl)))
7e282fb5 517
7e282fb5 518(defun zone-parse-head (head)
f38bc59e
MW
519 "Parse the HEAD of a zone form.
520
521 This has the form
7e282fb5 522
523 (NAME &key :source :admin :refresh :retry
b23c65ee 524 :expire :min-ttl :ttl :serial)
7e282fb5 525
2f1d381d
MW
526 though a singleton NAME needn't be a list. Returns the default TTL and an
527 soa structure representing the zone head."
7e282fb5 528 (destructuring-bind
529 (zname
530 &key
8a4f9a18 531 (source *default-zone-source*)
7e282fb5 532 (admin (or *default-zone-admin*
533 (format nil "hostmaster@~A" zname)))
534 (refresh *default-zone-refresh*)
535 (retry *default-zone-retry*)
536 (expire *default-zone-expire*)
537 (min-ttl *default-zone-min-ttl*)
538 (ttl min-ttl)
539 (serial (make-zone-serial zname)))
540 (listify head)
babb8dd2 541 (values (string-downcase zname)
7e282fb5 542 (timespec-seconds ttl)
543 (make-soa :admin admin
544 :source (zone-parse-host source zname)
545 :refresh (timespec-seconds refresh)
546 :retry (timespec-seconds retry)
547 :expire (timespec-seconds expire)
548 :min-ttl (timespec-seconds min-ttl)
549 :serial serial))))
550
afa2e2f1 551(export 'defzoneparse)
7e282fb5 552(defmacro defzoneparse (types (name data list
5bf80328 553 &key (prefix (gensym "PREFIX"))
b23c65ee
MW
554 (zname (gensym "ZNAME"))
555 (ttl (gensym "TTL")))
7e282fb5 556 &body body)
f38bc59e
MW
557 "Define a new zone record type.
558
f4e0c48f
MW
559 The arguments are as follows:
560
561 TYPES A singleton type symbol, or a list of aliases.
fe5fb85a 562
2f1d381d 563 NAME The name of the record to be added.
fe5fb85a 564
2f1d381d 565 DATA The content of the record to be added (a single object,
7fff3797 566 unevaluated).
fe5fb85a 567
2f1d381d 568 LIST A function to add a record to the zone. See below.
fe5fb85a 569
5bf80328
MW
570 PREFIX The prefix tag used in the original form.
571
2f1d381d 572 ZNAME The name of the zone being constructed.
fe5fb85a 573
2f1d381d 574 TTL The TTL for this record.
fe5fb85a 575
5bf80328
MW
576 You get to choose your own names for these. ZNAME, PREFIX and TTL are
577 optional: you don't have to accept them if you're not interested.
fe5fb85a 578
2f1d381d
MW
579 The LIST argument names a function to be bound in the body to add a new
580 low-level record to the zone. It has the prototype
fe5fb85a 581
590ad961 582 (LIST &key :name :type :data :ttl :make-ptr-p)
fe5fb85a 583
590ad961
MW
584 These (except MAKE-PTR-P, which defaults to nil) default to the above
585 arguments (even if you didn't accept the arguments)."
7e282fb5 586 (setf types (listify types))
587 (let* ((type (car types))
588 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
2ec279f5 589 (with-parsed-body (body decls doc) body
590ad961 590 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
40ded1b8
MW
591 `(progn
592 (dolist (,i ',types)
593 (setf (get ,i 'zone-parse) ',func))
5bf80328 594 (defun ,func (,prefix ,zname ,data ,ttl ,col)
40ded1b8
MW
595 ,@doc
596 ,@decls
5bf80328
MW
597 (let ((,name (zone-make-name ,prefix ,zname)))
598 (flet ((,list (&key ((:name ,tname) ,name)
599 ((:type ,ttype) ,type)
600 ((:data ,tdata) ,data)
590ad961
MW
601 ((:ttl ,tttl) ,ttl)
602 ((:make-ptr-p ,tmakeptrp) nil))
f4decf40 603 #+cmu (declare (optimize ext:inhibit-warnings))
5bf80328
MW
604 (collect (make-zone-record :name ,tname
605 :type ,ttype
606 :data ,tdata
590ad961
MW
607 :ttl ,tttl
608 :make-ptr-p ,tmakeptrp)
5bf80328
MW
609 ,col)))
610 ,@body)))
f4e0c48f 611 ',type)))))
7e282fb5 612
8fcf1ae3
MW
613(export 'zone-parse-records)
614(defun zone-parse-records (zname ttl records)
615 "Parse a sequence of RECORDS and return a list of raw records.
616
617 The records are parsed relative to the zone name ZNAME, and using the
618 given default TTL."
619 (collecting (rec)
620 (flet ((parse-record (zr)
621 (let ((func (or (get (zr-type zr) 'zone-parse)
622 (error "No parser for record ~A."
623 (zr-type zr))))
624 (name (and (zr-name zr) (stringify (zr-name zr)))))
625 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
626 (zone-process-records records ttl #'parse-record))))
7e282fb5 627
afa2e2f1 628(export 'zone-parse)
7e282fb5 629(defun zone-parse (zf)
f38bc59e
MW
630 "Parse a ZONE form.
631
f4e0c48f 632 The syntax of a zone form is as follows:
7e282fb5 633
2f1d381d
MW
634 ZONE-FORM:
635 ZONE-HEAD ZONE-RECORD*
7e282fb5 636
2f1d381d
MW
637 ZONE-RECORD:
638 ((NAME*) ZONE-RECORD*)
639 | SYM ARGS"
7e282fb5 640 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
8fcf1ae3
MW
641 (make-zone :name zname
642 :default-ttl ttl
643 :soa soa
644 :records (zone-parse-records zname ttl (cdr zf)))))
7e282fb5 645
afa2e2f1 646(export 'zone-create)
fe5fb85a
MW
647(defun zone-create (zf)
648 "Zone construction function. Given a zone form ZF, construct the zone and
2f1d381d 649 add it to the table."
fe5fb85a
MW
650 (let* ((zone (zone-parse zf))
651 (name (zone-name zone)))
652 (setf (zone-find name) zone)
653 name))
654
afa2e2f1 655(export 'defzone)
32ebbe9b 656(defmacro defzone (soa &body zf)
fe5fb85a
MW
657 "Zone definition macro."
658 `(zone-create '(,soa ,@zf)))
659
32ebbe9b
MW
660(export '*address-family*)
661(defvar *address-family* t
662 "The default address family. This is bound by `defrevzone'.")
663
afa2e2f1 664(export 'defrevzone)
32ebbe9b 665(defmacro defrevzone (head &body zf)
fe5fb85a 666 "Define a reverse zone, with the correct name."
32ebbe9b
MW
667 (destructuring-bind (nets &rest args
668 &key &allow-other-keys
669 (family '*address-family*)
670 prefix-bits)
fe5fb85a 671 (listify head)
32ebbe9b
MW
672 (with-gensyms (ipn)
673 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
674 (let ((*address-family* (ipnet-family ,ipn)))
675 (zone-create `((,(reverse-domain ,ipn ,prefix-bits)
676 ,@',(loop for (k v) on args by #'cddr
677 unless (member k
678 '(:family :prefix-bits))
679 nconc (list k v)))
680 ,@',zf)))))))
681
7c34d08c 682(export 'map-host-addresses)
32ebbe9b
MW
683(defun map-host-addresses (func addr &key (family *address-family*))
684 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
685
686 (dolist (a (host-addrs (host-parse addr family)))
687 (funcall func a)))
688
7c34d08c 689(export 'do-host)
32ebbe9b
MW
690(defmacro do-host ((addr spec &key (family *address-family*)) &body body)
691 "Evaluate BODY, binding ADDR to each address denoted by SPEC."
692 `(dolist (,addr (host-addrs (host-parse ,spec ,family)))
693 ,@body))
694
695(export 'zone-set-address)
696(defun zone-set-address (rec addrspec &rest args
697 &key (family *address-family*) name ttl make-ptr-p)
698 "Write records (using REC) defining addresses for ADDRSPEC."
699 (declare (ignore name ttl make-ptr-p))
700 (let ((key-args (loop for (k v) on args by #'cddr
701 unless (eq k :family)
702 nconc (list k v))))
703 (do-host (addr addrspec :family family)
704 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
fe5fb85a 705
9f408c60
MW
706;;;--------------------------------------------------------------------------
707;;; Building raw record vectors.
708
709(defvar *record-vector* nil
710 "The record vector under construction.")
711
712(defun rec-ensure (n)
713 "Ensure that at least N octets are spare in the current record."
714 (let ((want (+ n (fill-pointer *record-vector*)))
715 (have (array-dimension *record-vector* 0)))
716 (unless (<= want have)
717 (adjust-array *record-vector*
718 (do ((new (* 2 have) (* 2 new)))
719 ((<= want new) new))))))
720
721(export 'rec-byte)
722(defun rec-byte (octets value)
723 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
724 (rec-ensure octets)
725 (do ((i (1- octets) (1- i)))
726 ((minusp i))
727 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
728
729(export 'rec-u8)
730(defun rec-u8 (value)
731 "Append an 8-bit VALUE to the current record."
732 (rec-byte 1 value))
733
734(export 'rec-u16)
735(defun rec-u16 (value)
736 "Append a 16-bit VALUE to the current record."
737 (rec-byte 2 value))
738
739(export 'rec-u32)
740(defun rec-u32 (value)
741 "Append a 32-bit VALUE to the current record."
742 (rec-byte 4 value))
743
744(export 'rec-raw-string)
745(defun rec-raw-string (s &key (start 0) end)
746 "Append (a (substring of) a raw string S to the current record.
747
748 No arrangement is made for reporting the length of the string. That must
749 be done by the caller, if necessary."
750 (setf-default end (length s))
751 (rec-ensure (- end start))
752 (do ((i start (1+ i)))
753 ((>= i end))
754 (vector-push (char-code (char s i)) *record-vector*)))
755
756(export 'rec-string)
757(defun rec-string (s &key (start 0) end (max 255))
758 (let* ((end (or end (length s)))
759 (len (- end start)))
760 (unless (<= len max)
761 (error "String `~A' too long" (subseq s start end)))
762 (rec-u8 (- end start))
763 (rec-raw-string s :start start :end end)))
764
765(export 'rec-name)
766(defun rec-name (s)
767 "Append a domain name S.
768
769 No attempt is made to perform compression of the name."
770 (let ((i 0) (n (length s)))
771 (loop (let* ((dot (position #\. s :start i))
772 (lim (or dot n)))
773 (rec-string s :start i :end lim :max 63)
774 (if dot
775 (setf i (1+ dot))
776 (return))))
777 (when (< i n)
778 (rec-u8 0))))
779
780(export 'build-record)
781(defmacro build-record (&body body)
782 "Build a raw record, and return it as a vector of octets."
783 `(let ((*record-vector* (make-array 256
784 :element-type '(unsigned-byte 8)
785 :fill-pointer 0
786 :adjustable t)))
787 ,@body
788 (copy-seq *record-vector*)))
789
790(export 'zone-record-rrdata)
791(defgeneric zone-record-rrdata (type zr)
792 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
793
794 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
795 code."))
796
fe5fb85a
MW
797;;;--------------------------------------------------------------------------
798;;; Zone record parsers.
799
4e7e3780 800(defzoneparse :a (name data rec)
7e282fb5 801 ":a IPADDR"
32ebbe9b
MW
802 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
803
9f408c60
MW
804(defmethod zone-record-rrdata ((type (eql :a)) zr)
805 (rec-u32 (ipaddr-addr (zr-data zr)))
806 1)
807
a2267e14
MW
808(defzoneparse :aaaa (name data rec)
809 ":aaaa IPADDR"
810 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
811
9f408c60
MW
812(defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
813 (rec-byte 16 (ipaddr-addr (zr-data zr)))
814 28)
815
32ebbe9b
MW
816(defzoneparse :addr (name data rec)
817 ":addr IPADDR"
818 (zone-set-address #'rec data :make-ptr-p t))
590ad961
MW
819
820(defzoneparse :svc (name data rec)
821 ":svc IPADDR"
32ebbe9b 822 (zone-set-address #'rec data))
fe5fb85a 823
7e282fb5 824(defzoneparse :ptr (name data rec :zname zname)
825 ":ptr HOST"
826 (rec :data (zone-parse-host data zname)))
fe5fb85a 827
9f408c60
MW
828(defmethod zone-record-rrdata ((type (eql :ptr)) zr)
829 (rec-name (zr-data zr))
830 12)
831
7e282fb5 832(defzoneparse :cname (name data rec :zname zname)
833 ":cname HOST"
834 (rec :data (zone-parse-host data zname)))
fe5fb85a 835
9f408c60
MW
836(defmethod zone-record-rrdata ((type (eql :cname)) zr)
837 (rec-name (zr-data zr))
838 5)
839
90022a23 840(defzoneparse :txt (name data rec)
4ea82aba
MW
841 ":txt (TEXT*)"
842 (rec :data (listify data)))
90022a23 843
9f408c60
MW
844(defmethod zone-record-rrdata ((type (eql :txt)) zr)
845 (mapc #'rec-string (zr-data zr))
846 16)
847
f760c73a
MW
848(export '*dkim-pathname-defaults*)
849(defvar *dkim-pathname-defaults*
850 (make-pathname :directory '(:relative "keys")
851 :type "dkim"))
852
75f39e1a
MW
853(defzoneparse :dkim (name data rec)
854 ":dkim (KEYFILE {:TAG VALUE}*)"
855 (destructuring-bind (file &rest plist) (listify data)
856 (let ((things nil) (out nil))
857 (labels ((flush ()
858 (when out
859 (push (get-output-stream-string out) things)
860 (setf out nil)))
861 (emit (text)
862 (let ((len (length text)))
863 (when (and out (> (+ (file-position out)
864 (length text))
865 64))
866 (flush))
867 (when (plusp len)
868 (cond ((< len 64)
869 (unless out (setf out (make-string-output-stream)))
870 (write-string text out))
871 (t
872 (do ((i 0 j)
873 (j 64 (+ j 64)))
874 ((>= i len))
875 (push (subseq text i (min j len)) things))))))))
876 (do ((p plist (cddr p)))
877 ((endp p))
878 (emit (format nil "~(~A~)=~A;" (car p) (cadr p))))
879 (emit (with-output-to-string (out)
880 (write-string "p=" out)
881 (when file
f760c73a
MW
882 (with-open-file
883 (in (merge-pathnames file *dkim-pathname-defaults*))
75f39e1a
MW
884 (loop
885 (when (string= (read-line in)
886 "-----BEGIN PUBLIC KEY-----")
887 (return)))
888 (loop
889 (let ((line (read-line in)))
890 (if (string= line "-----END PUBLIC KEY-----")
891 (return)
892 (write-string line out)))))))))
893 (rec :type :txt
894 :data (nreverse things)))))
895
f1d7d492
MW
896(eval-when (:load-toplevel :execute)
897 (dolist (item '((sshfp-algorithm rsa 1)
898 (sshfp-algorithm dsa 2)
899 (sshfp-algorithm ecdsa 3)
900 (sshfp-type sha-1 1)
901 (sshfp-type sha-256 2)))
902 (destructuring-bind (prop sym val) item
903 (setf (get sym prop) val)
904 (export sym))))
905
f760c73a
MW
906(export '*sshfp-pathname-defaults*)
907(defvar *sshfp-pathname-defaults*
908 (make-pathname :directory '(:relative "keys")
909 :type "sshfp"))
910
f1d7d492
MW
911(defzoneparse :sshfp (name data rec)
912 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
913 (if (stringp data)
f760c73a 914 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
f1d7d492
MW
915 (loop (let ((line (read-line in nil)))
916 (unless line (return))
917 (let ((words (str-split-words line)))
918 (pop words)
919 (when (string= (car words) "IN") (pop words))
920 (unless (and (string= (car words) "SSHFP")
921 (= (length words) 4))
922 (error "Invalid SSHFP record."))
923 (pop words)
924 (destructuring-bind (alg type fpr) words
925 (rec :data (list (parse-integer alg)
926 (parse-integer type)
927 fpr)))))))
928 (flet ((lookup (what prop)
929 (etypecase what
930 (fixnum what)
931 (symbol (or (get what prop)
932 (error "~S is not a known ~A" what prop))))))
48608192
MW
933 (dolist (item (listify data))
934 (destructuring-bind (fpr &key (alg 'rsa) (type 'sha-1))
935 (listify item)
936 (rec :data (list (lookup alg 'sshfp-algorithm)
937 (lookup type 'sshfp-type)
938 fpr)))))))
f1d7d492 939
9f408c60
MW
940(defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
941 (destructuring-bind (alg type fpr) (zr-data zr)
942 (rec-u8 alg)
943 (rec-u8 type)
944 (do ((i 0 (+ i 2))
945 (n (length fpr)))
946 ((>= i n))
947 (rec-u8 (parse-integer fpr :start i :end (+ i 2) :radix 16))))
948 44)
949
7e282fb5 950(defzoneparse :mx (name data rec :zname zname)
951 ":mx ((HOST :prio INT :ip IPADDR)*)"
952 (dolist (mx (listify data))
953 (destructuring-bind
954 (mxname &key (prio *default-mx-priority*) ip)
955 (listify mx)
956 (let ((host (zone-parse-host mxname zname)))
32ebbe9b 957 (when ip (zone-set-address #'rec ip :name host))
7e282fb5 958 (rec :data (cons host prio))))))
fe5fb85a 959
9f408c60
MW
960(defmethod zone-record-rrdata ((type (eql :mx)) zr)
961 (let ((name (car (zr-data zr)))
962 (prio (cdr (zr-data zr))))
963 (rec-u16 prio)
964 (rec-name name))
965 15)
966
7e282fb5 967(defzoneparse :ns (name data rec :zname zname)
968 ":ns ((HOST :ip IPADDR)*)"
969 (dolist (ns (listify data))
970 (destructuring-bind
971 (nsname &key ip)
972 (listify ns)
973 (let ((host (zone-parse-host nsname zname)))
32ebbe9b 974 (when ip (zone-set-address #'rec ip :name host))
7e282fb5 975 (rec :data host)))))
fe5fb85a 976
9f408c60
MW
977(defmethod zone-record-rrdata ((type (eql :ns)) zr)
978 (rec-name (zr-data zr))
979 2)
980
7e282fb5 981(defzoneparse :alias (name data rec :zname zname)
982 ":alias (LABEL*)"
983 (dolist (a (listify data))
984 (rec :name (zone-parse-host a zname)
985 :type :cname
986 :data name)))
fe5fb85a 987
716105aa
MW
988(defzoneparse :srv (name data rec :zname zname)
989 ":srv (((SERVICE &key :port) (PROVIDER &key :port :prio :weight :ip)*)*)"
990 (dolist (srv data)
991 (destructuring-bind (servopts &rest providers) srv
992 (destructuring-bind
993 (service &key ((:port default-port)) (protocol :tcp))
994 (listify servopts)
995 (unless default-port
996 (let ((serv (serv-by-name service protocol)))
997 (setf default-port (and serv (serv-port serv)))))
998 (let ((rname (format nil "~(_~A._~A~).~A" service protocol name)))
999 (dolist (prov providers)
1000 (destructuring-bind
1001 (srvname
1002 &key
1003 (port default-port)
1004 (prio *default-mx-priority*)
1005 (weight 0)
1006 ip)
1007 (listify prov)
1008 (let ((host (zone-parse-host srvname zname)))
32ebbe9b 1009 (when ip (zone-set-address #'rec ip :name host))
716105aa
MW
1010 (rec :name rname
1011 :data (list prio weight port host))))))))))
1012
9f408c60
MW
1013(defmethod zone-record-rrdata ((type (eql :srv)) zr)
1014 (destructuring-bind (prio weight port host) (zr-data zr)
1015 (rec-u16 prio)
1016 (rec-u16 weight)
1017 (rec-u16 port)
1018 (rec-name host))
1019 33)
1020
a15288b4 1021(defzoneparse :net (name data rec)
1022 ":net (NETWORK*)"
1023 (dolist (net (listify data))
32ebbe9b
MW
1024 (dolist (ipn (net-ipnets (net-must-find net)))
1025 (let* ((base (ipnet-net ipn))
1026 (rrtype (ipaddr-rrtype base)))
1027 (flet ((frob (kind addr)
1028 (when addr
1029 (rec :name (zone-parse-host kind name)
1030 :type rrtype
1031 :data addr))))
1032 (frob "net" base)
1033 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
1034 (frob "bcast" (ipnet-broadcast ipn)))))))
7fff3797 1035
7e282fb5 1036(defzoneparse (:rev :reverse) (name data rec)
32ebbe9b 1037 ":reverse ((NET &key :prefix-bits :family) ZONE*)
679775ba
MW
1038
1039 Add a reverse record each host in the ZONEs (or all zones) that lies
32ebbe9b 1040 within NET."
7e282fb5 1041 (setf data (listify data))
32ebbe9b
MW
1042 (destructuring-bind (net &key prefix-bits (family *address-family*))
1043 (listify (car data))
1044
1045 (dolist (ipn (net-parse-to-ipnets net family))
1046 (let* ((seen (make-hash-table :test #'equal))
1047 (width (ipnet-width ipn))
1048 (frag-len (if prefix-bits (- width prefix-bits)
1049 (ipnet-changeable-bits width (ipnet-mask ipn)))))
1050 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
1051 (dolist (zr (zone-records (zone-find z)))
1052 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
1053 (zr-make-ptr-p zr)
1054 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
1055 (let* ((frag (reverse-domain-fragment (zr-data zr)
1056 0 frag-len))
1057 (name (concatenate 'string frag "." name)))
1058 (unless (gethash name seen)
1059 (rec :name name :type :ptr
1060 :ttl (zr-ttl zr) :data (zr-name zr))
1061 (setf (gethash name seen) t))))))))))
1062
74962377 1063(defzoneparse :multi (name data rec :zname zname :ttl ttl)
32ebbe9b
MW
1064 ":multi (((NET*) &key :start :end :family :suffix) . REC)
1065
1066 Output multiple records covering a portion of the reverse-resolution
1067 namespace corresponding to the particular NETs. The START and END bounds
1068 default to the most significant variable component of the
1069 reverse-resolution domain.
1070
1071 The REC tail is a sequence of record forms (as handled by
1072 `zone-process-records') to be emitted for each covered address. Within
1073 the bodies of these forms, the symbol `*' will be replaced by the
1074 domain-name fragment corresponding to the current host, optionally
1075 followed by the SUFFIX.
1076
1077 Examples:
1078
1079 (:multi ((delegated-subnet :start 8)
1080 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
1081
1082 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
1083 :cname *))
1084
1085 Obviously, nested `:multi' records won't work well."
1086
1087 (destructuring-bind (nets &key start end (family *address-family*) suffix)
1088 (listify (car data))
1089 (dolist (net (listify nets))
1090 (dolist (ipn (net-parse-to-ipnets net family))
1091 (let* ((addr (ipnet-net ipn))
1092 (width (ipaddr-width addr))
1093 (comp-width (reverse-domain-component-width addr))
1094 (end (round-up (or end
1095 (ipnet-changeable-bits width
1096 (ipnet-mask ipn)))
1097 comp-width))
1098 (start (round-down (or start (- end comp-width))
1099 comp-width))
1100 (map (ipnet-host-map ipn)))
1101 (multiple-value-bind (host-step host-limit)
1102 (ipnet-index-bounds map start end)
1103 (do ((index 0 (+ index host-step)))
1104 ((> index host-limit))
1105 (let* ((addr (ipnet-index-host map index))
1106 (frag (reverse-domain-fragment addr start end))
1107 (target (concatenate 'string
1108 (zone-make-name
1109 (if (not suffix) frag
1110 (concatenate 'string
1111 frag "." suffix))
1112 zname)
1113 ".")))
1114 (dolist (zr (zone-parse-records (zone-make-name frag zname)
1115 ttl
1116 (subst target '*
1117 (cdr data))))
1118 (rec :name (zr-name zr)
1119 :type (zr-type zr)
1120 :data (zr-data zr)
1121 :ttl (zr-ttl zr)
1122 :make-ptr-p (zr-make-ptr-p zr)))))))))))
7e282fb5 1123
fe5fb85a
MW
1124;;;--------------------------------------------------------------------------
1125;;; Zone file output.
7e282fb5 1126
afa2e2f1 1127(export 'zone-write)
a567a3bc
MW
1128(defgeneric zone-write (format zone stream)
1129 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1130
1131(defvar *writing-zone* nil
1132 "The zone currently being written.")
1133
1134(defvar *zone-output-stream* nil
1135 "Stream to write zone data on.")
1136
9f408c60 1137(export 'zone-write-raw-rrdata)
146571da
MW
1138(defgeneric zone-write-raw-rrdata (format zr type data)
1139 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1140
1141 ZR gives the record object, which carries the name and TTL; the TYPE is
1142 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1143 This is used by the default `zone-write-record' method to handle record
1144 types which aren't directly supported by the format driver."))
1145
1146(export 'zone-write-header)
1147(defgeneric zone-write-header (format zone)
1148 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1149
1150 The header includes any kind of initial comment, the SOA record, and any
1151 other necessary preamble. There is no default implementation.
1152
1153 This is part of the protocol used by the default method on `zone-write';
1154 if you override that method."))
1155
1156(export 'zone-write-trailer)
1157(defgeneric zone-write-trailer (format zone)
1158 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1159
1160 The footer may be empty, and is so by default.
1161
1162 This is part of the protocol used by the default method on `zone-write';
1163 if you override that method.")
1164 (:method (format zone)
1165 (declare (ignore format zone))
1166 nil))
1167
1168(export 'zone-write-record)
1169(defgeneric zone-write-record (format type zr)
1170 (:documentation "Emit a record of the given TYPE (a keyword).
1171
9f408c60
MW
1172 The default implementation builds the raw RRDATA and passes it to
1173 `zone-write-raw-rrdata'.")
1174 (:method (format type zr)
1175 (let* (code
1176 (data (build-record (setf code (zone-record-rrdata type zr)))))
1177 (zone-write-raw-rrdata format zr code data))))
146571da
MW
1178
1179(defmethod zone-write (format zone stream)
1180 "This default method calls `zone-write-header', then `zone-write-record'
1181 for each record in the zone, and finally `zone-write-trailer'. While it's
1182 running, `*writing-zone*' is bound to the zone object, and
1183 `*zone-output-stream*' to the output stream."
a567a3bc
MW
1184 (let ((*writing-zone* zone)
1185 (*zone-output-stream* stream))
146571da
MW
1186 (zone-write-header format zone)
1187 (dolist (zr (zone-records-sorted zone))
1188 (zone-write-record format (zr-type zr) zr))
1189 (zone-write-trailer format zone)))
a567a3bc 1190
afa2e2f1 1191(export 'zone-save)
a567a3bc
MW
1192(defun zone-save (zones &key (format :bind))
1193 "Write the named ZONES to files. If no zones are given, write all the
1194 zones."
1195 (unless zones
1196 (setf zones (hash-table-keys *zones*)))
1197 (safely (safe)
1198 (dolist (z zones)
1199 (let ((zz (zone-find z)))
1200 (unless zz
1201 (error "Unknown zone `~A'." z))
1202 (let ((stream (safely-open-output-stream safe
1203 (zone-file-name z :zone))))
1204 (zone-write format zz stream))))))
1205
1206;;;--------------------------------------------------------------------------
1207;;; Bind format output.
1208
80b5c2ff
MW
1209(defvar *bind-last-record-name* nil
1210 "The previously emitted record name.
1211
1212 Used for eliding record names on output.")
1213
afa2e2f1 1214(export 'bind-hostname)
a567a3bc 1215(defun bind-hostname (hostname)
80b5c2ff
MW
1216 (let* ((h (string-downcase (stringify hostname)))
1217 (hl (length h))
1218 (r (string-downcase (zone-name *writing-zone*)))
1219 (rl (length r)))
1220 (cond ((string= r h) "@")
1221 ((and (> hl rl)
1222 (char= (char h (- hl rl 1)) #\.)
1223 (string= h r :start1 (- hl rl)))
1224 (subseq h 0 (- hl rl 1)))
1225 (t (concatenate 'string h ".")))))
1226
1227(export 'bind-output-hostname)
1228(defun bind-output-hostname (hostname)
1229 (let ((name (bind-hostname hostname)))
1230 (cond ((and *bind-last-record-name*
1231 (string= name *bind-last-record-name*))
1232 "")
1233 (t
1234 (setf *bind-last-record-name* name)
1235 name))))
a567a3bc 1236
146571da
MW
1237(defmethod zone-write :around ((format (eql :bind)) zone stream)
1238 (let ((*bind-last-record-name* nil))
1239 (call-next-method)))
32ebbe9b 1240
146571da
MW
1241(defmethod zone-write-header ((format (eql :bind)) zone)
1242 (format *zone-output-stream* "~
7e282fb5 1243;;; Zone file `~(~A~)'
1244;;; (generated ~A)
1245
7d593efd
MW
1246$ORIGIN ~0@*~(~A.~)
1247$TTL ~2@*~D~2%"
7e282fb5 1248 (zone-name zone)
1249 (iso-date :now :datep t :timep t)
1250 (zone-default-ttl zone))
146571da 1251 (let* ((soa (zone-soa zone))
a567a3bc
MW
1252 (admin (let* ((name (soa-admin soa))
1253 (at (position #\@ name))
1254 (copy (format nil "~(~A~)." name)))
1255 (when at
1256 (setf (char copy at) #\.))
1257 copy)))
146571da 1258 (format *zone-output-stream* "~
fffebf35
MW
1259~A~30TIN SOA~40T~A (
1260~55@A~60T ;administrator
7e282fb5 1261~45T~10D~60T ;serial
1262~45T~10D~60T ;refresh
1263~45T~10D~60T ;retry
1264~45T~10D~60T ;expire
1265~45T~10D )~60T ;min-ttl~2%"
80b5c2ff 1266 (bind-output-hostname (zone-name zone))
a567a3bc
MW
1267 (bind-hostname (soa-source soa))
1268 admin
7e282fb5 1269 (soa-serial soa)
1270 (soa-refresh soa)
1271 (soa-retry soa)
1272 (soa-expire soa)
146571da 1273 (soa-min-ttl soa))))
a567a3bc 1274
afa2e2f1 1275(export 'bind-format-record)
146571da 1276(defun bind-format-record (zr format &rest args)
a567a3bc
MW
1277 (format *zone-output-stream*
1278 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
146571da
MW
1279 (bind-output-hostname (zr-name zr))
1280 (let ((ttl (zr-ttl zr)))
1281 (and (/= ttl (zone-default-ttl *writing-zone*))
1282 ttl))
1283 (string-upcase (symbol-name (zr-type zr)))
a567a3bc
MW
1284 format args))
1285
9f408c60
MW
1286(defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1287 (format *zone-output-stream*
1288 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A"
1289 (bind-output-hostname (zr-name zr))
1290 (let ((ttl (zr-ttl zr)))
1291 (and (/= ttl (zone-default-ttl *writing-zone*))
1292 ttl))
1293 type
1294 (length data))
1295 (let* ((hex (with-output-to-string (out)
1296 (dotimes (i (length data))
1297 (format out "~(~2,'0X~)" (aref data i)))))
1298 (len (length hex)))
1299 (cond ((< len 24)
1300 (format *zone-output-stream* " ~A~%" hex))
1301 (t
1302 (format *zone-output-stream* " (")
1303 (let ((i 0))
1304 (loop
1305 (when (>= i len) (return))
1306 (let ((j (min (+ i 64) len)))
1307 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1308 (setf i j))))
1309 (format *zone-output-stream* " )~%")))))
1310
146571da
MW
1311(defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1312 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1313
1314(defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1315 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1316
1317(defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1318 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1319
1320(defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1321 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1322
1323(defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1324 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1325
1326(defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1327 (bind-format-record zr "~2D ~A"
1328 (cdr (zr-data zr))
1329 (bind-hostname (car (zr-data zr)))))
1330
1331(defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1332 (destructuring-bind (prio weight port host) (zr-data zr)
1333 (bind-format-record zr "~2D ~5D ~5D ~A"
1334 prio weight port (bind-hostname host))))
1335
1336(defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1337 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1338
1339(defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1340 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
32ebbe9b 1341
e97012de
MW
1342;;;--------------------------------------------------------------------------
1343;;; tinydns-data output format.
1344
422e7cfc 1345(export 'tinydns-output)
e97012de
MW
1346(defun tinydns-output (code &rest fields)
1347 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1348
9f408c60 1349(defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
e97012de
MW
1350 (tinydns-output #\: (zr-name zr) type
1351 (with-output-to-string (out)
1352 (dotimes (i (length data))
1353 (let ((byte (aref data i)))
1354 (if (or (<= byte 32)
1355 (>= byte 128)
1356 (member byte '(#\: #\\) :key #'char-code))
1357 (format out "\\~3,'0O" byte)
1358 (write-char (code-char byte) out)))))
1359 (zr-ttl zr)))
1360
146571da
MW
1361(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1362 (tinydns-output #\+ (zr-name zr)
1363 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1364
1365(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1366 (tinydns-output #\3 (zr-name zr)
1367 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1368 (zr-ttl zr)))
1369
1370(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1371 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1372
1373(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1374 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1375
1376(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1377 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1378
1379(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1380 (let ((name (car (zr-data zr)))
1381 (prio (cdr (zr-data zr))))
1382 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1383
146571da
MW
1384(defmethod zone-write-header ((format (eql :tinydns)) zone)
1385 (format *zone-output-stream* "~
e97012de
MW
1386### Zone file `~(~A~)'
1387### (generated ~A)
1388~%"
1389 (zone-name zone)
1390 (iso-date :now :datep t :timep t))
1391 (let ((soa (zone-soa zone)))
1392 (tinydns-output #\Z
1393 (zone-name zone)
1394 (soa-source soa)
1395 (let* ((name (copy-seq (soa-admin soa)))
1396 (at (position #\@ name)))
1397 (when at (setf (char name at) #\.))
1398 name)
1399 (soa-serial soa)
1400 (soa-refresh soa)
1401 (soa-expire soa)
1402 (soa-min-ttl soa)
146571da 1403 (zone-default-ttl zone))))
e97012de 1404
7e282fb5 1405;;;----- That's all, folks --------------------------------------------------