summaryrefslogtreecommitdiff
path: root/src/dnsmxip.c
blob: e11d83e082e27daa67d7ff05cbb1da21e59f98f5 (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
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include "buffer.h"
#include "dnsresolv.h"
#include "exit.h"
#include "fmt.h"
#include "ip.h"
#include "logmsg.h"
#include "str.h"
#include "stralloc.h"

#include "dns.h"

#define WHO "dnsmxip"

static stralloc sa = {0};
static stralloc ia = {0};
static stralloc out = {0};
static stralloc ipaddr = {0};

static int dns_ia(stralloc *ip, char *s)
{
  int i;
  int j = 0;
  int r = 0;
  char ip4str[IP4_FMT];
  char ip6str[IP6_FMT];

  if (!stralloc_copys(&sa, s)) return -1;
  if (sa.s[sa.len - 1] != '.')
    if (!stralloc_append(&sa, ".")) return -1;
  if (!stralloc_copys(ip, "")) return -1;

  DNS_INIT
  if (dns_ip6(&ia, &sa) > 0) {
    for (i = 0; i + 16 <= ia.len; i += 16) {
      if (ip6_isv4mapped(ia.s + i)) continue;
      j = ip6_fmt(ip6str, ia.s + i);
      r += j;
      if (!stralloc_catb(ip, ip6str, j)) return -1;
      if (!stralloc_cats(ip, " ")) return -1;
      r++;
    }
  }

  if (dns_ip4(&ia, &sa) > 0) {
    for (i = 0; i + 4 <= ia.len; i += 4) {
      j = ip4_fmt(ip4str, ia.s + i);
      r += j;
      if (!stralloc_catb(ip, ip4str, j)) return -1;
      if (!stralloc_cats(ip, " ")) return -1;
      r++;
    }
  }
  if (!stralloc_0(ip)) return -1;

  return r ? r - 1 : 0;
}

int main(int argc, char **argv)
{
  int j, k, r;
  uint16 u;
  int len;
  char num[FMT_ULONG];

  if (!argv[1]) logmsg(WHO, 100, USAGE, "dnsmx fqdn");
  if (!stralloc_copys(&sa, argv[1])) logmsg(WHO, 111, FATAL, "out of memory");

  DNS_INIT
  if ((r = dns_mx(&out, &sa)) < 0) _exit(1);
  if (r > 0) {
    j = len = 0;
    do {
      j = str_chr(out.s + len + 2, '\0');
      k = dns_ia(&ipaddr, out.s + len + 2); /* IP */
      if (k) {
        buffer_put(buffer_1, out.s + len + 2, j); /* MX */
        buffer_puts(buffer_1, ": ");
        out.s[len + 3] = '\0';
        uint16_unpack_big(out.s + len, &u);
        buffer_put(buffer_1, num, fmt_ulong(num, u));
        buffer_puts(buffer_1, " [");
        buffer_put(buffer_1, ipaddr.s, k);
        buffer_puts(buffer_1, "]");
      }
      buffer_putsflush(buffer_1, "\n");
      len += j + 3;
    } while (len < out.len);
  } else {                        /* A/AAAA */
    k = dns_ia(&ipaddr, argv[1]); /* IP */
    if (k) {
      buffer_puts(buffer_1, argv[1]);
      buffer_puts(buffer_1, ": -");
      buffer_puts(buffer_1, " [");
      buffer_put(buffer_1, ipaddr.s, k);
      buffer_puts(buffer_1, "]");
      buffer_putsflush(buffer_1, "\n");
    }
  }

  _exit(0);
}