zone.lisp: Fix the docstring for `:srv' records.
[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 35;;;--------------------------------------------------------------------------
fe5fb85a
MW
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
fe5fb85a
MW
114;;;--------------------------------------------------------------------------
115;;; Zone types.
7e282fb5 116
afa2e2f1 117(export 'soa)
7e282fb5 118(defstruct (soa (:predicate soap))
119 "Start-of-authority record information."
120 source
121 admin
122 refresh
123 retry
124 expire
125 min-ttl
126 serial)
fe5fb85a 127
db43369d
MW
128(export 'zone-text-name)
129(defun zone-text-name (zone)
130 (princ-to-string (zone-name zone)))
131
afa2e2f1 132(export 'mx)
7e282fb5 133(defstruct (mx (:predicate mxp))
134 "Mail-exchange record information."
135 priority
136 domain)
fe5fb85a 137
afa2e2f1 138(export 'zone)
7e282fb5 139(defstruct (zone (:predicate zonep))
140 "Zone information."
141 soa
142 default-ttl
143 name
144 records)
145
fe5fb85a
MW
146;;;--------------------------------------------------------------------------
147;;; Zone defaults. It is intended that scripts override these.
148
afa2e2f1 149(export '*default-zone-source*)
7e282fb5 150(defvar *default-zone-source*
8e7c1366 151 (let ((hn (gethostname)))
8a4f9a18 152 (and hn (concatenate 'string (canonify-hostname hn) ".")))
7e282fb5 153 "The default zone source: the current host's name.")
fe5fb85a 154
afa2e2f1 155(export '*default-zone-refresh*)
7e282fb5 156(defvar *default-zone-refresh* (* 24 60 60)
157 "Default zone refresh interval: one day.")
fe5fb85a 158
afa2e2f1 159(export '*default-zone-admin*)
7e282fb5 160(defvar *default-zone-admin* nil
161 "Default zone administrator's email address.")
fe5fb85a 162
afa2e2f1 163(export '*default-zone-retry*)
7e282fb5 164(defvar *default-zone-retry* (* 60 60)
165 "Default znoe retry interval: one hour.")
fe5fb85a 166
afa2e2f1 167(export '*default-zone-expire*)
7e282fb5 168(defvar *default-zone-expire* (* 14 24 60 60)
169 "Default zone expiry time: two weeks.")
fe5fb85a 170
afa2e2f1 171(export '*default-zone-min-ttl*)
7e282fb5 172(defvar *default-zone-min-ttl* (* 4 60 60)
173 "Default zone minimum TTL/negative TTL: four hours.")
fe5fb85a 174
afa2e2f1 175(export '*default-zone-ttl*)
7e282fb5 176(defvar *default-zone-ttl* (* 8 60 60)
177 "Default zone TTL (for records without explicit TTLs): 8 hours.")
fe5fb85a 178
afa2e2f1 179(export '*default-mx-priority*)
7e282fb5 180(defvar *default-mx-priority* 50
181 "Default MX priority.")
182
fe5fb85a 183;;;--------------------------------------------------------------------------
fe5fb85a
MW
184;;; Zone variables and structures.
185
7e282fb5 186(defvar *zones* (make-hash-table :test #'equal)
187 "Map of known zones.")
fe5fb85a 188
afa2e2f1 189(export 'zone-find)
7e282fb5 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))
196
afa2e2f1 197(export 'zone-record)
7e282fb5 198(defstruct (zone-record (:conc-name zr-))
199 "A zone record."
200 (name '<unnamed>)
201 ttl
202 type
590ad961 203 (make-ptr-p nil)
7e282fb5 204 data)
205
afa2e2f1 206(export 'zone-subdomain)
7e282fb5 207(defstruct (zone-subdomain (:conc-name zs-))
f4e0c48f
MW
208 "A subdomain.
209
210 Slightly weird. Used internally by `zone-process-records', and shouldn't
211 escape."
7e282fb5 212 name
213 ttl
214 records)
215
afa2e2f1 216(export '*zone-output-path*)
3d7852d9
MW
217(defvar *zone-output-path* nil
218 "Pathname defaults to merge into output files.
219
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
222 load time.")
ab87c7bf 223
afa2e2f1 224(export '*preferred-subnets*)
8ce7eb9b
MW
225(defvar *preferred-subnets* nil
226 "Subnets to prefer when selecting defaults.")
227
fe5fb85a
MW
228;;;--------------------------------------------------------------------------
229;;; Zone infrastructure.
230
ab87c7bf
MW
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))
3d7852d9 235 (or *zone-output-path* *default-pathname-defaults*)))
ab87c7bf 236
afa2e2f1 237(export 'zone-preferred-subnet-p)
8ce7eb9b
MW
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))
241
afa2e2f1 242(export 'preferred-subnet-case)
8bd2576e 243(defmacro preferred-subnet-case (&body clauses)
f4e0c48f 244 "Execute a form based on which networks are considered preferred.
f38bc59e 245
f4e0c48f
MW
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
249 always matches."
8bd2576e
MW
250 `(cond
251 ,@(mapcar (lambda (clause)
252 (let ((subnets (car clause)))
253 (cons (cond ((eq subnets t)
254 t)
255 ((listp subnets)
256 `(or ,@(mapcar (lambda (subnet)
257 `(zone-preferred-subnet-p
258 ',subnet))
259 subnets)))
260 (t
261 `(zone-preferred-subnet-p ',subnets)))
262 (cdr clause))))
263 clauses)))
264
32ebbe9b 265(export 'zone-parse-host)
db43369d
MW
266(defun zone-parse-host (form &optional tail)
267 "Parse a host name FORM from a value in a zone form.
268
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
272 before use."
273 (let ((name (etypecase form
274 (null (make-domain-name :labels nil :absolutep nil))
275 (domain-name form)
276 (symbol (parse-domain-name (string-downcase form)))
277 (string (parse-domain-name form)))))
278 (if (null tail) name
279 (domain-name-concat name tail))))
32ebbe9b 280
aac45ff7
MW
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))
285 (lambda (zr-a zr-b)
05e83012
MW
286 (multiple-value-bind (precp follp)
287 (domain-name< (zr-name zr-a) (zr-name zr-b))
288 (cond (precp t)
289 (follp nil)
290 (t (string< (zr-type zr-a) (zr-type zr-b))))))))
aac45ff7 291
32ebbe9b
MW
292;;;--------------------------------------------------------------------------
293;;; Serial numbering.
294
295(export 'make-zone-serial)
296(defun make-zone-serial (name)
297 "Given a zone NAME, come up with a new serial number.
298
299 This will (very carefully) update a file ZONE.serial in the current
300 directory."
301 (let* ((file (zone-file-name name :serial))
302 (last (with-open-file (in file
303 :direction :input
304 :if-does-not-exist nil)
305 (if in (read in)
306 (list 0 0 0 0))))
307 (now (multiple-value-bind
308 (sec min hr dy mon yr dow dstp tz)
309 (get-decoded-time)
310 (declare (ignore sec min hr dow dstp tz))
311 (list dy mon yr)))
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)
316 (format out
317 ";; Serial number file for zone ~A~%~
318 ;; (LAST-SEQ DAY MONTH YEAR)~%~
319 ~S~%"
320 name
321 (cons seq now)))
322 (from-mixed-base '(100 100 100) (reverse (cons seq now)))))
323
324;;;--------------------------------------------------------------------------
325;;; Zone form parsing.
326
7e282fb5 327(defun zone-process-records (rec ttl func)
f38bc59e
MW
328 "Sort out the list of records in REC, calling FUNC for each one.
329
baad8564
MW
330 TTL is the default time-to-live for records which don't specify one.
331
f4e0c48f
MW
332 REC is a list of records of the form
333
334 ({ :ttl TTL | TYPE DATA | (LABEL . REC) }*)
335
336 The various kinds of entries have the following meanings.
337
338 :ttl TTL Set the TTL for subsequent records (at this level of
339 nesting only).
340
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.
344
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
350
351 (host (sub :a \"169.254.1.1\"))
baad8564 352
f4e0c48f 353 defines a record for `host.sub' -- not `sub.host'.
baad8564 354
f4e0c48f
MW
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.
baad8564 358
f4e0c48f
MW
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
362 the raw output."
baad8564 363
7e282fb5 364 (labels ((sift (rec ttl)
f4e0c48f
MW
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.
368
7e282fb5 369 (collecting (top sub)
370 (loop
371 (unless rec
372 (return))
373 (let ((r (pop rec)))
374 (cond ((eq r :ttl)
375 (setf ttl (pop rec)))
376 ((symbolp r)
377 (collect (make-zone-record :type r
378 :ttl ttl
379 :data (pop rec))
380 top))
381 ((listp r)
382 (dolist (name (listify (car r)))
db43369d
MW
383 (collect (make-zone-subdomain
384 :name (zone-parse-host name)
385 :ttl ttl :records (cdr r))
7e282fb5 386 sub)))
387 (t
388 (error "Unexpected record form ~A" (car r))))))))
f4e0c48f 389
4e7e3780 390 (process (rec dom ttl)
f4e0c48f
MW
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
394 ;; already.
395
7e282fb5 396 (multiple-value-bind (top sub) (sift rec ttl)
397 (if (and dom (null top) sub)
64e34a97 398 (let ((preferred
db43369d
MW
399 (or (find-if
400 (lambda (s)
401 (let ((ll (domain-name-labels (zs-name s))))
402 (and (consp ll) (null (cdr ll))
403 (zone-preferred-subnet-p (car ll)))))
404 sub)
64e34a97 405 (car sub))))
8ce7eb9b
MW
406 (when preferred
407 (process (zs-records preferred)
408 dom
409 (zs-ttl preferred))))
db43369d 410 (let ((name dom))
8ce7eb9b
MW
411 (dolist (zr top)
412 (setf (zr-name zr) name)
413 (funcall func zr))))
7e282fb5 414 (dolist (s sub)
415 (process (zs-records s)
db43369d
MW
416 (if (null dom) (zs-name s)
417 (domain-name-concat dom (zs-name s)))
4e7e3780 418 (zs-ttl s))))))
f4e0c48f
MW
419
420 ;; Process the records we're given with no prefix.
4e7e3780 421 (process rec nil ttl)))
7e282fb5 422
7e282fb5 423(defun zone-parse-head (head)
f38bc59e
MW
424 "Parse the HEAD of a zone form.
425
426 This has the form
7e282fb5 427
428 (NAME &key :source :admin :refresh :retry
b23c65ee 429 :expire :min-ttl :ttl :serial)
7e282fb5 430
2f1d381d
MW
431 though a singleton NAME needn't be a list. Returns the default TTL and an
432 soa structure representing the zone head."
7e282fb5 433 (destructuring-bind
db43369d 434 (raw-zname
7e282fb5 435 &key
8a4f9a18 436 (source *default-zone-source*)
7e282fb5 437 (admin (or *default-zone-admin*
db43369d 438 (format nil "hostmaster@~A" raw-zname)))
7e282fb5 439 (refresh *default-zone-refresh*)
440 (retry *default-zone-retry*)
441 (expire *default-zone-expire*)
442 (min-ttl *default-zone-min-ttl*)
443 (ttl min-ttl)
db43369d
MW
444 (serial (make-zone-serial raw-zname))
445 &aux
446 (zname (zone-parse-host raw-zname root-domain)))
7e282fb5 447 (listify head)
db43369d 448 (values zname
7e282fb5 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)
456 :serial serial))))
457
afa2e2f1 458(export 'defzoneparse)
7e282fb5 459(defmacro defzoneparse (types (name data list
5bf80328 460 &key (prefix (gensym "PREFIX"))
b23c65ee
MW
461 (zname (gensym "ZNAME"))
462 (ttl (gensym "TTL")))
7e282fb5 463 &body body)
f38bc59e
MW
464 "Define a new zone record type.
465
f4e0c48f
MW
466 The arguments are as follows:
467
468 TYPES A singleton type symbol, or a list of aliases.
fe5fb85a 469
2f1d381d 470 NAME The name of the record to be added.
fe5fb85a 471
2f1d381d 472 DATA The content of the record to be added (a single object,
7fff3797 473 unevaluated).
fe5fb85a 474
2f1d381d 475 LIST A function to add a record to the zone. See below.
fe5fb85a 476
5bf80328
MW
477 PREFIX The prefix tag used in the original form.
478
2f1d381d 479 ZNAME The name of the zone being constructed.
fe5fb85a 480
2f1d381d 481 TTL The TTL for this record.
fe5fb85a 482
5bf80328
MW
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.
fe5fb85a 485
2f1d381d
MW
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
fe5fb85a 488
590ad961 489 (LIST &key :name :type :data :ttl :make-ptr-p)
fe5fb85a 490
590ad961
MW
491 These (except MAKE-PTR-P, which defaults to nil) default to the above
492 arguments (even if you didn't accept the arguments)."
db43369d 493
7e282fb5 494 (setf types (listify types))
495 (let* ((type (car types))
496 (func (intern (format nil "ZONE-PARSE/~:@(~A~)" type))))
2ec279f5 497 (with-parsed-body (body decls doc) body
590ad961 498 (with-gensyms (col tname ttype tttl tdata tmakeptrp i)
40ded1b8
MW
499 `(progn
500 (dolist (,i ',types)
501 (setf (get ,i 'zone-parse) ',func))
5bf80328 502 (defun ,func (,prefix ,zname ,data ,ttl ,col)
40ded1b8
MW
503 ,@doc
504 ,@decls
db43369d
MW
505 (let ((,name (if (null ,prefix) ,zname
506 (domain-name-concat ,prefix ,zname))))
5bf80328
MW
507 (flet ((,list (&key ((:name ,tname) ,name)
508 ((:type ,ttype) ,type)
509 ((:data ,tdata) ,data)
590ad961
MW
510 ((:ttl ,tttl) ,ttl)
511 ((:make-ptr-p ,tmakeptrp) nil))
f4decf40 512 #+cmu (declare (optimize ext:inhibit-warnings))
5bf80328
MW
513 (collect (make-zone-record :name ,tname
514 :type ,ttype
515 :data ,tdata
590ad961
MW
516 :ttl ,tttl
517 :make-ptr-p ,tmakeptrp)
5bf80328
MW
518 ,col)))
519 ,@body)))
f4e0c48f 520 ',type)))))
7e282fb5 521
8fcf1ae3
MW
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.
525
526 The records are parsed relative to the zone name ZNAME, and using the
527 given default TTL."
528 (collecting (rec)
529 (flet ((parse-record (zr)
530 (let ((func (or (get (zr-type zr) 'zone-parse)
531 (error "No parser for record ~A."
532 (zr-type zr))))
db43369d 533 (name (and (zr-name zr) (zr-name zr))))
8fcf1ae3
MW
534 (funcall func name zname (zr-data zr) (zr-ttl zr) rec))))
535 (zone-process-records records ttl #'parse-record))))
7e282fb5 536
afa2e2f1 537(export 'zone-parse)
7e282fb5 538(defun zone-parse (zf)
f38bc59e
MW
539 "Parse a ZONE form.
540
f4e0c48f 541 The syntax of a zone form is as follows:
7e282fb5 542
2f1d381d
MW
543 ZONE-FORM:
544 ZONE-HEAD ZONE-RECORD*
7e282fb5 545
2f1d381d
MW
546 ZONE-RECORD:
547 ((NAME*) ZONE-RECORD*)
548 | SYM ARGS"
7e282fb5 549 (multiple-value-bind (zname ttl soa) (zone-parse-head (car zf))
8fcf1ae3
MW
550 (make-zone :name zname
551 :default-ttl ttl
552 :soa soa
553 :records (zone-parse-records zname ttl (cdr zf)))))
7e282fb5 554
afa2e2f1 555(export 'zone-create)
fe5fb85a 556(defun zone-create (zf)
db43369d
MW
557 "Zone construction function.
558
559 Given a zone form ZF, construct the zone and add it to the table."
fe5fb85a 560 (let* ((zone (zone-parse zf))
db43369d 561 (name (zone-text-name zone)))
fe5fb85a
MW
562 (setf (zone-find name) zone)
563 name))
564
afa2e2f1 565(export 'defzone)
32ebbe9b 566(defmacro defzone (soa &body zf)
fe5fb85a
MW
567 "Zone definition macro."
568 `(zone-create '(,soa ,@zf)))
569
32ebbe9b
MW
570(export '*address-family*)
571(defvar *address-family* t
572 "The default address family. This is bound by `defrevzone'.")
573
afa2e2f1 574(export 'defrevzone)
32ebbe9b 575(defmacro defrevzone (head &body zf)
fe5fb85a 576 "Define a reverse zone, with the correct name."
32ebbe9b
MW
577 (destructuring-bind (nets &rest args
578 &key &allow-other-keys
579 (family '*address-family*)
580 prefix-bits)
fe5fb85a 581 (listify head)
32ebbe9b
MW
582 (with-gensyms (ipn)
583 `(dolist (,ipn (net-parse-to-ipnets ',nets ,family))
584 (let ((*address-family* (ipnet-family ,ipn)))
db43369d
MW
585 (zone-create `((,(format nil "~A." (reverse-domain ,ipn
586 ,prefix-bits))
32ebbe9b
MW
587 ,@',(loop for (k v) on args by #'cddr
588 unless (member k
589 '(:family :prefix-bits))
590 nconc (list k v)))
591 ,@',zf)))))))
592
7c34d08c 593(export 'map-host-addresses)
32ebbe9b
MW
594(defun map-host-addresses (func addr &key (family *address-family*))
595 "Call FUNC for each address denoted by ADDR (a `host-parse' address)."
596
597 (dolist (a (host-addrs (host-parse addr family)))
598 (funcall func a)))
599
7c34d08c 600(export 'do-host)
32ebbe9b
MW
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)))
604 ,@body))
605
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)
613 nconc (list k v))))
614 (do-host (addr addrspec :family family)
615 (apply rec :type (ipaddr-rrtype addr) :data addr key-args))))
fe5fb85a
MW
616
617;;;--------------------------------------------------------------------------
9f408c60
MW
618;;; Building raw record vectors.
619
620(defvar *record-vector* nil
621 "The record vector under construction.")
622
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))))))
631
632(export 'rec-byte)
633(defun rec-byte (octets value)
634 "Append an unsigned byte, OCTETS octets wide, with VALUE, to the record."
635 (rec-ensure octets)
636 (do ((i (1- octets) (1- i)))
637 ((minusp i))
638 (vector-push (ldb (byte 8 (* 8 i)) value) *record-vector*)))
639
640(export 'rec-u8)
641(defun rec-u8 (value)
642 "Append an 8-bit VALUE to the current record."
643 (rec-byte 1 value))
644
645(export 'rec-u16)
646(defun rec-u16 (value)
647 "Append a 16-bit VALUE to the current record."
648 (rec-byte 2 value))
649
650(export 'rec-u32)
651(defun rec-u32 (value)
652 "Append a 32-bit VALUE to the current record."
653 (rec-byte 4 value))
654
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.
658
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)))
664 ((>= i end))
665 (vector-push (char-code (char s i)) *record-vector*)))
666
667(export 'rec-string)
668(defun rec-string (s &key (start 0) end (max 255))
669 (let* ((end (or end (length s)))
670 (len (- end start)))
671 (unless (<= len max)
672 (error "String `~A' too long" (subseq s start end)))
673 (rec-u8 (- end start))
674 (rec-raw-string s :start start :end end)))
675
676(export 'rec-name)
db43369d
MW
677(defun rec-name (name)
678 "Append a domain NAME.
9f408c60
MW
679
680 No attempt is made to perform compression of the name."
db43369d
MW
681 (dolist (label (reverse (domain-name-labels name)))
682 (rec-string label :max 63))
683 (rec-u8 0))
9f408c60
MW
684
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)
690 :fill-pointer 0
691 :adjustable t)))
692 ,@body
693 (copy-seq *record-vector*)))
694
695(export 'zone-record-rrdata)
696(defgeneric zone-record-rrdata (type zr)
697 (:documentation "Emit (using the `build-record' protocol) RRDATA for ZR.
698
699 The TYPE is a keyword naming the record type. Return the numeric RRTYPE
700 code."))
701
702;;;--------------------------------------------------------------------------
fe5fb85a
MW
703;;; Zone record parsers.
704
4e7e3780 705(defzoneparse :a (name data rec)
7e282fb5 706 ":a IPADDR"
32ebbe9b
MW
707 (zone-set-address #'rec data :make-ptr-p t :family :ipv4))
708
9f408c60
MW
709(defmethod zone-record-rrdata ((type (eql :a)) zr)
710 (rec-u32 (ipaddr-addr (zr-data zr)))
711 1)
712
a2267e14
MW
713(defzoneparse :aaaa (name data rec)
714 ":aaaa IPADDR"
715 (zone-set-address #'rec data :make-ptr-p t :family :ipv6))
716
9f408c60
MW
717(defmethod zone-record-rrdata ((type (eql :aaaa)) zr)
718 (rec-byte 16 (ipaddr-addr (zr-data zr)))
719 28)
720
32ebbe9b
MW
721(defzoneparse :addr (name data rec)
722 ":addr IPADDR"
723 (zone-set-address #'rec data :make-ptr-p t))
590ad961
MW
724
725(defzoneparse :svc (name data rec)
726 ":svc IPADDR"
32ebbe9b 727 (zone-set-address #'rec data))
fe5fb85a 728
7e282fb5 729(defzoneparse :ptr (name data rec :zname zname)
730 ":ptr HOST"
731 (rec :data (zone-parse-host data zname)))
fe5fb85a 732
9f408c60
MW
733(defmethod zone-record-rrdata ((type (eql :ptr)) zr)
734 (rec-name (zr-data zr))
735 12)
736
7e282fb5 737(defzoneparse :cname (name data rec :zname zname)
738 ":cname HOST"
739 (rec :data (zone-parse-host data zname)))
fe5fb85a 740
9f408c60
MW
741(defmethod zone-record-rrdata ((type (eql :cname)) zr)
742 (rec-name (zr-data zr))
743 5)
744
90022a23 745(defzoneparse :txt (name data rec)
4ea82aba
MW
746 ":txt (TEXT*)"
747 (rec :data (listify data)))
90022a23 748
9f408c60
MW
749(defmethod zone-record-rrdata ((type (eql :txt)) zr)
750 (mapc #'rec-string (zr-data zr))
751 16)
752
f760c73a
MW
753(export '*dkim-pathname-defaults*)
754(defvar *dkim-pathname-defaults*
755 (make-pathname :directory '(:relative "keys")
756 :type "dkim"))
757
75f39e1a
MW
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))
762 (labels ((flush ()
763 (when out
764 (push (get-output-stream-string out) things)
765 (setf out nil)))
766 (emit (text)
767 (let ((len (length text)))
768 (when (and out (> (+ (file-position out)
769 (length text))
770 64))
771 (flush))
772 (when (plusp len)
773 (cond ((< len 64)
774 (unless out (setf out (make-string-output-stream)))
775 (write-string text out))
776 (t
777 (do ((i 0 j)
778 (j 64 (+ j 64)))
779 ((>= i len))
780 (push (subseq text i (min j len)) things))))))))
781 (do ((p plist (cddr p)))
782 ((endp p))
783 (emit (format nil "~(~A~)=~A;" (car p) (cadr p))))
784 (emit (with-output-to-string (out)
785 (write-string "p=" out)
786 (when file
f760c73a
MW
787 (with-open-file
788 (in (merge-pathnames file *dkim-pathname-defaults*))
75f39e1a
MW
789 (loop
790 (when (string= (read-line in)
791 "-----BEGIN PUBLIC KEY-----")
792 (return)))
793 (loop
794 (let ((line (read-line in)))
795 (if (string= line "-----END PUBLIC KEY-----")
796 (return)
797 (write-string line out)))))))))
798 (rec :type :txt
799 :data (nreverse things)))))
800
f1d7d492
MW
801(eval-when (:load-toplevel :execute)
802 (dolist (item '((sshfp-algorithm rsa 1)
803 (sshfp-algorithm dsa 2)
804 (sshfp-algorithm ecdsa 3)
805 (sshfp-type sha-1 1)
806 (sshfp-type sha-256 2)))
807 (destructuring-bind (prop sym val) item
808 (setf (get sym prop) val)
809 (export sym))))
810
f760c73a
MW
811(export '*sshfp-pathname-defaults*)
812(defvar *sshfp-pathname-defaults*
813 (make-pathname :directory '(:relative "keys")
814 :type "sshfp"))
815
f1d7d492
MW
816(defzoneparse :sshfp (name data rec)
817 ":sshfp { FILENAME | ((FPR :alg ALG :type HASH)*) }"
818 (if (stringp data)
f760c73a 819 (with-open-file (in (merge-pathnames data *sshfp-pathname-defaults*))
f1d7d492
MW
820 (loop (let ((line (read-line in nil)))
821 (unless line (return))
822 (let ((words (str-split-words line)))
823 (pop words)
824 (when (string= (car words) "IN") (pop words))
825 (unless (and (string= (car words) "SSHFP")
826 (= (length words) 4))
827 (error "Invalid SSHFP record."))
828 (pop words)
829 (destructuring-bind (alg type fpr) words
830 (rec :data (list (parse-integer alg)
831 (parse-integer type)
832 fpr)))))))
833 (flet ((lookup (what prop)
834 (etypecase what
835 (fixnum what)
836 (symbol (or (get what prop)
837 (error "~S is not a known ~A" what prop))))))
48608192
MW
838 (dolist (item (listify data))
839 (destructuring-bind (fpr &key (alg 'rsa) (type 'sha-1))
840 (listify item)
841 (rec :data (list (lookup alg 'sshfp-algorithm)
842 (lookup type 'sshfp-type)
843 fpr)))))))
f1d7d492 844
9f408c60
MW
845(defmethod zone-record-rrdata ((type (eql :sshfp)) zr)
846 (destructuring-bind (alg type fpr) (zr-data zr)
847 (rec-u8 alg)
848 (rec-u8 type)
849 (do ((i 0 (+ i 2))
850 (n (length fpr)))
851 ((>= i n))
852 (rec-u8 (parse-integer fpr :start i :end (+ i 2) :radix 16))))
853 44)
854
7e282fb5 855(defzoneparse :mx (name data rec :zname zname)
856 ":mx ((HOST :prio INT :ip IPADDR)*)"
857 (dolist (mx (listify data))
858 (destructuring-bind
859 (mxname &key (prio *default-mx-priority*) ip)
860 (listify mx)
861 (let ((host (zone-parse-host mxname zname)))
32ebbe9b 862 (when ip (zone-set-address #'rec ip :name host))
7e282fb5 863 (rec :data (cons host prio))))))
fe5fb85a 864
9f408c60
MW
865(defmethod zone-record-rrdata ((type (eql :mx)) zr)
866 (let ((name (car (zr-data zr)))
867 (prio (cdr (zr-data zr))))
868 (rec-u16 prio)
869 (rec-name name))
870 15)
871
7e282fb5 872(defzoneparse :ns (name data rec :zname zname)
873 ":ns ((HOST :ip IPADDR)*)"
874 (dolist (ns (listify data))
875 (destructuring-bind
876 (nsname &key ip)
877 (listify ns)
878 (let ((host (zone-parse-host nsname zname)))
32ebbe9b 879 (when ip (zone-set-address #'rec ip :name host))
7e282fb5 880 (rec :data host)))))
fe5fb85a 881
9f408c60
MW
882(defmethod zone-record-rrdata ((type (eql :ns)) zr)
883 (rec-name (zr-data zr))
884 2)
885
7e282fb5 886(defzoneparse :alias (name data rec :zname zname)
887 ":alias (LABEL*)"
888 (dolist (a (listify data))
889 (rec :name (zone-parse-host a zname)
890 :type :cname
891 :data name)))
fe5fb85a 892
716105aa 893(defzoneparse :srv (name data rec :zname zname)
1b5ebe0a
MW
894 ":srv (((SERVICE &key :port :protocol)
895 (PROVIDER &key :port :prio :weight :ip)*)*)"
716105aa
MW
896 (dolist (srv data)
897 (destructuring-bind (servopts &rest providers) srv
898 (destructuring-bind
899 (service &key ((:port default-port)) (protocol :tcp))
900 (listify servopts)
901 (unless default-port
902 (let ((serv (serv-by-name service protocol)))
903 (setf default-port (and serv (serv-port serv)))))
db43369d
MW
904 (let ((rname (flet ((prepend (tag tail)
905 (domain-name-concat
906 (make-domain-name
907 :labels (list (format nil "_~(~A~)" tag)))
908 tail)))
909 (prepend service (prepend protocol name)))))
716105aa
MW
910 (dolist (prov providers)
911 (destructuring-bind
912 (srvname
913 &key
914 (port default-port)
915 (prio *default-mx-priority*)
916 (weight 0)
917 ip)
918 (listify prov)
919 (let ((host (zone-parse-host srvname zname)))
32ebbe9b 920 (when ip (zone-set-address #'rec ip :name host))
716105aa
MW
921 (rec :name rname
922 :data (list prio weight port host))))))))))
923
9f408c60
MW
924(defmethod zone-record-rrdata ((type (eql :srv)) zr)
925 (destructuring-bind (prio weight port host) (zr-data zr)
926 (rec-u16 prio)
927 (rec-u16 weight)
928 (rec-u16 port)
929 (rec-name host))
930 33)
931
a15288b4 932(defzoneparse :net (name data rec)
933 ":net (NETWORK*)"
934 (dolist (net (listify data))
32ebbe9b
MW
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)
939 (when addr
940 (rec :name (zone-parse-host kind name)
941 :type rrtype
942 :data addr))))
943 (frob "net" base)
944 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
945 (frob "bcast" (ipnet-broadcast ipn)))))))
7fff3797 946
7e282fb5 947(defzoneparse (:rev :reverse) (name data rec)
32ebbe9b 948 ":reverse ((NET &key :prefix-bits :family) ZONE*)
679775ba
MW
949
950 Add a reverse record each host in the ZONEs (or all zones) that lies
32ebbe9b 951 within NET."
7e282fb5 952 (setf data (listify data))
32ebbe9b
MW
953 (destructuring-bind (net &key prefix-bits (family *address-family*))
954 (listify (car data))
955
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)))
964 (zr-make-ptr-p zr)
965 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
966 (let* ((frag (reverse-domain-fragment (zr-data zr)
967 0 frag-len))
db43369d
MW
968 (name (domain-name-concat frag name))
969 (name-string (princ-to-string name)))
970 (unless (gethash name-string seen)
32ebbe9b
MW
971 (rec :name name :type :ptr
972 :ttl (zr-ttl zr) :data (zr-name zr))
db43369d 973 (setf (gethash name-string seen) t))))))))))
32ebbe9b 974
74962377 975(defzoneparse :multi (name data rec :zname zname :ttl ttl)
32ebbe9b
MW
976 ":multi (((NET*) &key :start :end :family :suffix) . REC)
977
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.
982
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.
988
989 Examples:
990
991 (:multi ((delegated-subnet :start 8)
992 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
993
994 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
995 :cname *))
996
997 Obviously, nested `:multi' records won't work well."
998
db43369d
MW
999 (destructuring-bind (nets
1000 &key start end ((:suffix raw-suffix))
1001 (family *address-family*))
32ebbe9b 1002 (listify (car data))
db43369d
MW
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
1013 (ipnet-mask ipn)))
1014 comp-width))
1015 (start (round-down (or start (- end comp-width))
1016 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)
1026 :from-end t
1027 :initial-value root-domain)))
1028 (dolist (zr (zone-parse-records (domain-name-concat frag
1029 zname)
1030 ttl
1031 (subst target '*
1032 (cdr data))))
1033 (rec :name (zr-name zr)
1034 :type (zr-type zr)
1035 :data (zr-data zr)
1036 :ttl (zr-ttl zr)
1037 :make-ptr-p (zr-make-ptr-p zr))))))))))))
7e282fb5 1038
fe5fb85a
MW
1039;;;--------------------------------------------------------------------------
1040;;; Zone file output.
7e282fb5 1041
afa2e2f1 1042(export 'zone-write)
a567a3bc
MW
1043(defgeneric zone-write (format zone stream)
1044 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1045
1046(defvar *writing-zone* nil
1047 "The zone currently being written.")
1048
1049(defvar *zone-output-stream* nil
1050 "Stream to write zone data on.")
1051
9f408c60 1052(export 'zone-write-raw-rrdata)
146571da
MW
1053(defgeneric zone-write-raw-rrdata (format zr type data)
1054 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1055
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."))
1060
1061(export 'zone-write-header)
1062(defgeneric zone-write-header (format zone)
1063 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1064
1065 The header includes any kind of initial comment, the SOA record, and any
1066 other necessary preamble. There is no default implementation.
1067
1068 This is part of the protocol used by the default method on `zone-write';
1069 if you override that method."))
1070
1071(export 'zone-write-trailer)
1072(defgeneric zone-write-trailer (format zone)
1073 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1074
1075 The footer may be empty, and is so by default.
1076
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))
1081 nil))
1082
1083(export 'zone-write-record)
1084(defgeneric zone-write-record (format type zr)
1085 (:documentation "Emit a record of the given TYPE (a keyword).
1086
9f408c60
MW
1087 The default implementation builds the raw RRDATA and passes it to
1088 `zone-write-raw-rrdata'.")
1089 (:method (format type zr)
1090 (let* (code
1091 (data (build-record (setf code (zone-record-rrdata type zr)))))
1092 (zone-write-raw-rrdata format zr code data))))
146571da
MW
1093
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."
a567a3bc
MW
1099 (let ((*writing-zone* zone)
1100 (*zone-output-stream* stream))
146571da
MW
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)))
a567a3bc 1105
afa2e2f1 1106(export 'zone-save)
a567a3bc
MW
1107(defun zone-save (zones &key (format :bind))
1108 "Write the named ZONES to files. If no zones are given, write all the
1109 zones."
1110 (unless zones
1111 (setf zones (hash-table-keys *zones*)))
1112 (safely (safe)
1113 (dolist (z zones)
1114 (let ((zz (zone-find z)))
1115 (unless zz
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))))))
1120
1121;;;--------------------------------------------------------------------------
1122;;; Bind format output.
1123
80b5c2ff
MW
1124(defvar *bind-last-record-name* nil
1125 "The previously emitted record name.
1126
1127 Used for eliding record names on output.")
1128
afa2e2f1 1129(export 'bind-hostname)
a567a3bc 1130(defun bind-hostname (hostname)
db43369d
MW
1131 (let ((zone (domain-name-labels (zone-name *writing-zone*)))
1132 (name (domain-name-labels hostname)))
1133 (loop
1134 (unless (and zone name (string= (car zone) (car name)))
1135 (return))
1136 (pop zone) (pop name))
1137 (flet ((stitch (labels absolutep)
1138 (format nil "~{~A~^.~}~@[.~]"
1139 (reverse (mapcar #'quotify-label labels))
1140 absolutep)))
1141 (cond (zone (stitch (domain-name-labels hostname) t))
1142 (name (stitch name nil))
1143 (t "@")))))
80b5c2ff
MW
1144
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*))
1150 "")
1151 (t
1152 (setf *bind-last-record-name* name)
1153 name))))
a567a3bc 1154
146571da 1155(defmethod zone-write :around ((format (eql :bind)) zone stream)
807e319f 1156 (declare (ignorable zone stream))
146571da
MW
1157 (let ((*bind-last-record-name* nil))
1158 (call-next-method)))
32ebbe9b 1159
146571da
MW
1160(defmethod zone-write-header ((format (eql :bind)) zone)
1161 (format *zone-output-stream* "~
7e282fb5 1162;;; Zone file `~(~A~)'
1163;;; (generated ~A)
1164
7d593efd
MW
1165$ORIGIN ~0@*~(~A.~)
1166$TTL ~2@*~D~2%"
7e282fb5 1167 (zone-name zone)
1168 (iso-date :now :datep t :timep t)
1169 (zone-default-ttl zone))
146571da 1170 (let* ((soa (zone-soa zone))
a567a3bc
MW
1171 (admin (let* ((name (soa-admin soa))
1172 (at (position #\@ name))
1173 (copy (format nil "~(~A~)." name)))
1174 (when at
1175 (setf (char copy at) #\.))
1176 copy)))
146571da 1177 (format *zone-output-stream* "~
fffebf35
MW
1178~A~30TIN SOA~40T~A (
1179~55@A~60T ;administrator
7e282fb5 1180~45T~10D~60T ;serial
1181~45T~10D~60T ;refresh
1182~45T~10D~60T ;retry
1183~45T~10D~60T ;expire
1184~45T~10D )~60T ;min-ttl~2%"
80b5c2ff 1185 (bind-output-hostname (zone-name zone))
a567a3bc
MW
1186 (bind-hostname (soa-source soa))
1187 admin
7e282fb5 1188 (soa-serial soa)
1189 (soa-refresh soa)
1190 (soa-retry soa)
1191 (soa-expire soa)
146571da 1192 (soa-min-ttl soa))))
a567a3bc 1193
afa2e2f1 1194(export 'bind-format-record)
146571da 1195(defun bind-format-record (zr format &rest args)
a567a3bc
MW
1196 (format *zone-output-stream*
1197 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
146571da
MW
1198 (bind-output-hostname (zr-name zr))
1199 (let ((ttl (zr-ttl zr)))
1200 (and (/= ttl (zone-default-ttl *writing-zone*))
1201 ttl))
1202 (string-upcase (symbol-name (zr-type zr)))
a567a3bc
MW
1203 format args))
1204
9f408c60
MW
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*))
1211 ttl))
1212 type
1213 (length data))
1214 (let* ((hex (with-output-to-string (out)
1215 (dotimes (i (length data))
1216 (format out "~(~2,'0X~)" (aref data i)))))
1217 (len (length hex)))
1218 (cond ((< len 24)
1219 (format *zone-output-stream* " ~A~%" hex))
1220 (t
1221 (format *zone-output-stream* " (")
1222 (let ((i 0))
1223 (loop
1224 (when (>= i len) (return))
1225 (let ((j (min (+ i 64) len)))
1226 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1227 (setf i j))))
1228 (format *zone-output-stream* " )~%")))))
1229
146571da
MW
1230(defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1231 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1232
1233(defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1234 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1235
1236(defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1237 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1238
1239(defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1240 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1241
1242(defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1243 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1244
1245(defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1246 (bind-format-record zr "~2D ~A"
1247 (cdr (zr-data zr))
1248 (bind-hostname (car (zr-data zr)))))
1249
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))))
1254
1255(defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1256 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1257
1258(defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1259 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
32ebbe9b 1260
e97012de
MW
1261;;;--------------------------------------------------------------------------
1262;;; tinydns-data output format.
1263
422e7cfc 1264(export 'tinydns-output)
e97012de
MW
1265(defun tinydns-output (code &rest fields)
1266 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1267
9f408c60 1268(defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
e97012de
MW
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)
1274 (>= byte 128)
1275 (member byte '(#\: #\\) :key #'char-code))
1276 (format out "\\~3,'0O" byte)
1277 (write-char (code-char byte) out)))))
1278 (zr-ttl zr)))
1279
146571da
MW
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)))
1283
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)))
1287 (zr-ttl zr)))
1288
1289(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1290 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1291
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)))
1294
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)))
1297
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))))
1302
146571da
MW
1303(defmethod zone-write-header ((format (eql :tinydns)) zone)
1304 (format *zone-output-stream* "~
e97012de
MW
1305### Zone file `~(~A~)'
1306### (generated ~A)
1307~%"
1308 (zone-name zone)
1309 (iso-date :now :datep t :timep t))
1310 (let ((soa (zone-soa zone)))
1311 (tinydns-output #\Z
1312 (zone-name zone)
1313 (soa-source soa)
1314 (let* ((name (copy-seq (soa-admin soa)))
1315 (at (position #\@ name)))
1316 (when at (setf (char name at) #\.))
1317 name)
1318 (soa-serial soa)
1319 (soa-refresh soa)
1320 (soa-expire soa)
1321 (soa-min-ttl soa)
146571da 1322 (zone-default-ttl zone))))
e97012de 1323
7e282fb5 1324;;;----- That's all, folks --------------------------------------------------