]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - contrib/bind9/lib/dns/masterdump.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / contrib / bind9 / lib / dns / masterdump.c
1 /*
2  * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 1999-2003  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: masterdump.c,v 1.94.50.2 2009/01/18 23:47:40 tbox Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <stdlib.h>
25
26 #include <isc/event.h>
27 #include <isc/file.h>
28 #include <isc/magic.h>
29 #include <isc/mem.h>
30 #include <isc/print.h>
31 #include <isc/stdio.h>
32 #include <isc/string.h>
33 #include <isc/task.h>
34 #include <isc/time.h>
35 #include <isc/util.h>
36
37 #include <dns/db.h>
38 #include <dns/dbiterator.h>
39 #include <dns/events.h>
40 #include <dns/fixedname.h>
41 #include <dns/lib.h>
42 #include <dns/log.h>
43 #include <dns/master.h>
44 #include <dns/masterdump.h>
45 #include <dns/rdata.h>
46 #include <dns/rdataclass.h>
47 #include <dns/rdataset.h>
48 #include <dns/rdatasetiter.h>
49 #include <dns/rdatatype.h>
50 #include <dns/result.h>
51 #include <dns/time.h>
52 #include <dns/ttl.h>
53
54 #define DNS_DCTX_MAGIC          ISC_MAGIC('D', 'c', 't', 'x')
55 #define DNS_DCTX_VALID(d)       ISC_MAGIC_VALID(d, DNS_DCTX_MAGIC)
56
57 #define RETERR(x) do { \
58         isc_result_t _r = (x); \
59         if (_r != ISC_R_SUCCESS) \
60                 return (_r); \
61         } while (0)
62
63 struct dns_master_style {
64         unsigned int flags;             /* DNS_STYLEFLAG_* */
65         unsigned int ttl_column;
66         unsigned int class_column;
67         unsigned int type_column;
68         unsigned int rdata_column;
69         unsigned int line_length;
70         unsigned int tab_width;
71 };
72
73 /*%
74  * The maximum length of the newline+indentation that is output
75  * when inserting a line break in an RR.  This effectively puts an
76  * upper limits on the value of "rdata_column", because if it is
77  * very large, the tabs and spaces needed to reach it will not fit.
78  */
79 #define DNS_TOTEXT_LINEBREAK_MAXLEN 100
80
81 /*%
82  * Context structure for a masterfile dump in progress.
83  */
84 typedef struct dns_totext_ctx {
85         dns_master_style_t      style;
86         isc_boolean_t           class_printed;
87         char *                  linebreak;
88         char                    linebreak_buf[DNS_TOTEXT_LINEBREAK_MAXLEN];
89         dns_name_t *            origin;
90         dns_name_t *            neworigin;
91         dns_fixedname_t         origin_fixname;
92         isc_uint32_t            current_ttl;
93         isc_boolean_t           current_ttl_valid;
94 } dns_totext_ctx_t;
95
96 LIBDNS_EXTERNAL_DATA const dns_master_style_t
97 dns_master_style_default = {
98         DNS_STYLEFLAG_OMIT_OWNER |
99         DNS_STYLEFLAG_OMIT_CLASS |
100         DNS_STYLEFLAG_REL_OWNER |
101         DNS_STYLEFLAG_REL_DATA |
102         DNS_STYLEFLAG_OMIT_TTL |
103         DNS_STYLEFLAG_TTL |
104         DNS_STYLEFLAG_COMMENT |
105         DNS_STYLEFLAG_MULTILINE,
106         24, 24, 24, 32, 80, 8
107 };
108
109 LIBDNS_EXTERNAL_DATA const dns_master_style_t
110 dns_master_style_full = {
111         DNS_STYLEFLAG_COMMENT |
112         DNS_STYLEFLAG_RESIGN,
113         46, 46, 46, 64, 120, 8
114 };
115
116 LIBDNS_EXTERNAL_DATA const dns_master_style_t
117 dns_master_style_explicitttl = {
118         DNS_STYLEFLAG_OMIT_OWNER |
119         DNS_STYLEFLAG_OMIT_CLASS |
120         DNS_STYLEFLAG_REL_OWNER |
121         DNS_STYLEFLAG_REL_DATA |
122         DNS_STYLEFLAG_COMMENT |
123         DNS_STYLEFLAG_MULTILINE,
124         24, 32, 32, 40, 80, 8
125 };
126
127 LIBDNS_EXTERNAL_DATA const dns_master_style_t
128 dns_master_style_cache = {
129         DNS_STYLEFLAG_OMIT_OWNER |
130         DNS_STYLEFLAG_OMIT_CLASS |
131         DNS_STYLEFLAG_MULTILINE |
132         DNS_STYLEFLAG_TRUST |
133         DNS_STYLEFLAG_NCACHE,
134         24, 32, 32, 40, 80, 8
135 };
136
137 LIBDNS_EXTERNAL_DATA const dns_master_style_t
138 dns_master_style_simple = {
139         0,
140         24, 32, 32, 40, 80, 8
141 };
142
143 /*%
144  * A style suitable for dns_rdataset_totext().
145  */
146 LIBDNS_EXTERNAL_DATA const dns_master_style_t
147 dns_master_style_debug = {
148         DNS_STYLEFLAG_REL_OWNER,
149         24, 32, 40, 48, 80, 8
150 };
151
152
153 #define N_SPACES 10
154 static char spaces[N_SPACES+1] = "          ";
155
156 #define N_TABS 10
157 static char tabs[N_TABS+1] = "\t\t\t\t\t\t\t\t\t\t";
158
159 struct dns_dumpctx {
160         unsigned int            magic;
161         isc_mem_t               *mctx;
162         isc_mutex_t             lock;
163         unsigned int            references;
164         isc_boolean_t           canceled;
165         isc_boolean_t           first;
166         isc_boolean_t           do_date;
167         isc_stdtime_t           now;
168         FILE                    *f;
169         dns_db_t                *db;
170         dns_dbversion_t         *version;
171         dns_dbiterator_t        *dbiter;
172         dns_totext_ctx_t        tctx;
173         isc_task_t              *task;
174         dns_dumpdonefunc_t      done;
175         void                    *done_arg;
176         unsigned int            nodes;
177         /* dns_master_dumpinc() */
178         char                    *file;
179         char                    *tmpfile;
180         dns_masterformat_t      format;
181         isc_result_t            (*dumpsets)(isc_mem_t *mctx, dns_name_t *name,
182                                             dns_rdatasetiter_t *rdsiter,
183                                             dns_totext_ctx_t *ctx,
184                                             isc_buffer_t *buffer, FILE *f);
185 };
186
187 #define NXDOMAIN(x) (((x)->attributes & DNS_RDATASETATTR_NXDOMAIN) != 0)
188
189 /*%
190  * Output tabs and spaces to go from column '*current' to
191  * column 'to', and update '*current' to reflect the new
192  * current column.
193  */
194 static isc_result_t
195 indent(unsigned int *current, unsigned int to, int tabwidth,
196        isc_buffer_t *target)
197 {
198         isc_region_t r;
199         unsigned char *p;
200         unsigned int from;
201         int ntabs, nspaces, t;
202
203         from = *current;
204
205         if (to < from + 1)
206                 to = from + 1;
207
208         ntabs = to / tabwidth - from / tabwidth;
209         if (ntabs < 0)
210                 ntabs = 0;
211
212         if (ntabs > 0) {
213                 isc_buffer_availableregion(target, &r);
214                 if (r.length < (unsigned) ntabs)
215                         return (ISC_R_NOSPACE);
216                 p = r.base;
217
218                 t = ntabs;
219                 while (t) {
220                         int n = t;
221                         if (n > N_TABS)
222                                 n = N_TABS;
223                         memcpy(p, tabs, n);
224                         p += n;
225                         t -= n;
226                 }
227                 isc_buffer_add(target, ntabs);
228                 from = (to / tabwidth) * tabwidth;
229         }
230
231         nspaces = to - from;
232         INSIST(nspaces >= 0);
233
234         isc_buffer_availableregion(target, &r);
235         if (r.length < (unsigned) nspaces)
236                 return (ISC_R_NOSPACE);
237         p = r.base;
238
239         t = nspaces;
240         while (t) {
241                 int n = t;
242                 if (n > N_SPACES)
243                         n = N_SPACES;
244                 memcpy(p, spaces, n);
245                 p += n;
246                 t -= n;
247         }
248         isc_buffer_add(target, nspaces);
249
250         *current = to;
251         return (ISC_R_SUCCESS);
252 }
253
254 static isc_result_t
255 totext_ctx_init(const dns_master_style_t *style, dns_totext_ctx_t *ctx) {
256         isc_result_t result;
257
258         REQUIRE(style->tab_width != 0);
259
260         ctx->style = *style;
261         ctx->class_printed = ISC_FALSE;
262
263         dns_fixedname_init(&ctx->origin_fixname);
264
265         /*
266          * Set up the line break string if needed.
267          */
268         if ((ctx->style.flags & DNS_STYLEFLAG_MULTILINE) != 0) {
269                 isc_buffer_t buf;
270                 isc_region_t r;
271                 unsigned int col = 0;
272
273                 isc_buffer_init(&buf, ctx->linebreak_buf,
274                                 sizeof(ctx->linebreak_buf));
275
276                 isc_buffer_availableregion(&buf, &r);
277                 if (r.length < 1)
278                         return (DNS_R_TEXTTOOLONG);
279                 r.base[0] = '\n';
280                 isc_buffer_add(&buf, 1);
281
282                 result = indent(&col, ctx->style.rdata_column,
283                                 ctx->style.tab_width, &buf);
284                 /*
285                  * Do not return ISC_R_NOSPACE if the line break string
286                  * buffer is too small, because that would just make
287                  * dump_rdataset() retry indefinitely with ever
288                  * bigger target buffers.  That's a different buffer,
289                  * so it won't help.  Use DNS_R_TEXTTOOLONG as a substitute.
290                  */
291                 if (result == ISC_R_NOSPACE)
292                         return (DNS_R_TEXTTOOLONG);
293                 if (result != ISC_R_SUCCESS)
294                         return (result);
295
296                 isc_buffer_availableregion(&buf, &r);
297                 if (r.length < 1)
298                         return (DNS_R_TEXTTOOLONG);
299                 r.base[0] = '\0';
300                 isc_buffer_add(&buf, 1);
301                 ctx->linebreak = ctx->linebreak_buf;
302         } else {
303                 ctx->linebreak = NULL;
304         }
305
306         ctx->origin = NULL;
307         ctx->neworigin = NULL;
308         ctx->current_ttl = 0;
309         ctx->current_ttl_valid = ISC_FALSE;
310
311         return (ISC_R_SUCCESS);
312 }
313
314 #define INDENT_TO(col) \
315         do { \
316                  if ((result = indent(&column, ctx->style.col, \
317                                       ctx->style.tab_width, target)) \
318                      != ISC_R_SUCCESS) \
319                             return (result); \
320         } while (0)
321
322
323 static isc_result_t
324 str_totext(const char *source, isc_buffer_t *target) {
325         unsigned int l;
326         isc_region_t region;
327
328         isc_buffer_availableregion(target, &region);
329         l = strlen(source);
330
331         if (l > region.length)
332                 return (ISC_R_NOSPACE);
333
334         memcpy(region.base, source, l);
335         isc_buffer_add(target, l);
336         return (ISC_R_SUCCESS);
337 }
338
339 /*
340  * Convert 'rdataset' to master file text format according to 'ctx',
341  * storing the result in 'target'.  If 'owner_name' is NULL, it
342  * is omitted; otherwise 'owner_name' must be valid and have at least
343  * one label.
344  */
345
346 static isc_result_t
347 rdataset_totext(dns_rdataset_t *rdataset,
348                 dns_name_t *owner_name,
349                 dns_totext_ctx_t *ctx,
350                 isc_boolean_t omit_final_dot,
351                 isc_buffer_t *target)
352 {
353         isc_result_t result;
354         unsigned int column;
355         isc_boolean_t first = ISC_TRUE;
356         isc_uint32_t current_ttl;
357         isc_boolean_t current_ttl_valid;
358         dns_rdatatype_t type;
359
360         REQUIRE(DNS_RDATASET_VALID(rdataset));
361
362         rdataset->attributes |= DNS_RDATASETATTR_LOADORDER;
363         result = dns_rdataset_first(rdataset);
364         REQUIRE(result == ISC_R_SUCCESS);
365
366         current_ttl = ctx->current_ttl;
367         current_ttl_valid = ctx->current_ttl_valid;
368
369         do {
370                 column = 0;
371
372                 /*
373                  * Owner name.
374                  */
375                 if (owner_name != NULL &&
376                     ! ((ctx->style.flags & DNS_STYLEFLAG_OMIT_OWNER) != 0 &&
377                        !first))
378                 {
379                         unsigned int name_start = target->used;
380                         RETERR(dns_name_totext(owner_name,
381                                                omit_final_dot,
382                                                target));
383                         column += target->used - name_start;
384                 }
385
386                 /*
387                  * TTL.
388                  */
389                 if ((ctx->style.flags & DNS_STYLEFLAG_NO_TTL) == 0 &&
390                     !((ctx->style.flags & DNS_STYLEFLAG_OMIT_TTL) != 0 &&
391                       current_ttl_valid &&
392                       rdataset->ttl == current_ttl))
393                 {
394                         char ttlbuf[64];
395                         isc_region_t r;
396                         unsigned int length;
397
398                         INDENT_TO(ttl_column);
399                         length = snprintf(ttlbuf, sizeof(ttlbuf), "%u",
400                                           rdataset->ttl);
401                         INSIST(length <= sizeof(ttlbuf));
402                         isc_buffer_availableregion(target, &r);
403                         if (r.length < length)
404                                 return (ISC_R_NOSPACE);
405                         memcpy(r.base, ttlbuf, length);
406                         isc_buffer_add(target, length);
407                         column += length;
408
409                         /*
410                          * If the $TTL directive is not in use, the TTL we
411                          * just printed becomes the default for subsequent RRs.
412                          */
413                         if ((ctx->style.flags & DNS_STYLEFLAG_TTL) == 0) {
414                                 current_ttl = rdataset->ttl;
415                                 current_ttl_valid = ISC_TRUE;
416                         }
417                 }
418
419                 /*
420                  * Class.
421                  */
422                 if ((ctx->style.flags & DNS_STYLEFLAG_NO_CLASS) == 0 &&
423                     ((ctx->style.flags & DNS_STYLEFLAG_OMIT_CLASS) == 0 ||
424                      ctx->class_printed == ISC_FALSE))
425                 {
426                         unsigned int class_start;
427                         INDENT_TO(class_column);
428                         class_start = target->used;
429                         result = dns_rdataclass_totext(rdataset->rdclass,
430                                                        target);
431                         if (result != ISC_R_SUCCESS)
432                                 return (result);
433                         column += (target->used - class_start);
434                 }
435
436                 /*
437                  * Type.
438                  */
439
440                 if (rdataset->type == 0) {
441                         type = rdataset->covers;
442                 } else {
443                         type = rdataset->type;
444                 }
445
446                 {
447                         unsigned int type_start;
448                         INDENT_TO(type_column);
449                         type_start = target->used;
450                         if (rdataset->type == 0)
451                                 RETERR(str_totext("\\-", target));
452                         result = dns_rdatatype_totext(type, target);
453                         if (result != ISC_R_SUCCESS)
454                                 return (result);
455                         column += (target->used - type_start);
456                 }
457
458                 /*
459                  * Rdata.
460                  */
461                 INDENT_TO(rdata_column);
462                 if (rdataset->type == 0) {
463                         if (NXDOMAIN(rdataset))
464                                 RETERR(str_totext(";-$NXDOMAIN\n", target));
465                         else
466                                 RETERR(str_totext(";-$NXRRSET\n", target));
467                 } else {
468                         dns_rdata_t rdata = DNS_RDATA_INIT;
469                         isc_region_t r;
470
471                         dns_rdataset_current(rdataset, &rdata);
472
473                         RETERR(dns_rdata_tofmttext(&rdata,
474                                                    ctx->origin,
475                                                    ctx->style.flags,
476                                                    ctx->style.line_length -
477                                                        ctx->style.rdata_column,
478                                                    ctx->linebreak,
479                                                    target));
480
481                         isc_buffer_availableregion(target, &r);
482                         if (r.length < 1)
483                                 return (ISC_R_NOSPACE);
484                         r.base[0] = '\n';
485                         isc_buffer_add(target, 1);
486                 }
487
488                 first = ISC_FALSE;
489                 result = dns_rdataset_next(rdataset);
490         } while (result == ISC_R_SUCCESS);
491
492         if (result != ISC_R_NOMORE)
493                 return (result);
494
495         /*
496          * Update the ctx state to reflect what we just printed.
497          * This is done last, only when we are sure we will return
498          * success, because this function may be called multiple
499          * times with increasing buffer sizes until it succeeds,
500          * and failed attempts must not update the state prematurely.
501          */
502         ctx->class_printed = ISC_TRUE;
503         ctx->current_ttl= current_ttl;
504         ctx->current_ttl_valid = current_ttl_valid;
505
506         return (ISC_R_SUCCESS);
507 }
508
509 /*
510  * Print the name, type, and class of an empty rdataset,
511  * such as those used to represent the question section
512  * of a DNS message.
513  */
514 static isc_result_t
515 question_totext(dns_rdataset_t *rdataset,
516                 dns_name_t *owner_name,
517                 dns_totext_ctx_t *ctx,
518                 isc_boolean_t omit_final_dot,
519                 isc_buffer_t *target)
520 {
521         unsigned int column;
522         isc_result_t result;
523         isc_region_t r;
524
525         REQUIRE(DNS_RDATASET_VALID(rdataset));
526         result = dns_rdataset_first(rdataset);
527         REQUIRE(result == ISC_R_NOMORE);
528
529         column = 0;
530
531         /* Owner name */
532         {
533                 unsigned int name_start = target->used;
534                 RETERR(dns_name_totext(owner_name,
535                                        omit_final_dot,
536                                        target));
537                 column += target->used - name_start;
538         }
539
540         /* Class */
541         {
542                 unsigned int class_start;
543                 INDENT_TO(class_column);
544                 class_start = target->used;
545                 result = dns_rdataclass_totext(rdataset->rdclass, target);
546                 if (result != ISC_R_SUCCESS)
547                         return (result);
548                 column += (target->used - class_start);
549         }
550
551         /* Type */
552         {
553                 unsigned int type_start;
554                 INDENT_TO(type_column);
555                 type_start = target->used;
556                 result = dns_rdatatype_totext(rdataset->type, target);
557                 if (result != ISC_R_SUCCESS)
558                         return (result);
559                 column += (target->used - type_start);
560         }
561
562         isc_buffer_availableregion(target, &r);
563         if (r.length < 1)
564                 return (ISC_R_NOSPACE);
565         r.base[0] = '\n';
566         isc_buffer_add(target, 1);
567
568         return (ISC_R_SUCCESS);
569 }
570
571 isc_result_t
572 dns_rdataset_totext(dns_rdataset_t *rdataset,
573                     dns_name_t *owner_name,
574                     isc_boolean_t omit_final_dot,
575                     isc_boolean_t question,
576                     isc_buffer_t *target)
577 {
578         dns_totext_ctx_t ctx;
579         isc_result_t result;
580         result = totext_ctx_init(&dns_master_style_debug, &ctx);
581         if (result != ISC_R_SUCCESS) {
582                 UNEXPECTED_ERROR(__FILE__, __LINE__,
583                                  "could not set master file style");
584                 return (ISC_R_UNEXPECTED);
585         }
586
587         /*
588          * The caller might want to give us an empty owner
589          * name (e.g. if they are outputting into a master
590          * file and this rdataset has the same name as the
591          * previous one.)
592          */
593         if (dns_name_countlabels(owner_name) == 0)
594                 owner_name = NULL;
595
596         if (question)
597                 return (question_totext(rdataset, owner_name, &ctx,
598                                         omit_final_dot, target));
599         else
600                 return (rdataset_totext(rdataset, owner_name, &ctx,
601                                         omit_final_dot, target));
602 }
603
604 isc_result_t
605 dns_master_rdatasettotext(dns_name_t *owner_name,
606                           dns_rdataset_t *rdataset,
607                           const dns_master_style_t *style,
608                           isc_buffer_t *target)
609 {
610         dns_totext_ctx_t ctx;
611         isc_result_t result;
612         result = totext_ctx_init(style, &ctx);
613         if (result != ISC_R_SUCCESS) {
614                 UNEXPECTED_ERROR(__FILE__, __LINE__,
615                                  "could not set master file style");
616                 return (ISC_R_UNEXPECTED);
617         }
618
619         return (rdataset_totext(rdataset, owner_name, &ctx,
620                                 ISC_FALSE, target));
621 }
622
623 isc_result_t
624 dns_master_questiontotext(dns_name_t *owner_name,
625                           dns_rdataset_t *rdataset,
626                           const dns_master_style_t *style,
627                           isc_buffer_t *target)
628 {
629         dns_totext_ctx_t ctx;
630         isc_result_t result;
631         result = totext_ctx_init(style, &ctx);
632         if (result != ISC_R_SUCCESS) {
633                 UNEXPECTED_ERROR(__FILE__, __LINE__,
634                                  "could not set master file style");
635                 return (ISC_R_UNEXPECTED);
636         }
637
638         return (question_totext(rdataset, owner_name, &ctx,
639                                 ISC_FALSE, target));
640 }
641
642 /*
643  * Print an rdataset.  'buffer' is a scratch buffer, which must have been
644  * dynamically allocated by the caller.  It must be large enough to
645  * hold the result from dns_ttl_totext().  If more than that is needed,
646  * the buffer will be grown automatically.
647  */
648
649 static isc_result_t
650 dump_rdataset(isc_mem_t *mctx, dns_name_t *name, dns_rdataset_t *rdataset,
651               dns_totext_ctx_t *ctx,
652               isc_buffer_t *buffer, FILE *f)
653 {
654         isc_region_t r;
655         isc_result_t result;
656
657         REQUIRE(buffer->length > 0);
658
659         /*
660          * Output a $TTL directive if needed.
661          */
662
663         if ((ctx->style.flags & DNS_STYLEFLAG_TTL) != 0) {
664                 if (ctx->current_ttl_valid == ISC_FALSE ||
665                     ctx->current_ttl != rdataset->ttl)
666                 {
667                         if ((ctx->style.flags & DNS_STYLEFLAG_COMMENT) != 0)
668                         {
669                                 isc_buffer_clear(buffer);
670                                 result = dns_ttl_totext(rdataset->ttl,
671                                                         ISC_TRUE, buffer);
672                                 INSIST(result == ISC_R_SUCCESS);
673                                 isc_buffer_usedregion(buffer, &r);
674                                 fprintf(f, "$TTL %u\t; %.*s\n", rdataset->ttl,
675                                         (int) r.length, (char *) r.base);
676                         } else {
677                                 fprintf(f, "$TTL %u\n", rdataset->ttl);
678                         }
679                         ctx->current_ttl = rdataset->ttl;
680                         ctx->current_ttl_valid = ISC_TRUE;
681                 }
682         }
683
684         isc_buffer_clear(buffer);
685
686         /*
687          * Generate the text representation of the rdataset into
688          * the buffer.  If the buffer is too small, grow it.
689          */
690         for (;;) {
691                 int newlength;
692                 void *newmem;
693                 result = rdataset_totext(rdataset, name, ctx,
694                                          ISC_FALSE, buffer);
695                 if (result != ISC_R_NOSPACE)
696                         break;
697
698                 newlength = buffer->length * 2;
699                 newmem = isc_mem_get(mctx, newlength);
700                 if (newmem == NULL)
701                         return (ISC_R_NOMEMORY);
702                 isc_mem_put(mctx, buffer->base, buffer->length);
703                 isc_buffer_init(buffer, newmem, newlength);
704         }
705         if (result != ISC_R_SUCCESS)
706                 return (result);
707
708         /*
709          * Write the buffer contents to the master file.
710          */
711         isc_buffer_usedregion(buffer, &r);
712         result = isc_stdio_write(r.base, 1, (size_t)r.length, f, NULL);
713
714         if (result != ISC_R_SUCCESS) {
715                 UNEXPECTED_ERROR(__FILE__, __LINE__,
716                                  "master file write failed: %s",
717                                  isc_result_totext(result));
718                 return (result);
719         }
720
721         return (ISC_R_SUCCESS);
722 }
723
724 /*
725  * Define the order in which rdatasets should be printed in zone
726  * files.  We will print SOA and NS records before others, SIGs
727  * immediately following the things they sign, and order everything
728  * else by RR number.  This is all just for aesthetics and
729  * compatibility with buggy software that expects the SOA to be first;
730  * the DNS specifications allow any order.
731  */
732
733 static int
734 dump_order(const dns_rdataset_t *rds) {
735         int t;
736         int sig;
737         if (rds->type == dns_rdatatype_rrsig) {
738                 t = rds->covers;
739                 sig = 1;
740         } else {
741                 t = rds->type;
742                 sig = 0;
743         }
744         switch (t) {
745         case dns_rdatatype_soa:
746                 t = 0;
747                 break;
748         case dns_rdatatype_ns:
749                 t = 1;
750                 break;
751         default:
752                 t += 2;
753                 break;
754         }
755         return (t << 1) + sig;
756 }
757
758 static int
759 dump_order_compare(const void *a, const void *b) {
760         return (dump_order(*((const dns_rdataset_t * const *) a)) -
761                 dump_order(*((const dns_rdataset_t * const *) b)));
762 }
763
764 /*
765  * Dump all the rdatasets of a domain name to a master file.  We make
766  * a "best effort" attempt to sort the RRsets in a nice order, but if
767  * there are more than MAXSORT RRsets, we punt and only sort them in
768  * groups of MAXSORT.  This is not expected to ever happen in practice
769  * since much less than 64 RR types have been registered with the
770  * IANA, so far, and the output will be correct (though not
771  * aesthetically pleasing) even if it does happen.
772  */
773
774 #define MAXSORT 64
775
776 static const char *trustnames[] = {
777         "none",
778         "pending",
779         "additional",
780         "glue",
781         "answer",
782         "authauthority",
783         "authanswer",
784         "secure",
785         "local" /* aka ultimate */
786 };
787
788 const char *
789 dns_trust_totext(dns_trust_t trust) {
790         if (trust >= sizeof(trustnames)/sizeof(*trustnames))
791                 return ("bad");
792         return (trustnames[trust]);
793 }
794
795 static isc_result_t
796 dump_rdatasets_text(isc_mem_t *mctx, dns_name_t *name,
797                     dns_rdatasetiter_t *rdsiter, dns_totext_ctx_t *ctx,
798                     isc_buffer_t *buffer, FILE *f)
799 {
800         isc_result_t itresult, dumpresult;
801         isc_region_t r;
802         dns_rdataset_t rdatasets[MAXSORT];
803         dns_rdataset_t *sorted[MAXSORT];
804         int i, n;
805
806         itresult = dns_rdatasetiter_first(rdsiter);
807         dumpresult = ISC_R_SUCCESS;
808
809         if (itresult == ISC_R_SUCCESS && ctx->neworigin != NULL) {
810                 isc_buffer_clear(buffer);
811                 itresult = dns_name_totext(ctx->neworigin, ISC_FALSE, buffer);
812                 RUNTIME_CHECK(itresult == ISC_R_SUCCESS);
813                 isc_buffer_usedregion(buffer, &r);
814                 fprintf(f, "$ORIGIN %.*s\n", (int) r.length, (char *) r.base);
815                 ctx->neworigin = NULL;
816         }
817
818  again:
819         for (i = 0;
820              itresult == ISC_R_SUCCESS && i < MAXSORT;
821              itresult = dns_rdatasetiter_next(rdsiter), i++) {
822                 dns_rdataset_init(&rdatasets[i]);
823                 dns_rdatasetiter_current(rdsiter, &rdatasets[i]);
824                 sorted[i] = &rdatasets[i];
825         }
826         n = i;
827         INSIST(n <= MAXSORT);
828
829         qsort(sorted, n, sizeof(sorted[0]), dump_order_compare);
830
831         for (i = 0; i < n; i++) {
832                 dns_rdataset_t *rds = sorted[i];
833                 if (ctx->style.flags & DNS_STYLEFLAG_TRUST) {
834                         unsigned int trust = rds->trust;
835                         INSIST(trust < (sizeof(trustnames) /
836                                         sizeof(trustnames[0])));
837                         fprintf(f, "; %s\n", trustnames[trust]);
838                 }
839                 if (rds->type == 0 &&
840                     (ctx->style.flags & DNS_STYLEFLAG_NCACHE) == 0) {
841                         /* Omit negative cache entries */
842                 } else {
843                         isc_result_t result =
844                                 dump_rdataset(mctx, name, rds, ctx,
845                                                buffer, f);
846                         if (result != ISC_R_SUCCESS)
847                                 dumpresult = result;
848                         if ((ctx->style.flags & DNS_STYLEFLAG_OMIT_OWNER) != 0)
849                                 name = NULL;
850                 }
851                 if (ctx->style.flags & DNS_STYLEFLAG_RESIGN &&
852                     rds->attributes & DNS_RDATASETATTR_RESIGN) {
853                         isc_buffer_t b;
854                         char buf[sizeof("YYYYMMDDHHMMSS")];
855                         memset(buf, 0, sizeof(buf));
856                         isc_buffer_init(&b, buf, sizeof(buf) - 1);
857                         dns_time64_totext((isc_uint64_t)rds->resign, &b);
858                         fprintf(f, "; resign=%s\n", buf);
859                 }
860                 dns_rdataset_disassociate(rds);
861         }
862
863         if (dumpresult != ISC_R_SUCCESS)
864                 return (dumpresult);
865
866         /*
867          * If we got more data than could be sorted at once,
868          * go handle the rest.
869          */
870         if (itresult == ISC_R_SUCCESS)
871                 goto again;
872
873         if (itresult == ISC_R_NOMORE)
874                 itresult = ISC_R_SUCCESS;
875
876         return (itresult);
877 }
878
879 /*
880  * Dump given RRsets in the "raw" format.
881  */
882 static isc_result_t
883 dump_rdataset_raw(isc_mem_t *mctx, dns_name_t *name, dns_rdataset_t *rdataset,
884                   isc_buffer_t *buffer, FILE *f)
885 {
886         isc_result_t result;
887         isc_uint32_t totallen;
888         isc_uint16_t dlen;
889         isc_region_t r, r_hdr;
890
891         REQUIRE(buffer->length > 0);
892         REQUIRE(DNS_RDATASET_VALID(rdataset));
893
894  restart:
895         totallen = 0;
896         result = dns_rdataset_first(rdataset);
897         REQUIRE(result == ISC_R_SUCCESS);
898
899         isc_buffer_clear(buffer);
900
901         /*
902          * Common header and owner name (length followed by name)
903          * These fields should be in a moderate length, so we assume we
904          * can store all of them in the initial buffer.
905          */
906         isc_buffer_availableregion(buffer, &r_hdr);
907         INSIST(r_hdr.length >= sizeof(dns_masterrawrdataset_t));
908         isc_buffer_putuint32(buffer, totallen); /* XXX: leave space */
909         isc_buffer_putuint16(buffer, rdataset->rdclass); /* 16-bit class */
910         isc_buffer_putuint16(buffer, rdataset->type); /* 16-bit type */
911         isc_buffer_putuint16(buffer, rdataset->covers); /* same as type */
912         isc_buffer_putuint32(buffer, rdataset->ttl); /* 32-bit TTL */
913         isc_buffer_putuint32(buffer, dns_rdataset_count(rdataset));
914         totallen = isc_buffer_usedlength(buffer);
915         INSIST(totallen <= sizeof(dns_masterrawrdataset_t));
916
917         dns_name_toregion(name, &r);
918         INSIST(isc_buffer_availablelength(buffer) >=
919                (sizeof(dlen) + r.length));
920         dlen = (isc_uint16_t)r.length;
921         isc_buffer_putuint16(buffer, dlen);
922         isc_buffer_copyregion(buffer, &r);
923         totallen += sizeof(dlen) + r.length;
924
925         do {
926                 dns_rdata_t rdata = DNS_RDATA_INIT;
927                 isc_region_t r;
928
929                 dns_rdataset_current(rdataset, &rdata);
930                 dns_rdata_toregion(&rdata, &r);
931                 INSIST(r.length <= 0xffffU);
932                 dlen = (isc_uint16_t)r.length;
933
934                 /*
935                  * Copy the rdata into the buffer.  If the buffer is too small,
936                  * grow it.  This should be rare, so we'll simply restart the
937                  * entire procedure (or should we copy the old data and
938                  * continue?).
939                  */
940                 if (isc_buffer_availablelength(buffer) <
941                                                  sizeof(dlen) + r.length) {
942                         int newlength;
943                         void *newmem;
944
945                         newlength = buffer->length * 2;
946                         newmem = isc_mem_get(mctx, newlength);
947                         if (newmem == NULL)
948                                 return (ISC_R_NOMEMORY);
949                         isc_mem_put(mctx, buffer->base, buffer->length);
950                         isc_buffer_init(buffer, newmem, newlength);
951                         goto restart;
952                 }
953                 isc_buffer_putuint16(buffer, dlen);
954                 isc_buffer_copyregion(buffer, &r);
955                 totallen += sizeof(dlen) + r.length;
956
957                 result = dns_rdataset_next(rdataset);
958         } while (result == ISC_R_SUCCESS);
959
960         if (result != ISC_R_NOMORE)
961                 return (result);
962
963         /*
964          * Fill in the total length field.
965          * XXX: this is a bit tricky.  Since we have already "used" the space
966          * for the total length in the buffer, we first remember the entire
967          * buffer length in the region, "rewind", and then write the value.
968          */
969         isc_buffer_usedregion(buffer, &r);
970         isc_buffer_clear(buffer);
971         isc_buffer_putuint32(buffer, totallen);
972         INSIST(isc_buffer_usedlength(buffer) < totallen);
973
974         /*
975          * Write the buffer contents to the raw master file.
976          */
977         result = isc_stdio_write(r.base, 1, (size_t)r.length, f, NULL);
978
979         if (result != ISC_R_SUCCESS) {
980                 UNEXPECTED_ERROR(__FILE__, __LINE__,
981                                  "raw master file write failed: %s",
982                                  isc_result_totext(result));
983                 return (result);
984         }
985
986         return (result);
987 }
988
989 static isc_result_t
990 dump_rdatasets_raw(isc_mem_t *mctx, dns_name_t *name,
991                    dns_rdatasetiter_t *rdsiter, dns_totext_ctx_t *ctx,
992                    isc_buffer_t *buffer, FILE *f)
993 {
994         isc_result_t result;
995         dns_rdataset_t rdataset;
996
997         for (result = dns_rdatasetiter_first(rdsiter);
998              result == ISC_R_SUCCESS;
999              result = dns_rdatasetiter_next(rdsiter)) {
1000
1001                 dns_rdataset_init(&rdataset);
1002                 dns_rdatasetiter_current(rdsiter, &rdataset);
1003
1004                 if (rdataset.type == 0 &&
1005                     (ctx->style.flags & DNS_STYLEFLAG_NCACHE) == 0) {
1006                         /* Omit negative cache entries */
1007                 } else {
1008                         result = dump_rdataset_raw(mctx, name, &rdataset,
1009                                                    buffer, f);
1010                 }
1011                 dns_rdataset_disassociate(&rdataset);
1012         }
1013
1014         if (result == ISC_R_NOMORE)
1015                 result = ISC_R_SUCCESS;
1016
1017         return (result);
1018 }
1019
1020 /*
1021  * Initial size of text conversion buffer.  The buffer is used
1022  * for several purposes: converting origin names, rdatasets,
1023  * $DATE timestamps, and comment strings for $TTL directives.
1024  *
1025  * When converting rdatasets, it is dynamically resized, but
1026  * when converting origins, timestamps, etc it is not.  Therefore,
1027  * the initial size must large enough to hold the longest possible
1028  * text representation of any domain name (for $ORIGIN).
1029  */
1030 static const int initial_buffer_length = 1200;
1031
1032 static isc_result_t
1033 dumptostreaminc(dns_dumpctx_t *dctx);
1034
1035 static void
1036 dumpctx_destroy(dns_dumpctx_t *dctx) {
1037
1038         dctx->magic = 0;
1039         DESTROYLOCK(&dctx->lock);
1040         dns_dbiterator_destroy(&dctx->dbiter);
1041         if (dctx->version != NULL)
1042                 dns_db_closeversion(dctx->db, &dctx->version, ISC_FALSE);
1043         dns_db_detach(&dctx->db);
1044         if (dctx->task != NULL)
1045                 isc_task_detach(&dctx->task);
1046         if (dctx->file != NULL)
1047                 isc_mem_free(dctx->mctx, dctx->file);
1048         if (dctx->tmpfile != NULL)
1049                 isc_mem_free(dctx->mctx, dctx->tmpfile);
1050         isc_mem_putanddetach(&dctx->mctx, dctx, sizeof(*dctx));
1051 }
1052
1053 void
1054 dns_dumpctx_attach(dns_dumpctx_t *source, dns_dumpctx_t **target) {
1055
1056         REQUIRE(DNS_DCTX_VALID(source));
1057         REQUIRE(target != NULL && *target == NULL);
1058
1059         LOCK(&source->lock);
1060         INSIST(source->references > 0);
1061         source->references++;
1062         INSIST(source->references != 0);        /* Overflow? */
1063         UNLOCK(&source->lock);
1064
1065         *target = source;
1066 }
1067
1068 void
1069 dns_dumpctx_detach(dns_dumpctx_t **dctxp) {
1070         dns_dumpctx_t *dctx;
1071         isc_boolean_t need_destroy = ISC_FALSE;
1072
1073         REQUIRE(dctxp != NULL);
1074         dctx = *dctxp;
1075         REQUIRE(DNS_DCTX_VALID(dctx));
1076
1077         *dctxp = NULL;
1078
1079         LOCK(&dctx->lock);
1080         INSIST(dctx->references != 0);
1081         dctx->references--;
1082         if (dctx->references == 0)
1083                 need_destroy = ISC_TRUE;
1084         UNLOCK(&dctx->lock);
1085         if (need_destroy)
1086                 dumpctx_destroy(dctx);
1087 }
1088
1089 dns_dbversion_t *
1090 dns_dumpctx_version(dns_dumpctx_t *dctx) {
1091         REQUIRE(DNS_DCTX_VALID(dctx));
1092         return (dctx->version);
1093 }
1094
1095 dns_db_t *
1096 dns_dumpctx_db(dns_dumpctx_t *dctx) {
1097         REQUIRE(DNS_DCTX_VALID(dctx));
1098         return (dctx->db);
1099 }
1100
1101 void
1102 dns_dumpctx_cancel(dns_dumpctx_t *dctx) {
1103         REQUIRE(DNS_DCTX_VALID(dctx));
1104
1105         LOCK(&dctx->lock);
1106         dctx->canceled = ISC_TRUE;
1107         UNLOCK(&dctx->lock);
1108 }
1109
1110 static isc_result_t
1111 closeandrename(FILE *f, isc_result_t result, const char *temp, const char *file)
1112 {
1113         isc_result_t tresult;
1114         isc_boolean_t logit = ISC_TF(result == ISC_R_SUCCESS);
1115
1116         if (result == ISC_R_SUCCESS)
1117                 result = isc_stdio_sync(f);
1118         if (result != ISC_R_SUCCESS && logit) {
1119                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1120                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1121                               "dumping master file: %s: fsync: %s",
1122                               temp, isc_result_totext(result));
1123                 logit = ISC_FALSE;
1124         }
1125         tresult = isc_stdio_close(f);
1126         if (result == ISC_R_SUCCESS)
1127                 result = tresult;
1128         if (result != ISC_R_SUCCESS && logit) {
1129                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1130                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1131                               "dumping master file: %s: fclose: %s",
1132                               temp, isc_result_totext(result));
1133                 logit = ISC_FALSE;
1134         }
1135         if (result == ISC_R_SUCCESS)
1136                 result = isc_file_rename(temp, file);
1137         else
1138                 (void)isc_file_remove(temp);
1139         if (result != ISC_R_SUCCESS && logit) {
1140                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1141                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1142                               "dumping master file: rename: %s: %s",
1143                               file, isc_result_totext(result));
1144         }
1145         return (result);
1146 }
1147
1148 static void
1149 dump_quantum(isc_task_t *task, isc_event_t *event) {
1150         isc_result_t result;
1151         isc_result_t tresult;
1152         dns_dumpctx_t *dctx;
1153
1154         REQUIRE(event != NULL);
1155         dctx = event->ev_arg;
1156         REQUIRE(DNS_DCTX_VALID(dctx));
1157         if (dctx->canceled)
1158                 result = ISC_R_CANCELED;
1159         else
1160                 result = dumptostreaminc(dctx);
1161         if (result == DNS_R_CONTINUE) {
1162                 event->ev_arg = dctx;
1163                 isc_task_send(task, &event);
1164                 return;
1165         }
1166
1167         if (dctx->file != NULL) {
1168                 tresult = closeandrename(dctx->f, result,
1169                                          dctx->tmpfile, dctx->file);
1170                 if (tresult != ISC_R_SUCCESS && result == ISC_R_SUCCESS)
1171                         result = tresult;
1172         }
1173         (dctx->done)(dctx->done_arg, result);
1174         isc_event_free(&event);
1175         dns_dumpctx_detach(&dctx);
1176 }
1177
1178 static isc_result_t
1179 task_send(dns_dumpctx_t *dctx) {
1180         isc_event_t *event;
1181
1182         event = isc_event_allocate(dctx->mctx, NULL, DNS_EVENT_DUMPQUANTUM,
1183                                    dump_quantum, dctx, sizeof(*event));
1184         if (event == NULL)
1185                 return (ISC_R_NOMEMORY);
1186         isc_task_send(dctx->task, &event);
1187         return (ISC_R_SUCCESS);
1188 }
1189
1190 static isc_result_t
1191 dumpctx_create(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1192                const dns_master_style_t *style, FILE *f, dns_dumpctx_t **dctxp,
1193                dns_masterformat_t format)
1194 {
1195         dns_dumpctx_t *dctx;
1196         isc_result_t result;
1197         unsigned int options;
1198
1199         dctx = isc_mem_get(mctx, sizeof(*dctx));
1200         if (dctx == NULL)
1201                 return (ISC_R_NOMEMORY);
1202
1203         dctx->mctx = NULL;
1204         dctx->f = f;
1205         dctx->dbiter = NULL;
1206         dctx->db = NULL;
1207         dctx->version = NULL;
1208         dctx->done = NULL;
1209         dctx->done_arg = NULL;
1210         dctx->task = NULL;
1211         dctx->nodes = 0;
1212         dctx->first = ISC_TRUE;
1213         dctx->canceled = ISC_FALSE;
1214         dctx->file = NULL;
1215         dctx->tmpfile = NULL;
1216         dctx->format = format;
1217
1218         switch (format) {
1219         case dns_masterformat_text:
1220                 dctx->dumpsets = dump_rdatasets_text;
1221                 break;
1222         case dns_masterformat_raw:
1223                 dctx->dumpsets = dump_rdatasets_raw;
1224                 break;
1225         default:
1226                 INSIST(0);
1227                 break;
1228         }
1229
1230         result = totext_ctx_init(style, &dctx->tctx);
1231         if (result != ISC_R_SUCCESS) {
1232                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1233                                  "could not set master file style");
1234                 goto cleanup;
1235         }
1236
1237         isc_stdtime_get(&dctx->now);
1238         dns_db_attach(db, &dctx->db);
1239
1240         dctx->do_date = dns_db_iscache(dctx->db);
1241
1242         if (dctx->format == dns_masterformat_text &&
1243             (dctx->tctx.style.flags & DNS_STYLEFLAG_REL_OWNER) != 0) {
1244                 options = DNS_DB_RELATIVENAMES;
1245         } else
1246                 options = 0;
1247         result = dns_db_createiterator(dctx->db, options, &dctx->dbiter);
1248         if (result != ISC_R_SUCCESS)
1249                 goto cleanup;
1250
1251         result = isc_mutex_init(&dctx->lock);
1252         if (result != ISC_R_SUCCESS)
1253                 goto cleanup;
1254         if (version != NULL)
1255                 dns_db_attachversion(dctx->db, version, &dctx->version);
1256         else if (!dns_db_iscache(db))
1257                 dns_db_currentversion(dctx->db, &dctx->version);
1258         isc_mem_attach(mctx, &dctx->mctx);
1259         dctx->references = 1;
1260         dctx->magic = DNS_DCTX_MAGIC;
1261         *dctxp = dctx;
1262         return (ISC_R_SUCCESS);
1263
1264  cleanup:
1265         if (dctx->dbiter != NULL)
1266                 dns_dbiterator_destroy(&dctx->dbiter);
1267         if (dctx->db != NULL)
1268                 dns_db_detach(&dctx->db);
1269         if (dctx != NULL)
1270                 isc_mem_put(mctx, dctx, sizeof(*dctx));
1271         return (result);
1272 }
1273
1274 static isc_result_t
1275 dumptostreaminc(dns_dumpctx_t *dctx) {
1276         isc_result_t result;
1277         isc_buffer_t buffer;
1278         char *bufmem;
1279         isc_region_t r;
1280         dns_name_t *name;
1281         dns_fixedname_t fixname;
1282         unsigned int nodes;
1283         dns_masterrawheader_t rawheader;
1284         isc_uint32_t now32;
1285         isc_time_t start;
1286
1287         bufmem = isc_mem_get(dctx->mctx, initial_buffer_length);
1288         if (bufmem == NULL)
1289                 return (ISC_R_NOMEMORY);
1290
1291         isc_buffer_init(&buffer, bufmem, initial_buffer_length);
1292
1293         dns_fixedname_init(&fixname);
1294         name = dns_fixedname_name(&fixname);
1295
1296         if (dctx->first) {
1297                 switch (dctx->format) {
1298                 case dns_masterformat_text:
1299                         /*
1300                          * If the database has cache semantics, output an
1301                          * RFC2540 $DATE directive so that the TTLs can be
1302                          * adjusted when it is reloaded.  For zones it is not
1303                          * really needed, and it would make the file
1304                          * incompatible with pre-RFC2540 software, so we omit
1305                          * it in the zone case.
1306                          */
1307                         if (dctx->do_date) {
1308                                 result = dns_time32_totext(dctx->now, &buffer);
1309                                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1310                                 isc_buffer_usedregion(&buffer, &r);
1311                                 fprintf(dctx->f, "$DATE %.*s\n",
1312                                         (int) r.length, (char *) r.base);
1313                         }
1314                         break;
1315                 case dns_masterformat_raw:
1316                         r.base = (unsigned char *)&rawheader;
1317                         r.length = sizeof(rawheader);
1318                         isc_buffer_region(&buffer, &r);
1319                         isc_buffer_putuint32(&buffer, dns_masterformat_raw);
1320                         isc_buffer_putuint32(&buffer, DNS_RAWFORMAT_VERSION);
1321                         if (sizeof(now32) != sizeof(dctx->now)) {
1322                                 /*
1323                                  * We assume isc_stdtime_t is a 32-bit integer,
1324                                  * which should be the case on most cases.
1325                                  * If it turns out to be uncommon, we'll need
1326                                  * to bump the version number and revise the
1327                                  * header format.
1328                                  */
1329                                 isc_log_write(dns_lctx,
1330                                               ISC_LOGCATEGORY_GENERAL,
1331                                               DNS_LOGMODULE_MASTERDUMP,
1332                                               ISC_LOG_INFO,
1333                                               "dumping master file in raw "
1334                                               "format: stdtime is not 32bits");
1335                                 now32 = 0;
1336                         } else
1337                                 now32 = dctx->now;
1338                         isc_buffer_putuint32(&buffer, now32);
1339                         INSIST(isc_buffer_usedlength(&buffer) <=
1340                                sizeof(rawheader));
1341                         result = isc_stdio_write(buffer.base, 1,
1342                                                  isc_buffer_usedlength(&buffer),
1343                                                  dctx->f, NULL);
1344                         if (result != ISC_R_SUCCESS)
1345                                 return (result);
1346                         isc_buffer_clear(&buffer);
1347                         break;
1348                 default:
1349                         INSIST(0);
1350                 }
1351
1352                 result = dns_dbiterator_first(dctx->dbiter);
1353                 dctx->first = ISC_FALSE;
1354         } else
1355                 result = ISC_R_SUCCESS;
1356
1357         nodes = dctx->nodes;
1358         isc_time_now(&start);
1359         while (result == ISC_R_SUCCESS && (dctx->nodes == 0 || nodes--)) {
1360                 dns_rdatasetiter_t *rdsiter = NULL;
1361                 dns_dbnode_t *node = NULL;
1362
1363                 result = dns_dbiterator_current(dctx->dbiter, &node, name);
1364                 if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN)
1365                         break;
1366                 if (result == DNS_R_NEWORIGIN) {
1367                         dns_name_t *origin =
1368                                 dns_fixedname_name(&dctx->tctx.origin_fixname);
1369                         result = dns_dbiterator_origin(dctx->dbiter, origin);
1370                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1371                         if ((dctx->tctx.style.flags & DNS_STYLEFLAG_REL_DATA) != 0)
1372                                 dctx->tctx.origin = origin;
1373                         dctx->tctx.neworigin = origin;
1374                 }
1375                 result = dns_db_allrdatasets(dctx->db, node, dctx->version,
1376                                              dctx->now, &rdsiter);
1377                 if (result != ISC_R_SUCCESS) {
1378                         dns_db_detachnode(dctx->db, &node);
1379                         goto fail;
1380                 }
1381                 result = (dctx->dumpsets)(dctx->mctx, name, rdsiter,
1382                                           &dctx->tctx, &buffer, dctx->f);
1383                 dns_rdatasetiter_destroy(&rdsiter);
1384                 if (result != ISC_R_SUCCESS) {
1385                         dns_db_detachnode(dctx->db, &node);
1386                         goto fail;
1387                 }
1388                 dns_db_detachnode(dctx->db, &node);
1389                 result = dns_dbiterator_next(dctx->dbiter);
1390         }
1391
1392         /*
1393          * Work out how many nodes can be written in the time between
1394          * two requests to the nameserver.  Smooth the resulting number and
1395          * use it as a estimate for the number of nodes to be written in the
1396          * next iteration.
1397          */
1398         if (dctx->nodes != 0 && result == ISC_R_SUCCESS) {
1399                 unsigned int pps = dns_pps;     /* packets per second */
1400                 unsigned int interval;
1401                 isc_uint64_t usecs;
1402                 isc_time_t end;
1403
1404                 isc_time_now(&end);
1405                 if (pps < 100)
1406                         pps = 100;
1407                 interval = 1000000 / pps;       /* interval in usecs */
1408                 if (interval == 0)
1409                         interval = 1;
1410                 usecs = isc_time_microdiff(&end, &start);
1411                 if (usecs == 0) {
1412                         dctx->nodes = dctx->nodes * 2;
1413                         if (dctx->nodes > 1000)
1414                                 dctx->nodes = 1000;
1415                 } else {
1416                         nodes = dctx->nodes * interval;
1417                         nodes /= (unsigned int)usecs;
1418                         if (nodes == 0)
1419                                 nodes = 1;
1420                         else if (nodes > 1000)
1421                                 nodes = 1000;
1422
1423                         /* Smooth and assign. */
1424                         dctx->nodes = (nodes + dctx->nodes * 7) / 8;
1425
1426                         isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1427                                       DNS_LOGMODULE_MASTERDUMP,
1428                                       ISC_LOG_DEBUG(1),
1429                                       "dumptostreaminc(%p) new nodes -> %d\n",
1430                                       dctx, dctx->nodes);
1431                 }
1432                 result = DNS_R_CONTINUE;
1433         } else if (result == ISC_R_NOMORE)
1434                 result = ISC_R_SUCCESS;
1435  fail:
1436         RUNTIME_CHECK(dns_dbiterator_pause(dctx->dbiter) == ISC_R_SUCCESS);
1437         isc_mem_put(dctx->mctx, buffer.base, buffer.length);
1438         return (result);
1439 }
1440
1441 isc_result_t
1442 dns_master_dumptostreaminc(isc_mem_t *mctx, dns_db_t *db,
1443                            dns_dbversion_t *version,
1444                            const dns_master_style_t *style,
1445                            FILE *f, isc_task_t *task,
1446                            dns_dumpdonefunc_t done, void *done_arg,
1447                            dns_dumpctx_t **dctxp)
1448 {
1449         dns_dumpctx_t *dctx = NULL;
1450         isc_result_t result;
1451
1452         REQUIRE(task != NULL);
1453         REQUIRE(f != NULL);
1454         REQUIRE(done != NULL);
1455
1456         result = dumpctx_create(mctx, db, version, style, f, &dctx,
1457                                 dns_masterformat_text);
1458         if (result != ISC_R_SUCCESS)
1459                 return (result);
1460         isc_task_attach(task, &dctx->task);
1461         dctx->done = done;
1462         dctx->done_arg = done_arg;
1463         dctx->nodes = 100;
1464
1465         result = task_send(dctx);
1466         if (result == ISC_R_SUCCESS) {
1467                 dns_dumpctx_attach(dctx, dctxp);
1468                 return (DNS_R_CONTINUE);
1469         }
1470
1471         dns_dumpctx_detach(&dctx);
1472         return (result);
1473 }
1474
1475 /*
1476  * Dump an entire database into a master file.
1477  */
1478 isc_result_t
1479 dns_master_dumptostream(isc_mem_t *mctx, dns_db_t *db,
1480                         dns_dbversion_t *version,
1481                         const dns_master_style_t *style,
1482                         FILE *f)
1483 {
1484         return (dns_master_dumptostream2(mctx, db, version, style,
1485                                          dns_masterformat_text, f));
1486 }
1487
1488 isc_result_t
1489 dns_master_dumptostream2(isc_mem_t *mctx, dns_db_t *db,
1490                          dns_dbversion_t *version,
1491                          const dns_master_style_t *style,
1492                          dns_masterformat_t format, FILE *f)
1493 {
1494         dns_dumpctx_t *dctx = NULL;
1495         isc_result_t result;
1496
1497         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1498         if (result != ISC_R_SUCCESS)
1499                 return (result);
1500
1501         result = dumptostreaminc(dctx);
1502         INSIST(result != DNS_R_CONTINUE);
1503         dns_dumpctx_detach(&dctx);
1504         return (result);
1505 }
1506
1507 static isc_result_t
1508 opentmp(isc_mem_t *mctx, const char *file, char **tempp, FILE **fp) {
1509         FILE *f = NULL;
1510         isc_result_t result;
1511         char *tempname = NULL;
1512         int tempnamelen;
1513
1514         tempnamelen = strlen(file) + 20;
1515         tempname = isc_mem_allocate(mctx, tempnamelen);
1516         if (tempname == NULL)
1517                 return (ISC_R_NOMEMORY);
1518
1519         result = isc_file_mktemplate(file, tempname, tempnamelen);
1520         if (result != ISC_R_SUCCESS)
1521                 goto cleanup;
1522
1523         result = isc_file_openunique(tempname, &f);
1524         if (result != ISC_R_SUCCESS) {
1525                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1526                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1527                               "dumping master file: %s: open: %s",
1528                               tempname, isc_result_totext(result));
1529                 goto cleanup;
1530         }
1531         *tempp = tempname;
1532         *fp = f;
1533         return (ISC_R_SUCCESS);
1534
1535 cleanup:
1536         isc_mem_free(mctx, tempname);
1537         return (result);
1538 }
1539
1540 isc_result_t
1541 dns_master_dumpinc(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1542                    const dns_master_style_t *style, const char *filename,
1543                    isc_task_t *task, dns_dumpdonefunc_t done, void *done_arg,
1544                    dns_dumpctx_t **dctxp)
1545 {
1546         return (dns_master_dumpinc2(mctx, db, version, style, filename, task,
1547                                     done, done_arg, dctxp,
1548                                     dns_masterformat_text));
1549 }
1550
1551 isc_result_t
1552 dns_master_dumpinc2(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1553                     const dns_master_style_t *style, const char *filename,
1554                     isc_task_t *task, dns_dumpdonefunc_t done, void *done_arg,
1555                     dns_dumpctx_t **dctxp, dns_masterformat_t format)
1556 {
1557         FILE *f = NULL;
1558         isc_result_t result;
1559         char *tempname = NULL;
1560         char *file = NULL;
1561         dns_dumpctx_t *dctx = NULL;
1562
1563         file = isc_mem_strdup(mctx, filename);
1564         if (file == NULL)
1565                 return (ISC_R_NOMEMORY);
1566
1567         result = opentmp(mctx, filename, &tempname, &f);
1568         if (result != ISC_R_SUCCESS)
1569                 goto cleanup;
1570
1571         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1572         if (result != ISC_R_SUCCESS) {
1573                 (void)isc_stdio_close(f);
1574                 (void)isc_file_remove(tempname);
1575                 goto cleanup;
1576         }
1577
1578         isc_task_attach(task, &dctx->task);
1579         dctx->done = done;
1580         dctx->done_arg = done_arg;
1581         dctx->nodes = 100;
1582         dctx->file = file;
1583         file = NULL;
1584         dctx->tmpfile = tempname;
1585         tempname = NULL;
1586
1587         result = task_send(dctx);
1588         if (result == ISC_R_SUCCESS) {
1589                 dns_dumpctx_attach(dctx, dctxp);
1590                 return (DNS_R_CONTINUE);
1591         }
1592
1593  cleanup:
1594         if (dctx != NULL)
1595                 dns_dumpctx_detach(&dctx);
1596         if (file != NULL)
1597                 isc_mem_free(mctx, file);
1598         if (tempname != NULL)
1599                 isc_mem_free(mctx, tempname);
1600         return (result);
1601 }
1602
1603 isc_result_t
1604 dns_master_dump(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1605                 const dns_master_style_t *style, const char *filename)
1606 {
1607         return (dns_master_dump2(mctx, db, version, style, filename,
1608                                  dns_masterformat_text));
1609 }
1610
1611 isc_result_t
1612 dns_master_dump2(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1613                  const dns_master_style_t *style, const char *filename,
1614                  dns_masterformat_t format)
1615 {
1616         FILE *f = NULL;
1617         isc_result_t result;
1618         char *tempname;
1619         dns_dumpctx_t *dctx = NULL;
1620
1621         result = opentmp(mctx, filename, &tempname, &f);
1622         if (result != ISC_R_SUCCESS)
1623                 return (result);
1624
1625         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1626         if (result != ISC_R_SUCCESS)
1627                 goto cleanup;
1628
1629         result = dumptostreaminc(dctx);
1630         INSIST(result != DNS_R_CONTINUE);
1631         dns_dumpctx_detach(&dctx);
1632
1633         result = closeandrename(f, result, tempname, filename);
1634
1635  cleanup:
1636         isc_mem_free(mctx, tempname);
1637         return (result);
1638 }
1639
1640 /*
1641  * Dump a database node into a master file.
1642  * XXX: this function assumes the text format.
1643  */
1644 isc_result_t
1645 dns_master_dumpnodetostream(isc_mem_t *mctx, dns_db_t *db,
1646                             dns_dbversion_t *version,
1647                             dns_dbnode_t *node, dns_name_t *name,
1648                             const dns_master_style_t *style,
1649                             FILE *f)
1650 {
1651         isc_result_t result;
1652         isc_buffer_t buffer;
1653         char *bufmem;
1654         isc_stdtime_t now;
1655         dns_totext_ctx_t ctx;
1656         dns_rdatasetiter_t *rdsiter = NULL;
1657
1658         result = totext_ctx_init(style, &ctx);
1659         if (result != ISC_R_SUCCESS) {
1660                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1661                                  "could not set master file style");
1662                 return (ISC_R_UNEXPECTED);
1663         }
1664
1665         isc_stdtime_get(&now);
1666
1667         bufmem = isc_mem_get(mctx, initial_buffer_length);
1668         if (bufmem == NULL)
1669                 return (ISC_R_NOMEMORY);
1670
1671         isc_buffer_init(&buffer, bufmem, initial_buffer_length);
1672
1673         result = dns_db_allrdatasets(db, node, version, now, &rdsiter);
1674         if (result != ISC_R_SUCCESS)
1675                 goto failure;
1676         result = dump_rdatasets_text(mctx, name, rdsiter, &ctx, &buffer, f);
1677         if (result != ISC_R_SUCCESS)
1678                 goto failure;
1679         dns_rdatasetiter_destroy(&rdsiter);
1680
1681         result = ISC_R_SUCCESS;
1682
1683  failure:
1684         isc_mem_put(mctx, buffer.base, buffer.length);
1685         return (result);
1686 }
1687
1688 isc_result_t
1689 dns_master_dumpnode(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1690                     dns_dbnode_t *node, dns_name_t *name,
1691                     const dns_master_style_t *style, const char *filename)
1692 {
1693         FILE *f = NULL;
1694         isc_result_t result;
1695
1696         result = isc_stdio_open(filename, "w", &f);
1697         if (result != ISC_R_SUCCESS) {
1698                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1699                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1700                               "dumping node to file: %s: open: %s", filename,
1701                               isc_result_totext(result));
1702                 return (ISC_R_UNEXPECTED);
1703         }
1704
1705         result = dns_master_dumpnodetostream(mctx, db, version, node, name,
1706                                              style, f);
1707
1708         result = isc_stdio_close(f);
1709         if (result != ISC_R_SUCCESS) {
1710                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1711                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1712                               "dumping master file: %s: close: %s", filename,
1713                               isc_result_totext(result));
1714                 return (ISC_R_UNEXPECTED);
1715         }
1716
1717         return (result);
1718 }
1719
1720 isc_result_t
1721 dns_master_stylecreate(dns_master_style_t **stylep, unsigned int flags,
1722                        unsigned int ttl_column, unsigned int class_column,
1723                        unsigned int type_column, unsigned int rdata_column,
1724                        unsigned int line_length, unsigned int tab_width,
1725                        isc_mem_t *mctx)
1726 {
1727         dns_master_style_t *style;
1728
1729         REQUIRE(stylep != NULL && *stylep == NULL);
1730         style = isc_mem_get(mctx, sizeof(*style));
1731         if (style == NULL)
1732                 return (ISC_R_NOMEMORY);
1733
1734         style->flags = flags;
1735         style->ttl_column = ttl_column;
1736         style->class_column = class_column;
1737         style->type_column = type_column;
1738         style->rdata_column = rdata_column;
1739         style->line_length = line_length;
1740         style->tab_width = tab_width;
1741
1742         *stylep = style;
1743         return (ISC_R_SUCCESS);
1744 }
1745
1746 void
1747 dns_master_styledestroy(dns_master_style_t **stylep, isc_mem_t *mctx) {
1748         dns_master_style_t *style;
1749
1750         REQUIRE(stylep != NULL && *stylep != NULL);
1751         style = *stylep;
1752         *stylep = NULL;
1753         isc_mem_put(mctx, style, sizeof(*style));
1754 }