summaryrefslogtreecommitdiff
path: root/tools/dnssec/dns-wire2text.c
blob: 1443bc45f212b3522ee2b3b99cf6d94a47b41357 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
  Read RR's in getdns wire format and print them in presentation
  format.
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <getdns/getdns.h>
#include <getdns/getdns_extra.h>
#include "common.h"

#undef DEBUG

#if defined(DEBUG)
static void
hd(const char *buf, size_t buf_len)
{
  for (size_t n = 0; n < buf_len; n++)
    {
      if (n % 16 == 0)
        {
          if (n != 0)
            fprintf(stderr, "\n");
          fprintf(stderr, "%08x  ", n);
        }
      else if (n % 8 == 0)
        fprintf(stderr, " ");
      fprintf(stderr, "%02hhx ", buf[n]);
    }
  fprintf(stderr, "\n");
}
#else  /* !DEBUG */
#define hd(a,b)
#endif

int
main(int argc, char *argv[])
{
  /* Read from file in argv[1] or from stdin. */
  FILE *infp = stdin;
  if (argc > 1)
    {
      infp = fopen(argv[1], "r");
      if (infp == NULL)
        {
          perror("fopen(argv[1])");
          return errno;
        }
    }

  /* Read RRs in wire format. */
  uint8_t *inbuf = NULL;
  size_t inbuf_len = read_buffer(infp, &inbuf, 0);
  if (inbuf == NULL)
    {
      perror("read_buffer");
      return errno;
    }
  if (infp != stdin)
    if (fclose(infp))
      perror("fclose");
  hd((const char *) wirebuf, n); /* DEBUG */

  /* Convert to getdns dicts in a getdns list. */
  getdns_return_t r = 0;
  getdns_list *rrs_list = NULL;
  r = wire_rrs2list(inbuf, inbuf_len, &rrs_list);
  free(inbuf);
  if (r)
    {
      fprintf(stderr, "error converting input: %s\n",
              getdns_get_errorstr_by_id(r));
      getdns_list_destroy(rrs_list);
      return r;
    }

  /* Print dicts in list. */
  size_t rrs_list_len;
  r = getdns_list_get_length(rrs_list, &rrs_list_len);
  if (r)
    {
      fprintf(stderr, "error getting list length: %s\n",
              getdns_get_errorstr_by_id(r));
      return r;
    }
  for (size_t i = 0; i < rrs_list_len; i++)
    {
      char *stringbuf = NULL;
      getdns_dict *rr_dict = NULL;

      r = getdns_list_get_dict(rrs_list, i, &rr_dict);
      if (r)
        {
          fprintf(stderr, "error getting dict from list: %s\n",
                  getdns_get_errorstr_by_id(r));
          break;
        }
      r = getdns_rr_dict2str(rr_dict, &stringbuf);
      if (r)
        {
          fprintf(stderr, "error converting dict to string: %s\n",
                  getdns_get_errorstr_by_id(r));
          break;
        }

      printf("%s", stringbuf);
      free(stringbuf);
    }
  getdns_list_destroy(rrs_list);

  return r;
}