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