Handle domain names properly, including RFC1035 quoting.
[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
MW
893(defzoneparse :srv (name data rec :zname zname)
894 ":srv (((SERVICE &key :port) (PROVIDER &key :port :prio :weight :ip)*)*)"
895 (dolist (srv data)
896 (destructuring-bind (servopts &rest providers) srv
897 (destructuring-bind
898 (service &key ((:port default-port)) (protocol :tcp))
899 (listify servopts)
900 (unless default-port
901 (let ((serv (serv-by-name service protocol)))
902 (setf default-port (and serv (serv-port serv)))))
db43369d
MW
903 (let ((rname (flet ((prepend (tag tail)
904 (domain-name-concat
905 (make-domain-name
906 :labels (list (format nil "_~(~A~)" tag)))
907 tail)))
908 (prepend service (prepend protocol name)))))
716105aa
MW
909 (dolist (prov providers)
910 (destructuring-bind
911 (srvname
912 &key
913 (port default-port)
914 (prio *default-mx-priority*)
915 (weight 0)
916 ip)
917 (listify prov)
918 (let ((host (zone-parse-host srvname zname)))
32ebbe9b 919 (when ip (zone-set-address #'rec ip :name host))
716105aa
MW
920 (rec :name rname
921 :data (list prio weight port host))))))))))
922
9f408c60
MW
923(defmethod zone-record-rrdata ((type (eql :srv)) zr)
924 (destructuring-bind (prio weight port host) (zr-data zr)
925 (rec-u16 prio)
926 (rec-u16 weight)
927 (rec-u16 port)
928 (rec-name host))
929 33)
930
a15288b4 931(defzoneparse :net (name data rec)
932 ":net (NETWORK*)"
933 (dolist (net (listify data))
32ebbe9b
MW
934 (dolist (ipn (net-ipnets (net-must-find net)))
935 (let* ((base (ipnet-net ipn))
936 (rrtype (ipaddr-rrtype base)))
937 (flet ((frob (kind addr)
938 (when addr
939 (rec :name (zone-parse-host kind name)
940 :type rrtype
941 :data addr))))
942 (frob "net" base)
943 (frob "mask" (ipaddr (ipnet-mask ipn) (ipnet-family ipn)))
944 (frob "bcast" (ipnet-broadcast ipn)))))))
7fff3797 945
7e282fb5 946(defzoneparse (:rev :reverse) (name data rec)
32ebbe9b 947 ":reverse ((NET &key :prefix-bits :family) ZONE*)
679775ba
MW
948
949 Add a reverse record each host in the ZONEs (or all zones) that lies
32ebbe9b 950 within NET."
7e282fb5 951 (setf data (listify data))
32ebbe9b
MW
952 (destructuring-bind (net &key prefix-bits (family *address-family*))
953 (listify (car data))
954
955 (dolist (ipn (net-parse-to-ipnets net family))
956 (let* ((seen (make-hash-table :test #'equal))
957 (width (ipnet-width ipn))
958 (frag-len (if prefix-bits (- width prefix-bits)
959 (ipnet-changeable-bits width (ipnet-mask ipn)))))
960 (dolist (z (or (cdr data) (hash-table-keys *zones*)))
961 (dolist (zr (zone-records (zone-find z)))
962 (when (and (eq (zr-type zr) (ipaddr-rrtype (ipnet-net ipn)))
963 (zr-make-ptr-p zr)
964 (ipaddr-networkp (ipaddr-addr (zr-data zr)) ipn))
965 (let* ((frag (reverse-domain-fragment (zr-data zr)
966 0 frag-len))
db43369d
MW
967 (name (domain-name-concat frag name))
968 (name-string (princ-to-string name)))
969 (unless (gethash name-string seen)
32ebbe9b
MW
970 (rec :name name :type :ptr
971 :ttl (zr-ttl zr) :data (zr-name zr))
db43369d 972 (setf (gethash name-string seen) t))))))))))
32ebbe9b 973
74962377 974(defzoneparse :multi (name data rec :zname zname :ttl ttl)
32ebbe9b
MW
975 ":multi (((NET*) &key :start :end :family :suffix) . REC)
976
977 Output multiple records covering a portion of the reverse-resolution
978 namespace corresponding to the particular NETs. The START and END bounds
979 default to the most significant variable component of the
980 reverse-resolution domain.
981
982 The REC tail is a sequence of record forms (as handled by
983 `zone-process-records') to be emitted for each covered address. Within
984 the bodies of these forms, the symbol `*' will be replaced by the
985 domain-name fragment corresponding to the current host, optionally
986 followed by the SUFFIX.
987
988 Examples:
989
990 (:multi ((delegated-subnet :start 8)
991 :ns (some.ns.delegated.example :ip \"169.254.5.2\")))
992
993 (:multi ((tiny-subnet :suffix \"128.10.254.169.in-addr.arpa\")
994 :cname *))
995
996 Obviously, nested `:multi' records won't work well."
997
db43369d
MW
998 (destructuring-bind (nets
999 &key start end ((:suffix raw-suffix))
1000 (family *address-family*))
32ebbe9b 1001 (listify (car data))
db43369d
MW
1002 (let ((suffix (if (not raw-suffix)
1003 (make-domain-name :labels nil :absolutep nil)
1004 (zone-parse-host raw-suffix))))
1005 (dolist (net (listify nets))
1006 (dolist (ipn (net-parse-to-ipnets net family))
1007 (let* ((addr (ipnet-net ipn))
1008 (width (ipaddr-width addr))
1009 (comp-width (reverse-domain-component-width addr))
1010 (end (round-up (or end
1011 (ipnet-changeable-bits width
1012 (ipnet-mask ipn)))
1013 comp-width))
1014 (start (round-down (or start (- end comp-width))
1015 comp-width))
1016 (map (ipnet-host-map ipn)))
1017 (multiple-value-bind (host-step host-limit)
1018 (ipnet-index-bounds map start end)
1019 (do ((index 0 (+ index host-step)))
1020 ((> index host-limit))
1021 (let* ((addr (ipnet-index-host map index))
1022 (frag (reverse-domain-fragment addr start end))
1023 (target (reduce #'domain-name-concat
1024 (list frag suffix zname)
1025 :from-end t
1026 :initial-value root-domain)))
1027 (dolist (zr (zone-parse-records (domain-name-concat frag
1028 zname)
1029 ttl
1030 (subst target '*
1031 (cdr data))))
1032 (rec :name (zr-name zr)
1033 :type (zr-type zr)
1034 :data (zr-data zr)
1035 :ttl (zr-ttl zr)
1036 :make-ptr-p (zr-make-ptr-p zr))))))))))))
7e282fb5 1037
fe5fb85a
MW
1038;;;--------------------------------------------------------------------------
1039;;; Zone file output.
7e282fb5 1040
afa2e2f1 1041(export 'zone-write)
a567a3bc
MW
1042(defgeneric zone-write (format zone stream)
1043 (:documentation "Write ZONE's records to STREAM in the specified FORMAT."))
1044
1045(defvar *writing-zone* nil
1046 "The zone currently being written.")
1047
1048(defvar *zone-output-stream* nil
1049 "Stream to write zone data on.")
1050
9f408c60 1051(export 'zone-write-raw-rrdata)
146571da
MW
1052(defgeneric zone-write-raw-rrdata (format zr type data)
1053 (:documentation "Write an otherwise unsupported record in a given FORMAT.
1054
1055 ZR gives the record object, which carries the name and TTL; the TYPE is
1056 the numeric RRTYPE code; and DATA is an octet vector giving the RRDATA.
1057 This is used by the default `zone-write-record' method to handle record
1058 types which aren't directly supported by the format driver."))
1059
1060(export 'zone-write-header)
1061(defgeneric zone-write-header (format zone)
1062 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1063
1064 The header includes any kind of initial comment, the SOA record, and any
1065 other necessary preamble. There is no default implementation.
1066
1067 This is part of the protocol used by the default method on `zone-write';
1068 if you override that method."))
1069
1070(export 'zone-write-trailer)
1071(defgeneric zone-write-trailer (format zone)
1072 (:documentation "Emit the header for a ZONE, in a given FORMAT.
1073
1074 The footer may be empty, and is so by default.
1075
1076 This is part of the protocol used by the default method on `zone-write';
1077 if you override that method.")
1078 (:method (format zone)
1079 (declare (ignore format zone))
1080 nil))
1081
1082(export 'zone-write-record)
1083(defgeneric zone-write-record (format type zr)
1084 (:documentation "Emit a record of the given TYPE (a keyword).
1085
9f408c60
MW
1086 The default implementation builds the raw RRDATA and passes it to
1087 `zone-write-raw-rrdata'.")
1088 (:method (format type zr)
1089 (let* (code
1090 (data (build-record (setf code (zone-record-rrdata type zr)))))
1091 (zone-write-raw-rrdata format zr code data))))
146571da
MW
1092
1093(defmethod zone-write (format zone stream)
1094 "This default method calls `zone-write-header', then `zone-write-record'
1095 for each record in the zone, and finally `zone-write-trailer'. While it's
1096 running, `*writing-zone*' is bound to the zone object, and
1097 `*zone-output-stream*' to the output stream."
a567a3bc
MW
1098 (let ((*writing-zone* zone)
1099 (*zone-output-stream* stream))
146571da
MW
1100 (zone-write-header format zone)
1101 (dolist (zr (zone-records-sorted zone))
1102 (zone-write-record format (zr-type zr) zr))
1103 (zone-write-trailer format zone)))
a567a3bc 1104
afa2e2f1 1105(export 'zone-save)
a567a3bc
MW
1106(defun zone-save (zones &key (format :bind))
1107 "Write the named ZONES to files. If no zones are given, write all the
1108 zones."
1109 (unless zones
1110 (setf zones (hash-table-keys *zones*)))
1111 (safely (safe)
1112 (dolist (z zones)
1113 (let ((zz (zone-find z)))
1114 (unless zz
1115 (error "Unknown zone `~A'." z))
1116 (let ((stream (safely-open-output-stream safe
1117 (zone-file-name z :zone))))
1118 (zone-write format zz stream))))))
1119
1120;;;--------------------------------------------------------------------------
1121;;; Bind format output.
1122
80b5c2ff
MW
1123(defvar *bind-last-record-name* nil
1124 "The previously emitted record name.
1125
1126 Used for eliding record names on output.")
1127
afa2e2f1 1128(export 'bind-hostname)
a567a3bc 1129(defun bind-hostname (hostname)
db43369d
MW
1130 (let ((zone (domain-name-labels (zone-name *writing-zone*)))
1131 (name (domain-name-labels hostname)))
1132 (loop
1133 (unless (and zone name (string= (car zone) (car name)))
1134 (return))
1135 (pop zone) (pop name))
1136 (flet ((stitch (labels absolutep)
1137 (format nil "~{~A~^.~}~@[.~]"
1138 (reverse (mapcar #'quotify-label labels))
1139 absolutep)))
1140 (cond (zone (stitch (domain-name-labels hostname) t))
1141 (name (stitch name nil))
1142 (t "@")))))
80b5c2ff
MW
1143
1144(export 'bind-output-hostname)
1145(defun bind-output-hostname (hostname)
1146 (let ((name (bind-hostname hostname)))
1147 (cond ((and *bind-last-record-name*
1148 (string= name *bind-last-record-name*))
1149 "")
1150 (t
1151 (setf *bind-last-record-name* name)
1152 name))))
a567a3bc 1153
146571da
MW
1154(defmethod zone-write :around ((format (eql :bind)) zone stream)
1155 (let ((*bind-last-record-name* nil))
1156 (call-next-method)))
32ebbe9b 1157
146571da
MW
1158(defmethod zone-write-header ((format (eql :bind)) zone)
1159 (format *zone-output-stream* "~
7e282fb5 1160;;; Zone file `~(~A~)'
1161;;; (generated ~A)
1162
7d593efd
MW
1163$ORIGIN ~0@*~(~A.~)
1164$TTL ~2@*~D~2%"
7e282fb5 1165 (zone-name zone)
1166 (iso-date :now :datep t :timep t)
1167 (zone-default-ttl zone))
146571da 1168 (let* ((soa (zone-soa zone))
a567a3bc
MW
1169 (admin (let* ((name (soa-admin soa))
1170 (at (position #\@ name))
1171 (copy (format nil "~(~A~)." name)))
1172 (when at
1173 (setf (char copy at) #\.))
1174 copy)))
146571da 1175 (format *zone-output-stream* "~
fffebf35
MW
1176~A~30TIN SOA~40T~A (
1177~55@A~60T ;administrator
7e282fb5 1178~45T~10D~60T ;serial
1179~45T~10D~60T ;refresh
1180~45T~10D~60T ;retry
1181~45T~10D~60T ;expire
1182~45T~10D )~60T ;min-ttl~2%"
80b5c2ff 1183 (bind-output-hostname (zone-name zone))
a567a3bc
MW
1184 (bind-hostname (soa-source soa))
1185 admin
7e282fb5 1186 (soa-serial soa)
1187 (soa-refresh soa)
1188 (soa-retry soa)
1189 (soa-expire soa)
146571da 1190 (soa-min-ttl soa))))
a567a3bc 1191
afa2e2f1 1192(export 'bind-format-record)
146571da 1193(defun bind-format-record (zr format &rest args)
a567a3bc
MW
1194 (format *zone-output-stream*
1195 "~A~20T~@[~8D~]~30TIN ~A~40T~?~%"
146571da
MW
1196 (bind-output-hostname (zr-name zr))
1197 (let ((ttl (zr-ttl zr)))
1198 (and (/= ttl (zone-default-ttl *writing-zone*))
1199 ttl))
1200 (string-upcase (symbol-name (zr-type zr)))
a567a3bc
MW
1201 format args))
1202
9f408c60
MW
1203(defmethod zone-write-raw-rrdata ((format (eql :bind)) zr type data)
1204 (format *zone-output-stream*
1205 "~A~20T~@[~8D~]~30TIN TYPE~A~40T\\# ~A"
1206 (bind-output-hostname (zr-name zr))
1207 (let ((ttl (zr-ttl zr)))
1208 (and (/= ttl (zone-default-ttl *writing-zone*))
1209 ttl))
1210 type
1211 (length data))
1212 (let* ((hex (with-output-to-string (out)
1213 (dotimes (i (length data))
1214 (format out "~(~2,'0X~)" (aref data i)))))
1215 (len (length hex)))
1216 (cond ((< len 24)
1217 (format *zone-output-stream* " ~A~%" hex))
1218 (t
1219 (format *zone-output-stream* " (")
1220 (let ((i 0))
1221 (loop
1222 (when (>= i len) (return))
1223 (let ((j (min (+ i 64) len)))
1224 (format *zone-output-stream* "~%~8T~A" (subseq hex i j))
1225 (setf i j))))
1226 (format *zone-output-stream* " )~%")))))
1227
146571da
MW
1228(defmethod zone-write-record ((format (eql :bind)) (type (eql :a)) zr)
1229 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1230
1231(defmethod zone-write-record ((format (eql :bind)) (type (eql :aaaa)) zr)
1232 (bind-format-record zr "~A" (ipaddr-string (zr-data zr))))
1233
1234(defmethod zone-write-record ((format (eql :bind)) (type (eql :ptr)) zr)
1235 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1236
1237(defmethod zone-write-record ((format (eql :bind)) (type (eql :cname)) zr)
1238 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1239
1240(defmethod zone-write-record ((format (eql :bind)) (type (eql :ns)) zr)
1241 (bind-format-record zr "~A" (bind-hostname (zr-data zr))))
1242
1243(defmethod zone-write-record ((format (eql :bind)) (type (eql :mx)) zr)
1244 (bind-format-record zr "~2D ~A"
1245 (cdr (zr-data zr))
1246 (bind-hostname (car (zr-data zr)))))
1247
1248(defmethod zone-write-record ((format (eql :bind)) (type (eql :srv)) zr)
1249 (destructuring-bind (prio weight port host) (zr-data zr)
1250 (bind-format-record zr "~2D ~5D ~5D ~A"
1251 prio weight port (bind-hostname host))))
1252
1253(defmethod zone-write-record ((format (eql :bind)) (type (eql :sshfp)) zr)
1254 (bind-format-record zr "~{~2D ~2D ~A~}" (zr-data zr)))
1255
1256(defmethod zone-write-record ((format (eql :bind)) (type (eql :txt)) zr)
1257 (bind-format-record zr "~{~#[\"\"~;~S~:;(~@{~%~8T~S~} )~]~}" (zr-data zr)))
32ebbe9b 1258
e97012de
MW
1259;;;--------------------------------------------------------------------------
1260;;; tinydns-data output format.
1261
422e7cfc 1262(export 'tinydns-output)
e97012de
MW
1263(defun tinydns-output (code &rest fields)
1264 (format *zone-output-stream* "~C~{~@[~A~]~^:~}~%" code fields))
1265
9f408c60 1266(defmethod zone-write-raw-rrdata ((format (eql :tinydns)) zr type data)
e97012de
MW
1267 (tinydns-output #\: (zr-name zr) type
1268 (with-output-to-string (out)
1269 (dotimes (i (length data))
1270 (let ((byte (aref data i)))
1271 (if (or (<= byte 32)
1272 (>= byte 128)
1273 (member byte '(#\: #\\) :key #'char-code))
1274 (format out "\\~3,'0O" byte)
1275 (write-char (code-char byte) out)))))
1276 (zr-ttl zr)))
1277
146571da
MW
1278(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :a)) zr)
1279 (tinydns-output #\+ (zr-name zr)
1280 (ipaddr-string (zr-data zr)) (zr-ttl zr)))
1281
1282(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :aaaa)) zr)
1283 (tinydns-output #\3 (zr-name zr)
1284 (format nil "~(~32,'0X~)" (ipaddr-addr (zr-data zr)))
1285 (zr-ttl zr)))
1286
1287(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ptr)) zr)
1288 (tinydns-output #\^ (zr-name zr) (zr-data zr) (zr-ttl zr)))
1289
1290(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :cname)) zr)
1291 (tinydns-output #\C (zr-name zr) (zr-data zr) (zr-ttl zr)))
1292
1293(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :ns)) zr)
1294 (tinydns-output #\& (zr-name zr) nil (zr-data zr) (zr-ttl zr)))
1295
1296(defmethod zone-write-record ((format (eql :tinydns)) (type (eql :mx)) zr)
1297 (let ((name (car (zr-data zr)))
1298 (prio (cdr (zr-data zr))))
1299 (tinydns-output #\@ (zr-name zr) nil name prio (zr-ttl zr))))
1300
146571da
MW
1301(defmethod zone-write-header ((format (eql :tinydns)) zone)
1302 (format *zone-output-stream* "~
e97012de
MW
1303### Zone file `~(~A~)'
1304### (generated ~A)
1305~%"
1306 (zone-name zone)
1307 (iso-date :now :datep t :timep t))
1308 (let ((soa (zone-soa zone)))
1309 (tinydns-output #\Z
1310 (zone-name zone)
1311 (soa-source soa)
1312 (let* ((name (copy-seq (soa-admin soa)))
1313 (at (position #\@ name)))
1314 (when at (setf (char name at) #\.))
1315 name)
1316 (soa-serial soa)
1317 (soa-refresh soa)
1318 (soa-expire soa)
1319 (soa-min-ttl soa)
146571da 1320 (zone-default-ttl zone))))
e97012de 1321
7e282fb5 1322;;;----- That's all, folks --------------------------------------------------