]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - contrib/bind9/lib/dns/masterdump.c
Update to version 9.6-ESV-R4-P3
[FreeBSD/stable/8.git] / contrib / bind9 / lib / dns / masterdump.c
1 /*
2  * Copyright (C) 2004-2009, 2011  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.3.18.3 2011-06-21 20:13:22 each 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         unsigned int type_start;
360
361         REQUIRE(DNS_RDATASET_VALID(rdataset));
362
363         rdataset->attributes |= DNS_RDATASETATTR_LOADORDER;
364         result = dns_rdataset_first(rdataset);
365         REQUIRE(result == ISC_R_SUCCESS);
366
367         current_ttl = ctx->current_ttl;
368         current_ttl_valid = ctx->current_ttl_valid;
369
370         do {
371                 column = 0;
372
373                 /*
374                  * Owner name.
375                  */
376                 if (owner_name != NULL &&
377                     ! ((ctx->style.flags & DNS_STYLEFLAG_OMIT_OWNER) != 0 &&
378                        !first))
379                 {
380                         unsigned int name_start = target->used;
381                         RETERR(dns_name_totext(owner_name,
382                                                omit_final_dot,
383                                                target));
384                         column += target->used - name_start;
385                 }
386
387                 /*
388                  * TTL.
389                  */
390                 if ((ctx->style.flags & DNS_STYLEFLAG_NO_TTL) == 0 &&
391                     !((ctx->style.flags & DNS_STYLEFLAG_OMIT_TTL) != 0 &&
392                       current_ttl_valid &&
393                       rdataset->ttl == current_ttl))
394                 {
395                         char ttlbuf[64];
396                         isc_region_t r;
397                         unsigned int length;
398
399                         INDENT_TO(ttl_column);
400                         length = snprintf(ttlbuf, sizeof(ttlbuf), "%u",
401                                           rdataset->ttl);
402                         INSIST(length <= sizeof(ttlbuf));
403                         isc_buffer_availableregion(target, &r);
404                         if (r.length < length)
405                                 return (ISC_R_NOSPACE);
406                         memcpy(r.base, ttlbuf, length);
407                         isc_buffer_add(target, length);
408                         column += length;
409
410                         /*
411                          * If the $TTL directive is not in use, the TTL we
412                          * just printed becomes the default for subsequent RRs.
413                          */
414                         if ((ctx->style.flags & DNS_STYLEFLAG_TTL) == 0) {
415                                 current_ttl = rdataset->ttl;
416                                 current_ttl_valid = ISC_TRUE;
417                         }
418                 }
419
420                 /*
421                  * Class.
422                  */
423                 if ((ctx->style.flags & DNS_STYLEFLAG_NO_CLASS) == 0 &&
424                     ((ctx->style.flags & DNS_STYLEFLAG_OMIT_CLASS) == 0 ||
425                      ctx->class_printed == ISC_FALSE))
426                 {
427                         unsigned int class_start;
428                         INDENT_TO(class_column);
429                         class_start = target->used;
430                         result = dns_rdataclass_totext(rdataset->rdclass,
431                                                        target);
432                         if (result != ISC_R_SUCCESS)
433                                 return (result);
434                         column += (target->used - class_start);
435                 }
436
437                 /*
438                  * Type.
439                  */
440
441                 if ((rdataset->attributes & DNS_RDATASETATTR_NEGATIVE) != 0) {
442                         type = rdataset->covers;
443                 } else {
444                         type = rdataset->type;
445                 }
446
447                 INDENT_TO(type_column);
448                 type_start = target->used;
449                 if ((rdataset->attributes & DNS_RDATASETATTR_NEGATIVE) != 0)
450                         RETERR(str_totext("\\-", target));
451                 result = dns_rdatatype_totext(type, target);
452                 if (result != ISC_R_SUCCESS)
453                         return (result);
454                 column += (target->used - type_start);
455
456                 /*
457                  * Rdata.
458                  */
459                 INDENT_TO(rdata_column);
460                 if ((rdataset->attributes & DNS_RDATASETATTR_NEGATIVE) != 0) {
461                         if (NXDOMAIN(rdataset))
462                                 RETERR(str_totext(";-$NXDOMAIN\n", target));
463                         else
464                                 RETERR(str_totext(";-$NXRRSET\n", target));
465                 } else {
466                         dns_rdata_t rdata = DNS_RDATA_INIT;
467                         isc_region_t r;
468
469                         dns_rdataset_current(rdataset, &rdata);
470
471                         RETERR(dns_rdata_tofmttext(&rdata,
472                                                    ctx->origin,
473                                                    ctx->style.flags,
474                                                    ctx->style.line_length -
475                                                        ctx->style.rdata_column,
476                                                    ctx->linebreak,
477                                                    target));
478
479                         isc_buffer_availableregion(target, &r);
480                         if (r.length < 1)
481                                 return (ISC_R_NOSPACE);
482                         r.base[0] = '\n';
483                         isc_buffer_add(target, 1);
484                 }
485
486                 first = ISC_FALSE;
487                 result = dns_rdataset_next(rdataset);
488         } while (result == ISC_R_SUCCESS);
489
490         if (result != ISC_R_NOMORE)
491                 return (result);
492
493         /*
494          * Update the ctx state to reflect what we just printed.
495          * This is done last, only when we are sure we will return
496          * success, because this function may be called multiple
497          * times with increasing buffer sizes until it succeeds,
498          * and failed attempts must not update the state prematurely.
499          */
500         ctx->class_printed = ISC_TRUE;
501         ctx->current_ttl= current_ttl;
502         ctx->current_ttl_valid = current_ttl_valid;
503
504         return (ISC_R_SUCCESS);
505 }
506
507 /*
508  * Print the name, type, and class of an empty rdataset,
509  * such as those used to represent the question section
510  * of a DNS message.
511  */
512 static isc_result_t
513 question_totext(dns_rdataset_t *rdataset,
514                 dns_name_t *owner_name,
515                 dns_totext_ctx_t *ctx,
516                 isc_boolean_t omit_final_dot,
517                 isc_buffer_t *target)
518 {
519         unsigned int column;
520         isc_result_t result;
521         isc_region_t r;
522
523         REQUIRE(DNS_RDATASET_VALID(rdataset));
524         result = dns_rdataset_first(rdataset);
525         REQUIRE(result == ISC_R_NOMORE);
526
527         column = 0;
528
529         /* Owner name */
530         {
531                 unsigned int name_start = target->used;
532                 RETERR(dns_name_totext(owner_name,
533                                        omit_final_dot,
534                                        target));
535                 column += target->used - name_start;
536         }
537
538         /* Class */
539         {
540                 unsigned int class_start;
541                 INDENT_TO(class_column);
542                 class_start = target->used;
543                 result = dns_rdataclass_totext(rdataset->rdclass, target);
544                 if (result != ISC_R_SUCCESS)
545                         return (result);
546                 column += (target->used - class_start);
547         }
548
549         /* Type */
550         {
551                 unsigned int type_start;
552                 INDENT_TO(type_column);
553                 type_start = target->used;
554                 result = dns_rdatatype_totext(rdataset->type, target);
555                 if (result != ISC_R_SUCCESS)
556                         return (result);
557                 column += (target->used - type_start);
558         }
559
560         isc_buffer_availableregion(target, &r);
561         if (r.length < 1)
562                 return (ISC_R_NOSPACE);
563         r.base[0] = '\n';
564         isc_buffer_add(target, 1);
565
566         return (ISC_R_SUCCESS);
567 }
568
569 isc_result_t
570 dns_rdataset_totext(dns_rdataset_t *rdataset,
571                     dns_name_t *owner_name,
572                     isc_boolean_t omit_final_dot,
573                     isc_boolean_t question,
574                     isc_buffer_t *target)
575 {
576         dns_totext_ctx_t ctx;
577         isc_result_t result;
578         result = totext_ctx_init(&dns_master_style_debug, &ctx);
579         if (result != ISC_R_SUCCESS) {
580                 UNEXPECTED_ERROR(__FILE__, __LINE__,
581                                  "could not set master file style");
582                 return (ISC_R_UNEXPECTED);
583         }
584
585         /*
586          * The caller might want to give us an empty owner
587          * name (e.g. if they are outputting into a master
588          * file and this rdataset has the same name as the
589          * previous one.)
590          */
591         if (dns_name_countlabels(owner_name) == 0)
592                 owner_name = NULL;
593
594         if (question)
595                 return (question_totext(rdataset, owner_name, &ctx,
596                                         omit_final_dot, target));
597         else
598                 return (rdataset_totext(rdataset, owner_name, &ctx,
599                                         omit_final_dot, target));
600 }
601
602 isc_result_t
603 dns_master_rdatasettotext(dns_name_t *owner_name,
604                           dns_rdataset_t *rdataset,
605                           const dns_master_style_t *style,
606                           isc_buffer_t *target)
607 {
608         dns_totext_ctx_t ctx;
609         isc_result_t result;
610         result = totext_ctx_init(style, &ctx);
611         if (result != ISC_R_SUCCESS) {
612                 UNEXPECTED_ERROR(__FILE__, __LINE__,
613                                  "could not set master file style");
614                 return (ISC_R_UNEXPECTED);
615         }
616
617         return (rdataset_totext(rdataset, owner_name, &ctx,
618                                 ISC_FALSE, target));
619 }
620
621 isc_result_t
622 dns_master_questiontotext(dns_name_t *owner_name,
623                           dns_rdataset_t *rdataset,
624                           const dns_master_style_t *style,
625                           isc_buffer_t *target)
626 {
627         dns_totext_ctx_t ctx;
628         isc_result_t result;
629         result = totext_ctx_init(style, &ctx);
630         if (result != ISC_R_SUCCESS) {
631                 UNEXPECTED_ERROR(__FILE__, __LINE__,
632                                  "could not set master file style");
633                 return (ISC_R_UNEXPECTED);
634         }
635
636         return (question_totext(rdataset, owner_name, &ctx,
637                                 ISC_FALSE, target));
638 }
639
640 /*
641  * Print an rdataset.  'buffer' is a scratch buffer, which must have been
642  * dynamically allocated by the caller.  It must be large enough to
643  * hold the result from dns_ttl_totext().  If more than that is needed,
644  * the buffer will be grown automatically.
645  */
646
647 static isc_result_t
648 dump_rdataset(isc_mem_t *mctx, dns_name_t *name, dns_rdataset_t *rdataset,
649               dns_totext_ctx_t *ctx,
650               isc_buffer_t *buffer, FILE *f)
651 {
652         isc_region_t r;
653         isc_result_t result;
654
655         REQUIRE(buffer->length > 0);
656
657         /*
658          * Output a $TTL directive if needed.
659          */
660
661         if ((ctx->style.flags & DNS_STYLEFLAG_TTL) != 0) {
662                 if (ctx->current_ttl_valid == ISC_FALSE ||
663                     ctx->current_ttl != rdataset->ttl)
664                 {
665                         if ((ctx->style.flags & DNS_STYLEFLAG_COMMENT) != 0)
666                         {
667                                 isc_buffer_clear(buffer);
668                                 result = dns_ttl_totext(rdataset->ttl,
669                                                         ISC_TRUE, buffer);
670                                 INSIST(result == ISC_R_SUCCESS);
671                                 isc_buffer_usedregion(buffer, &r);
672                                 fprintf(f, "$TTL %u\t; %.*s\n", rdataset->ttl,
673                                         (int) r.length, (char *) r.base);
674                         } else {
675                                 fprintf(f, "$TTL %u\n", rdataset->ttl);
676                         }
677                         ctx->current_ttl = rdataset->ttl;
678                         ctx->current_ttl_valid = ISC_TRUE;
679                 }
680         }
681
682         isc_buffer_clear(buffer);
683
684         /*
685          * Generate the text representation of the rdataset into
686          * the buffer.  If the buffer is too small, grow it.
687          */
688         for (;;) {
689                 int newlength;
690                 void *newmem;
691                 result = rdataset_totext(rdataset, name, ctx,
692                                          ISC_FALSE, buffer);
693                 if (result != ISC_R_NOSPACE)
694                         break;
695
696                 newlength = buffer->length * 2;
697                 newmem = isc_mem_get(mctx, newlength);
698                 if (newmem == NULL)
699                         return (ISC_R_NOMEMORY);
700                 isc_mem_put(mctx, buffer->base, buffer->length);
701                 isc_buffer_init(buffer, newmem, newlength);
702         }
703         if (result != ISC_R_SUCCESS)
704                 return (result);
705
706         /*
707          * Write the buffer contents to the master file.
708          */
709         isc_buffer_usedregion(buffer, &r);
710         result = isc_stdio_write(r.base, 1, (size_t)r.length, f, NULL);
711
712         if (result != ISC_R_SUCCESS) {
713                 UNEXPECTED_ERROR(__FILE__, __LINE__,
714                                  "master file write failed: %s",
715                                  isc_result_totext(result));
716                 return (result);
717         }
718
719         return (ISC_R_SUCCESS);
720 }
721
722 /*
723  * Define the order in which rdatasets should be printed in zone
724  * files.  We will print SOA and NS records before others, SIGs
725  * immediately following the things they sign, and order everything
726  * else by RR number.  This is all just for aesthetics and
727  * compatibility with buggy software that expects the SOA to be first;
728  * the DNS specifications allow any order.
729  */
730
731 static int
732 dump_order(const dns_rdataset_t *rds) {
733         int t;
734         int sig;
735         if (rds->type == dns_rdatatype_rrsig) {
736                 t = rds->covers;
737                 sig = 1;
738         } else {
739                 t = rds->type;
740                 sig = 0;
741         }
742         switch (t) {
743         case dns_rdatatype_soa:
744                 t = 0;
745                 break;
746         case dns_rdatatype_ns:
747                 t = 1;
748                 break;
749         default:
750                 t += 2;
751                 break;
752         }
753         return (t << 1) + sig;
754 }
755
756 static int
757 dump_order_compare(const void *a, const void *b) {
758         return (dump_order(*((const dns_rdataset_t * const *) a)) -
759                 dump_order(*((const dns_rdataset_t * const *) b)));
760 }
761
762 /*
763  * Dump all the rdatasets of a domain name to a master file.  We make
764  * a "best effort" attempt to sort the RRsets in a nice order, but if
765  * there are more than MAXSORT RRsets, we punt and only sort them in
766  * groups of MAXSORT.  This is not expected to ever happen in practice
767  * since much less than 64 RR types have been registered with the
768  * IANA, so far, and the output will be correct (though not
769  * aesthetically pleasing) even if it does happen.
770  */
771
772 #define MAXSORT 64
773
774 static isc_result_t
775 dump_rdatasets_text(isc_mem_t *mctx, dns_name_t *name,
776                     dns_rdatasetiter_t *rdsiter, dns_totext_ctx_t *ctx,
777                     isc_buffer_t *buffer, FILE *f)
778 {
779         isc_result_t itresult, dumpresult;
780         isc_region_t r;
781         dns_rdataset_t rdatasets[MAXSORT];
782         dns_rdataset_t *sorted[MAXSORT];
783         int i, n;
784
785         itresult = dns_rdatasetiter_first(rdsiter);
786         dumpresult = ISC_R_SUCCESS;
787
788         if (itresult == ISC_R_SUCCESS && ctx->neworigin != NULL) {
789                 isc_buffer_clear(buffer);
790                 itresult = dns_name_totext(ctx->neworigin, ISC_FALSE, buffer);
791                 RUNTIME_CHECK(itresult == ISC_R_SUCCESS);
792                 isc_buffer_usedregion(buffer, &r);
793                 fprintf(f, "$ORIGIN %.*s\n", (int) r.length, (char *) r.base);
794                 ctx->neworigin = NULL;
795         }
796
797  again:
798         for (i = 0;
799              itresult == ISC_R_SUCCESS && i < MAXSORT;
800              itresult = dns_rdatasetiter_next(rdsiter), i++) {
801                 dns_rdataset_init(&rdatasets[i]);
802                 dns_rdatasetiter_current(rdsiter, &rdatasets[i]);
803                 sorted[i] = &rdatasets[i];
804         }
805         n = i;
806         INSIST(n <= MAXSORT);
807
808         qsort(sorted, n, sizeof(sorted[0]), dump_order_compare);
809
810         for (i = 0; i < n; i++) {
811                 dns_rdataset_t *rds = sorted[i];
812                 if (ctx->style.flags & DNS_STYLEFLAG_TRUST) {
813                         fprintf(f, "; %s\n", dns_trust_totext(rds->trust));
814                 }
815                 if (((rds->attributes & DNS_RDATASETATTR_NEGATIVE) != 0) &&
816                     (ctx->style.flags & DNS_STYLEFLAG_NCACHE) == 0) {
817                         /* Omit negative cache entries */
818                 } else {
819                         isc_result_t result =
820                                 dump_rdataset(mctx, name, rds, ctx,
821                                                buffer, f);
822                         if (result != ISC_R_SUCCESS)
823                                 dumpresult = result;
824                         if ((ctx->style.flags & DNS_STYLEFLAG_OMIT_OWNER) != 0)
825                                 name = NULL;
826                 }
827                 if (ctx->style.flags & DNS_STYLEFLAG_RESIGN &&
828                     rds->attributes & DNS_RDATASETATTR_RESIGN) {
829                         isc_buffer_t b;
830                         char buf[sizeof("YYYYMMDDHHMMSS")];
831                         memset(buf, 0, sizeof(buf));
832                         isc_buffer_init(&b, buf, sizeof(buf) - 1);
833                         dns_time64_totext((isc_uint64_t)rds->resign, &b);
834                         fprintf(f, "; resign=%s\n", buf);
835                 }
836                 dns_rdataset_disassociate(rds);
837         }
838
839         if (dumpresult != ISC_R_SUCCESS)
840                 return (dumpresult);
841
842         /*
843          * If we got more data than could be sorted at once,
844          * go handle the rest.
845          */
846         if (itresult == ISC_R_SUCCESS)
847                 goto again;
848
849         if (itresult == ISC_R_NOMORE)
850                 itresult = ISC_R_SUCCESS;
851
852         return (itresult);
853 }
854
855 /*
856  * Dump given RRsets in the "raw" format.
857  */
858 static isc_result_t
859 dump_rdataset_raw(isc_mem_t *mctx, dns_name_t *name, dns_rdataset_t *rdataset,
860                   isc_buffer_t *buffer, FILE *f)
861 {
862         isc_result_t result;
863         isc_uint32_t totallen;
864         isc_uint16_t dlen;
865         isc_region_t r, r_hdr;
866
867         REQUIRE(buffer->length > 0);
868         REQUIRE(DNS_RDATASET_VALID(rdataset));
869
870  restart:
871         totallen = 0;
872         result = dns_rdataset_first(rdataset);
873         REQUIRE(result == ISC_R_SUCCESS);
874
875         isc_buffer_clear(buffer);
876
877         /*
878          * Common header and owner name (length followed by name)
879          * These fields should be in a moderate length, so we assume we
880          * can store all of them in the initial buffer.
881          */
882         isc_buffer_availableregion(buffer, &r_hdr);
883         INSIST(r_hdr.length >= sizeof(dns_masterrawrdataset_t));
884         isc_buffer_putuint32(buffer, totallen); /* XXX: leave space */
885         isc_buffer_putuint16(buffer, rdataset->rdclass); /* 16-bit class */
886         isc_buffer_putuint16(buffer, rdataset->type); /* 16-bit type */
887         isc_buffer_putuint16(buffer, rdataset->covers); /* same as type */
888         isc_buffer_putuint32(buffer, rdataset->ttl); /* 32-bit TTL */
889         isc_buffer_putuint32(buffer, dns_rdataset_count(rdataset));
890         totallen = isc_buffer_usedlength(buffer);
891         INSIST(totallen <= sizeof(dns_masterrawrdataset_t));
892
893         dns_name_toregion(name, &r);
894         INSIST(isc_buffer_availablelength(buffer) >=
895                (sizeof(dlen) + r.length));
896         dlen = (isc_uint16_t)r.length;
897         isc_buffer_putuint16(buffer, dlen);
898         isc_buffer_copyregion(buffer, &r);
899         totallen += sizeof(dlen) + r.length;
900
901         do {
902                 dns_rdata_t rdata = DNS_RDATA_INIT;
903                 isc_region_t r;
904
905                 dns_rdataset_current(rdataset, &rdata);
906                 dns_rdata_toregion(&rdata, &r);
907                 INSIST(r.length <= 0xffffU);
908                 dlen = (isc_uint16_t)r.length;
909
910                 /*
911                  * Copy the rdata into the buffer.  If the buffer is too small,
912                  * grow it.  This should be rare, so we'll simply restart the
913                  * entire procedure (or should we copy the old data and
914                  * continue?).
915                  */
916                 if (isc_buffer_availablelength(buffer) <
917                                                  sizeof(dlen) + r.length) {
918                         int newlength;
919                         void *newmem;
920
921                         newlength = buffer->length * 2;
922                         newmem = isc_mem_get(mctx, newlength);
923                         if (newmem == NULL)
924                                 return (ISC_R_NOMEMORY);
925                         isc_mem_put(mctx, buffer->base, buffer->length);
926                         isc_buffer_init(buffer, newmem, newlength);
927                         goto restart;
928                 }
929                 isc_buffer_putuint16(buffer, dlen);
930                 isc_buffer_copyregion(buffer, &r);
931                 totallen += sizeof(dlen) + r.length;
932
933                 result = dns_rdataset_next(rdataset);
934         } while (result == ISC_R_SUCCESS);
935
936         if (result != ISC_R_NOMORE)
937                 return (result);
938
939         /*
940          * Fill in the total length field.
941          * XXX: this is a bit tricky.  Since we have already "used" the space
942          * for the total length in the buffer, we first remember the entire
943          * buffer length in the region, "rewind", and then write the value.
944          */
945         isc_buffer_usedregion(buffer, &r);
946         isc_buffer_clear(buffer);
947         isc_buffer_putuint32(buffer, totallen);
948         INSIST(isc_buffer_usedlength(buffer) < totallen);
949
950         /*
951          * Write the buffer contents to the raw master file.
952          */
953         result = isc_stdio_write(r.base, 1, (size_t)r.length, f, NULL);
954
955         if (result != ISC_R_SUCCESS) {
956                 UNEXPECTED_ERROR(__FILE__, __LINE__,
957                                  "raw master file write failed: %s",
958                                  isc_result_totext(result));
959                 return (result);
960         }
961
962         return (result);
963 }
964
965 static isc_result_t
966 dump_rdatasets_raw(isc_mem_t *mctx, dns_name_t *name,
967                    dns_rdatasetiter_t *rdsiter, dns_totext_ctx_t *ctx,
968                    isc_buffer_t *buffer, FILE *f)
969 {
970         isc_result_t result;
971         dns_rdataset_t rdataset;
972
973         for (result = dns_rdatasetiter_first(rdsiter);
974              result == ISC_R_SUCCESS;
975              result = dns_rdatasetiter_next(rdsiter)) {
976
977                 dns_rdataset_init(&rdataset);
978                 dns_rdatasetiter_current(rdsiter, &rdataset);
979
980                 if (((rdataset.attributes & DNS_RDATASETATTR_NEGATIVE) != 0) &&
981                     (ctx->style.flags & DNS_STYLEFLAG_NCACHE) == 0) {
982                         /* Omit negative cache entries */
983                 } else {
984                         result = dump_rdataset_raw(mctx, name, &rdataset,
985                                                    buffer, f);
986                 }
987                 dns_rdataset_disassociate(&rdataset);
988         }
989
990         if (result == ISC_R_NOMORE)
991                 result = ISC_R_SUCCESS;
992
993         return (result);
994 }
995
996 /*
997  * Initial size of text conversion buffer.  The buffer is used
998  * for several purposes: converting origin names, rdatasets,
999  * $DATE timestamps, and comment strings for $TTL directives.
1000  *
1001  * When converting rdatasets, it is dynamically resized, but
1002  * when converting origins, timestamps, etc it is not.  Therefore,
1003  * the initial size must large enough to hold the longest possible
1004  * text representation of any domain name (for $ORIGIN).
1005  */
1006 static const int initial_buffer_length = 1200;
1007
1008 static isc_result_t
1009 dumptostreaminc(dns_dumpctx_t *dctx);
1010
1011 static void
1012 dumpctx_destroy(dns_dumpctx_t *dctx) {
1013
1014         dctx->magic = 0;
1015         DESTROYLOCK(&dctx->lock);
1016         dns_dbiterator_destroy(&dctx->dbiter);
1017         if (dctx->version != NULL)
1018                 dns_db_closeversion(dctx->db, &dctx->version, ISC_FALSE);
1019         dns_db_detach(&dctx->db);
1020         if (dctx->task != NULL)
1021                 isc_task_detach(&dctx->task);
1022         if (dctx->file != NULL)
1023                 isc_mem_free(dctx->mctx, dctx->file);
1024         if (dctx->tmpfile != NULL)
1025                 isc_mem_free(dctx->mctx, dctx->tmpfile);
1026         isc_mem_putanddetach(&dctx->mctx, dctx, sizeof(*dctx));
1027 }
1028
1029 void
1030 dns_dumpctx_attach(dns_dumpctx_t *source, dns_dumpctx_t **target) {
1031
1032         REQUIRE(DNS_DCTX_VALID(source));
1033         REQUIRE(target != NULL && *target == NULL);
1034
1035         LOCK(&source->lock);
1036         INSIST(source->references > 0);
1037         source->references++;
1038         INSIST(source->references != 0);        /* Overflow? */
1039         UNLOCK(&source->lock);
1040
1041         *target = source;
1042 }
1043
1044 void
1045 dns_dumpctx_detach(dns_dumpctx_t **dctxp) {
1046         dns_dumpctx_t *dctx;
1047         isc_boolean_t need_destroy = ISC_FALSE;
1048
1049         REQUIRE(dctxp != NULL);
1050         dctx = *dctxp;
1051         REQUIRE(DNS_DCTX_VALID(dctx));
1052
1053         *dctxp = NULL;
1054
1055         LOCK(&dctx->lock);
1056         INSIST(dctx->references != 0);
1057         dctx->references--;
1058         if (dctx->references == 0)
1059                 need_destroy = ISC_TRUE;
1060         UNLOCK(&dctx->lock);
1061         if (need_destroy)
1062                 dumpctx_destroy(dctx);
1063 }
1064
1065 dns_dbversion_t *
1066 dns_dumpctx_version(dns_dumpctx_t *dctx) {
1067         REQUIRE(DNS_DCTX_VALID(dctx));
1068         return (dctx->version);
1069 }
1070
1071 dns_db_t *
1072 dns_dumpctx_db(dns_dumpctx_t *dctx) {
1073         REQUIRE(DNS_DCTX_VALID(dctx));
1074         return (dctx->db);
1075 }
1076
1077 void
1078 dns_dumpctx_cancel(dns_dumpctx_t *dctx) {
1079         REQUIRE(DNS_DCTX_VALID(dctx));
1080
1081         LOCK(&dctx->lock);
1082         dctx->canceled = ISC_TRUE;
1083         UNLOCK(&dctx->lock);
1084 }
1085
1086 static isc_result_t
1087 closeandrename(FILE *f, isc_result_t result, const char *temp, const char *file)
1088 {
1089         isc_result_t tresult;
1090         isc_boolean_t logit = ISC_TF(result == ISC_R_SUCCESS);
1091
1092         if (result == ISC_R_SUCCESS)
1093                 result = isc_stdio_sync(f);
1094         if (result != ISC_R_SUCCESS && logit) {
1095                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1096                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1097                               "dumping master file: %s: fsync: %s",
1098                               temp, isc_result_totext(result));
1099                 logit = ISC_FALSE;
1100         }
1101         tresult = isc_stdio_close(f);
1102         if (result == ISC_R_SUCCESS)
1103                 result = tresult;
1104         if (result != ISC_R_SUCCESS && logit) {
1105                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1106                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1107                               "dumping master file: %s: fclose: %s",
1108                               temp, isc_result_totext(result));
1109                 logit = ISC_FALSE;
1110         }
1111         if (result == ISC_R_SUCCESS)
1112                 result = isc_file_rename(temp, file);
1113         else
1114                 (void)isc_file_remove(temp);
1115         if (result != ISC_R_SUCCESS && logit) {
1116                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1117                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1118                               "dumping master file: rename: %s: %s",
1119                               file, isc_result_totext(result));
1120         }
1121         return (result);
1122 }
1123
1124 static void
1125 dump_quantum(isc_task_t *task, isc_event_t *event) {
1126         isc_result_t result;
1127         isc_result_t tresult;
1128         dns_dumpctx_t *dctx;
1129
1130         REQUIRE(event != NULL);
1131         dctx = event->ev_arg;
1132         REQUIRE(DNS_DCTX_VALID(dctx));
1133         if (dctx->canceled)
1134                 result = ISC_R_CANCELED;
1135         else
1136                 result = dumptostreaminc(dctx);
1137         if (result == DNS_R_CONTINUE) {
1138                 event->ev_arg = dctx;
1139                 isc_task_send(task, &event);
1140                 return;
1141         }
1142
1143         if (dctx->file != NULL) {
1144                 tresult = closeandrename(dctx->f, result,
1145                                          dctx->tmpfile, dctx->file);
1146                 if (tresult != ISC_R_SUCCESS && result == ISC_R_SUCCESS)
1147                         result = tresult;
1148         }
1149         (dctx->done)(dctx->done_arg, result);
1150         isc_event_free(&event);
1151         dns_dumpctx_detach(&dctx);
1152 }
1153
1154 static isc_result_t
1155 task_send(dns_dumpctx_t *dctx) {
1156         isc_event_t *event;
1157
1158         event = isc_event_allocate(dctx->mctx, NULL, DNS_EVENT_DUMPQUANTUM,
1159                                    dump_quantum, dctx, sizeof(*event));
1160         if (event == NULL)
1161                 return (ISC_R_NOMEMORY);
1162         isc_task_send(dctx->task, &event);
1163         return (ISC_R_SUCCESS);
1164 }
1165
1166 static isc_result_t
1167 dumpctx_create(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1168                const dns_master_style_t *style, FILE *f, dns_dumpctx_t **dctxp,
1169                dns_masterformat_t format)
1170 {
1171         dns_dumpctx_t *dctx;
1172         isc_result_t result;
1173         unsigned int options;
1174
1175         dctx = isc_mem_get(mctx, sizeof(*dctx));
1176         if (dctx == NULL)
1177                 return (ISC_R_NOMEMORY);
1178
1179         dctx->mctx = NULL;
1180         dctx->f = f;
1181         dctx->dbiter = NULL;
1182         dctx->db = NULL;
1183         dctx->version = NULL;
1184         dctx->done = NULL;
1185         dctx->done_arg = NULL;
1186         dctx->task = NULL;
1187         dctx->nodes = 0;
1188         dctx->first = ISC_TRUE;
1189         dctx->canceled = ISC_FALSE;
1190         dctx->file = NULL;
1191         dctx->tmpfile = NULL;
1192         dctx->format = format;
1193
1194         switch (format) {
1195         case dns_masterformat_text:
1196                 dctx->dumpsets = dump_rdatasets_text;
1197                 break;
1198         case dns_masterformat_raw:
1199                 dctx->dumpsets = dump_rdatasets_raw;
1200                 break;
1201         default:
1202                 INSIST(0);
1203                 break;
1204         }
1205
1206         result = totext_ctx_init(style, &dctx->tctx);
1207         if (result != ISC_R_SUCCESS) {
1208                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1209                                  "could not set master file style");
1210                 goto cleanup;
1211         }
1212
1213         isc_stdtime_get(&dctx->now);
1214         dns_db_attach(db, &dctx->db);
1215
1216         dctx->do_date = dns_db_iscache(dctx->db);
1217
1218         if (dctx->format == dns_masterformat_text &&
1219             (dctx->tctx.style.flags & DNS_STYLEFLAG_REL_OWNER) != 0) {
1220                 options = DNS_DB_RELATIVENAMES;
1221         } else
1222                 options = 0;
1223         result = dns_db_createiterator(dctx->db, options, &dctx->dbiter);
1224         if (result != ISC_R_SUCCESS)
1225                 goto cleanup;
1226
1227         result = isc_mutex_init(&dctx->lock);
1228         if (result != ISC_R_SUCCESS)
1229                 goto cleanup;
1230         if (version != NULL)
1231                 dns_db_attachversion(dctx->db, version, &dctx->version);
1232         else if (!dns_db_iscache(db))
1233                 dns_db_currentversion(dctx->db, &dctx->version);
1234         isc_mem_attach(mctx, &dctx->mctx);
1235         dctx->references = 1;
1236         dctx->magic = DNS_DCTX_MAGIC;
1237         *dctxp = dctx;
1238         return (ISC_R_SUCCESS);
1239
1240  cleanup:
1241         if (dctx->dbiter != NULL)
1242                 dns_dbiterator_destroy(&dctx->dbiter);
1243         if (dctx->db != NULL)
1244                 dns_db_detach(&dctx->db);
1245         if (dctx != NULL)
1246                 isc_mem_put(mctx, dctx, sizeof(*dctx));
1247         return (result);
1248 }
1249
1250 static isc_result_t
1251 dumptostreaminc(dns_dumpctx_t *dctx) {
1252         isc_result_t result;
1253         isc_buffer_t buffer;
1254         char *bufmem;
1255         isc_region_t r;
1256         dns_name_t *name;
1257         dns_fixedname_t fixname;
1258         unsigned int nodes;
1259         dns_masterrawheader_t rawheader;
1260         isc_uint32_t now32;
1261         isc_time_t start;
1262
1263         bufmem = isc_mem_get(dctx->mctx, initial_buffer_length);
1264         if (bufmem == NULL)
1265                 return (ISC_R_NOMEMORY);
1266
1267         isc_buffer_init(&buffer, bufmem, initial_buffer_length);
1268
1269         dns_fixedname_init(&fixname);
1270         name = dns_fixedname_name(&fixname);
1271
1272         if (dctx->first) {
1273                 switch (dctx->format) {
1274                 case dns_masterformat_text:
1275                         /*
1276                          * If the database has cache semantics, output an
1277                          * RFC2540 $DATE directive so that the TTLs can be
1278                          * adjusted when it is reloaded.  For zones it is not
1279                          * really needed, and it would make the file
1280                          * incompatible with pre-RFC2540 software, so we omit
1281                          * it in the zone case.
1282                          */
1283                         if (dctx->do_date) {
1284                                 result = dns_time32_totext(dctx->now, &buffer);
1285                                 RUNTIME_CHECK(result == ISC_R_SUCCESS);
1286                                 isc_buffer_usedregion(&buffer, &r);
1287                                 fprintf(dctx->f, "$DATE %.*s\n",
1288                                         (int) r.length, (char *) r.base);
1289                         }
1290                         break;
1291                 case dns_masterformat_raw:
1292                         r.base = (unsigned char *)&rawheader;
1293                         r.length = sizeof(rawheader);
1294                         isc_buffer_region(&buffer, &r);
1295                         isc_buffer_putuint32(&buffer, dns_masterformat_raw);
1296                         isc_buffer_putuint32(&buffer, DNS_RAWFORMAT_VERSION);
1297                         if (sizeof(now32) != sizeof(dctx->now)) {
1298                                 /*
1299                                  * We assume isc_stdtime_t is a 32-bit integer,
1300                                  * which should be the case on most cases.
1301                                  * If it turns out to be uncommon, we'll need
1302                                  * to bump the version number and revise the
1303                                  * header format.
1304                                  */
1305                                 isc_log_write(dns_lctx,
1306                                               ISC_LOGCATEGORY_GENERAL,
1307                                               DNS_LOGMODULE_MASTERDUMP,
1308                                               ISC_LOG_INFO,
1309                                               "dumping master file in raw "
1310                                               "format: stdtime is not 32bits");
1311                                 now32 = 0;
1312                         } else
1313                                 now32 = dctx->now;
1314                         isc_buffer_putuint32(&buffer, now32);
1315                         INSIST(isc_buffer_usedlength(&buffer) <=
1316                                sizeof(rawheader));
1317                         result = isc_stdio_write(buffer.base, 1,
1318                                                  isc_buffer_usedlength(&buffer),
1319                                                  dctx->f, NULL);
1320                         if (result != ISC_R_SUCCESS)
1321                                 return (result);
1322                         isc_buffer_clear(&buffer);
1323                         break;
1324                 default:
1325                         INSIST(0);
1326                 }
1327
1328                 result = dns_dbiterator_first(dctx->dbiter);
1329                 dctx->first = ISC_FALSE;
1330         } else
1331                 result = ISC_R_SUCCESS;
1332
1333         nodes = dctx->nodes;
1334         isc_time_now(&start);
1335         while (result == ISC_R_SUCCESS && (dctx->nodes == 0 || nodes--)) {
1336                 dns_rdatasetiter_t *rdsiter = NULL;
1337                 dns_dbnode_t *node = NULL;
1338
1339                 result = dns_dbiterator_current(dctx->dbiter, &node, name);
1340                 if (result != ISC_R_SUCCESS && result != DNS_R_NEWORIGIN)
1341                         break;
1342                 if (result == DNS_R_NEWORIGIN) {
1343                         dns_name_t *origin =
1344                                 dns_fixedname_name(&dctx->tctx.origin_fixname);
1345                         result = dns_dbiterator_origin(dctx->dbiter, origin);
1346                         RUNTIME_CHECK(result == ISC_R_SUCCESS);
1347                         if ((dctx->tctx.style.flags & DNS_STYLEFLAG_REL_DATA) != 0)
1348                                 dctx->tctx.origin = origin;
1349                         dctx->tctx.neworigin = origin;
1350                 }
1351                 result = dns_db_allrdatasets(dctx->db, node, dctx->version,
1352                                              dctx->now, &rdsiter);
1353                 if (result != ISC_R_SUCCESS) {
1354                         dns_db_detachnode(dctx->db, &node);
1355                         goto fail;
1356                 }
1357                 result = (dctx->dumpsets)(dctx->mctx, name, rdsiter,
1358                                           &dctx->tctx, &buffer, dctx->f);
1359                 dns_rdatasetiter_destroy(&rdsiter);
1360                 if (result != ISC_R_SUCCESS) {
1361                         dns_db_detachnode(dctx->db, &node);
1362                         goto fail;
1363                 }
1364                 dns_db_detachnode(dctx->db, &node);
1365                 result = dns_dbiterator_next(dctx->dbiter);
1366         }
1367
1368         /*
1369          * Work out how many nodes can be written in the time between
1370          * two requests to the nameserver.  Smooth the resulting number and
1371          * use it as a estimate for the number of nodes to be written in the
1372          * next iteration.
1373          */
1374         if (dctx->nodes != 0 && result == ISC_R_SUCCESS) {
1375                 unsigned int pps = dns_pps;     /* packets per second */
1376                 unsigned int interval;
1377                 isc_uint64_t usecs;
1378                 isc_time_t end;
1379
1380                 isc_time_now(&end);
1381                 if (pps < 100)
1382                         pps = 100;
1383                 interval = 1000000 / pps;       /* interval in usecs */
1384                 if (interval == 0)
1385                         interval = 1;
1386                 usecs = isc_time_microdiff(&end, &start);
1387                 if (usecs == 0) {
1388                         dctx->nodes = dctx->nodes * 2;
1389                         if (dctx->nodes > 1000)
1390                                 dctx->nodes = 1000;
1391                 } else {
1392                         nodes = dctx->nodes * interval;
1393                         nodes /= (unsigned int)usecs;
1394                         if (nodes == 0)
1395                                 nodes = 1;
1396                         else if (nodes > 1000)
1397                                 nodes = 1000;
1398
1399                         /* Smooth and assign. */
1400                         dctx->nodes = (nodes + dctx->nodes * 7) / 8;
1401
1402                         isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1403                                       DNS_LOGMODULE_MASTERDUMP,
1404                                       ISC_LOG_DEBUG(1),
1405                                       "dumptostreaminc(%p) new nodes -> %d\n",
1406                                       dctx, dctx->nodes);
1407                 }
1408                 result = DNS_R_CONTINUE;
1409         } else if (result == ISC_R_NOMORE)
1410                 result = ISC_R_SUCCESS;
1411  fail:
1412         RUNTIME_CHECK(dns_dbiterator_pause(dctx->dbiter) == ISC_R_SUCCESS);
1413         isc_mem_put(dctx->mctx, buffer.base, buffer.length);
1414         return (result);
1415 }
1416
1417 isc_result_t
1418 dns_master_dumptostreaminc(isc_mem_t *mctx, dns_db_t *db,
1419                            dns_dbversion_t *version,
1420                            const dns_master_style_t *style,
1421                            FILE *f, isc_task_t *task,
1422                            dns_dumpdonefunc_t done, void *done_arg,
1423                            dns_dumpctx_t **dctxp)
1424 {
1425         dns_dumpctx_t *dctx = NULL;
1426         isc_result_t result;
1427
1428         REQUIRE(task != NULL);
1429         REQUIRE(f != NULL);
1430         REQUIRE(done != NULL);
1431
1432         result = dumpctx_create(mctx, db, version, style, f, &dctx,
1433                                 dns_masterformat_text);
1434         if (result != ISC_R_SUCCESS)
1435                 return (result);
1436         isc_task_attach(task, &dctx->task);
1437         dctx->done = done;
1438         dctx->done_arg = done_arg;
1439         dctx->nodes = 100;
1440
1441         result = task_send(dctx);
1442         if (result == ISC_R_SUCCESS) {
1443                 dns_dumpctx_attach(dctx, dctxp);
1444                 return (DNS_R_CONTINUE);
1445         }
1446
1447         dns_dumpctx_detach(&dctx);
1448         return (result);
1449 }
1450
1451 /*
1452  * Dump an entire database into a master file.
1453  */
1454 isc_result_t
1455 dns_master_dumptostream(isc_mem_t *mctx, dns_db_t *db,
1456                         dns_dbversion_t *version,
1457                         const dns_master_style_t *style,
1458                         FILE *f)
1459 {
1460         return (dns_master_dumptostream2(mctx, db, version, style,
1461                                          dns_masterformat_text, f));
1462 }
1463
1464 isc_result_t
1465 dns_master_dumptostream2(isc_mem_t *mctx, dns_db_t *db,
1466                          dns_dbversion_t *version,
1467                          const dns_master_style_t *style,
1468                          dns_masterformat_t format, FILE *f)
1469 {
1470         dns_dumpctx_t *dctx = NULL;
1471         isc_result_t result;
1472
1473         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1474         if (result != ISC_R_SUCCESS)
1475                 return (result);
1476
1477         result = dumptostreaminc(dctx);
1478         INSIST(result != DNS_R_CONTINUE);
1479         dns_dumpctx_detach(&dctx);
1480         return (result);
1481 }
1482
1483 static isc_result_t
1484 opentmp(isc_mem_t *mctx, const char *file, char **tempp, FILE **fp) {
1485         FILE *f = NULL;
1486         isc_result_t result;
1487         char *tempname = NULL;
1488         int tempnamelen;
1489
1490         tempnamelen = strlen(file) + 20;
1491         tempname = isc_mem_allocate(mctx, tempnamelen);
1492         if (tempname == NULL)
1493                 return (ISC_R_NOMEMORY);
1494
1495         result = isc_file_mktemplate(file, tempname, tempnamelen);
1496         if (result != ISC_R_SUCCESS)
1497                 goto cleanup;
1498
1499         result = isc_file_openunique(tempname, &f);
1500         if (result != ISC_R_SUCCESS) {
1501                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1502                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1503                               "dumping master file: %s: open: %s",
1504                               tempname, isc_result_totext(result));
1505                 goto cleanup;
1506         }
1507         *tempp = tempname;
1508         *fp = f;
1509         return (ISC_R_SUCCESS);
1510
1511 cleanup:
1512         isc_mem_free(mctx, tempname);
1513         return (result);
1514 }
1515
1516 isc_result_t
1517 dns_master_dumpinc(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1518                    const dns_master_style_t *style, const char *filename,
1519                    isc_task_t *task, dns_dumpdonefunc_t done, void *done_arg,
1520                    dns_dumpctx_t **dctxp)
1521 {
1522         return (dns_master_dumpinc2(mctx, db, version, style, filename, task,
1523                                     done, done_arg, dctxp,
1524                                     dns_masterformat_text));
1525 }
1526
1527 isc_result_t
1528 dns_master_dumpinc2(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1529                     const dns_master_style_t *style, const char *filename,
1530                     isc_task_t *task, dns_dumpdonefunc_t done, void *done_arg,
1531                     dns_dumpctx_t **dctxp, dns_masterformat_t format)
1532 {
1533         FILE *f = NULL;
1534         isc_result_t result;
1535         char *tempname = NULL;
1536         char *file = NULL;
1537         dns_dumpctx_t *dctx = NULL;
1538
1539         file = isc_mem_strdup(mctx, filename);
1540         if (file == NULL)
1541                 return (ISC_R_NOMEMORY);
1542
1543         result = opentmp(mctx, filename, &tempname, &f);
1544         if (result != ISC_R_SUCCESS)
1545                 goto cleanup;
1546
1547         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1548         if (result != ISC_R_SUCCESS) {
1549                 (void)isc_stdio_close(f);
1550                 (void)isc_file_remove(tempname);
1551                 goto cleanup;
1552         }
1553
1554         isc_task_attach(task, &dctx->task);
1555         dctx->done = done;
1556         dctx->done_arg = done_arg;
1557         dctx->nodes = 100;
1558         dctx->file = file;
1559         file = NULL;
1560         dctx->tmpfile = tempname;
1561         tempname = NULL;
1562
1563         result = task_send(dctx);
1564         if (result == ISC_R_SUCCESS) {
1565                 dns_dumpctx_attach(dctx, dctxp);
1566                 return (DNS_R_CONTINUE);
1567         }
1568
1569  cleanup:
1570         if (dctx != NULL)
1571                 dns_dumpctx_detach(&dctx);
1572         if (file != NULL)
1573                 isc_mem_free(mctx, file);
1574         if (tempname != NULL)
1575                 isc_mem_free(mctx, tempname);
1576         return (result);
1577 }
1578
1579 isc_result_t
1580 dns_master_dump(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1581                 const dns_master_style_t *style, const char *filename)
1582 {
1583         return (dns_master_dump2(mctx, db, version, style, filename,
1584                                  dns_masterformat_text));
1585 }
1586
1587 isc_result_t
1588 dns_master_dump2(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1589                  const dns_master_style_t *style, const char *filename,
1590                  dns_masterformat_t format)
1591 {
1592         FILE *f = NULL;
1593         isc_result_t result;
1594         char *tempname;
1595         dns_dumpctx_t *dctx = NULL;
1596
1597         result = opentmp(mctx, filename, &tempname, &f);
1598         if (result != ISC_R_SUCCESS)
1599                 return (result);
1600
1601         result = dumpctx_create(mctx, db, version, style, f, &dctx, format);
1602         if (result != ISC_R_SUCCESS)
1603                 goto cleanup;
1604
1605         result = dumptostreaminc(dctx);
1606         INSIST(result != DNS_R_CONTINUE);
1607         dns_dumpctx_detach(&dctx);
1608
1609         result = closeandrename(f, result, tempname, filename);
1610
1611  cleanup:
1612         isc_mem_free(mctx, tempname);
1613         return (result);
1614 }
1615
1616 /*
1617  * Dump a database node into a master file.
1618  * XXX: this function assumes the text format.
1619  */
1620 isc_result_t
1621 dns_master_dumpnodetostream(isc_mem_t *mctx, dns_db_t *db,
1622                             dns_dbversion_t *version,
1623                             dns_dbnode_t *node, dns_name_t *name,
1624                             const dns_master_style_t *style,
1625                             FILE *f)
1626 {
1627         isc_result_t result;
1628         isc_buffer_t buffer;
1629         char *bufmem;
1630         isc_stdtime_t now;
1631         dns_totext_ctx_t ctx;
1632         dns_rdatasetiter_t *rdsiter = NULL;
1633
1634         result = totext_ctx_init(style, &ctx);
1635         if (result != ISC_R_SUCCESS) {
1636                 UNEXPECTED_ERROR(__FILE__, __LINE__,
1637                                  "could not set master file style");
1638                 return (ISC_R_UNEXPECTED);
1639         }
1640
1641         isc_stdtime_get(&now);
1642
1643         bufmem = isc_mem_get(mctx, initial_buffer_length);
1644         if (bufmem == NULL)
1645                 return (ISC_R_NOMEMORY);
1646
1647         isc_buffer_init(&buffer, bufmem, initial_buffer_length);
1648
1649         result = dns_db_allrdatasets(db, node, version, now, &rdsiter);
1650         if (result != ISC_R_SUCCESS)
1651                 goto failure;
1652         result = dump_rdatasets_text(mctx, name, rdsiter, &ctx, &buffer, f);
1653         if (result != ISC_R_SUCCESS)
1654                 goto failure;
1655         dns_rdatasetiter_destroy(&rdsiter);
1656
1657         result = ISC_R_SUCCESS;
1658
1659  failure:
1660         isc_mem_put(mctx, buffer.base, buffer.length);
1661         return (result);
1662 }
1663
1664 isc_result_t
1665 dns_master_dumpnode(isc_mem_t *mctx, dns_db_t *db, dns_dbversion_t *version,
1666                     dns_dbnode_t *node, dns_name_t *name,
1667                     const dns_master_style_t *style, const char *filename)
1668 {
1669         FILE *f = NULL;
1670         isc_result_t result;
1671
1672         result = isc_stdio_open(filename, "w", &f);
1673         if (result != ISC_R_SUCCESS) {
1674                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1675                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1676                               "dumping node to file: %s: open: %s", filename,
1677                               isc_result_totext(result));
1678                 return (ISC_R_UNEXPECTED);
1679         }
1680
1681         result = dns_master_dumpnodetostream(mctx, db, version, node, name,
1682                                              style, f);
1683
1684         result = isc_stdio_close(f);
1685         if (result != ISC_R_SUCCESS) {
1686                 isc_log_write(dns_lctx, ISC_LOGCATEGORY_GENERAL,
1687                               DNS_LOGMODULE_MASTERDUMP, ISC_LOG_ERROR,
1688                               "dumping master file: %s: close: %s", filename,
1689                               isc_result_totext(result));
1690                 return (ISC_R_UNEXPECTED);
1691         }
1692
1693         return (result);
1694 }
1695
1696 isc_result_t
1697 dns_master_stylecreate(dns_master_style_t **stylep, unsigned int flags,
1698                        unsigned int ttl_column, unsigned int class_column,
1699                        unsigned int type_column, unsigned int rdata_column,
1700                        unsigned int line_length, unsigned int tab_width,
1701                        isc_mem_t *mctx)
1702 {
1703         dns_master_style_t *style;
1704
1705         REQUIRE(stylep != NULL && *stylep == NULL);
1706         style = isc_mem_get(mctx, sizeof(*style));
1707         if (style == NULL)
1708                 return (ISC_R_NOMEMORY);
1709
1710         style->flags = flags;
1711         style->ttl_column = ttl_column;
1712         style->class_column = class_column;
1713         style->type_column = type_column;
1714         style->rdata_column = rdata_column;
1715         style->line_length = line_length;
1716         style->tab_width = tab_width;
1717
1718         *stylep = style;
1719         return (ISC_R_SUCCESS);
1720 }
1721
1722 void
1723 dns_master_styledestroy(dns_master_style_t **stylep, isc_mem_t *mctx) {
1724         dns_master_style_t *style;
1725
1726         REQUIRE(stylep != NULL && *stylep != NULL);
1727         style = *stylep;
1728         *stylep = NULL;
1729         isc_mem_put(mctx, style, sizeof(*style));
1730 }