3 * - address-family specific code
6 * This file is part of adns, which is
7 * Copyright (C) 1997-2000,2003,2006 Ian Jackson
8 * Copyright (C) 1999-2000,2003,2006 Tony Finch
9 * Copyright (C) 1991 Massachusetts Institute of Technology
10 * (See the file INSTALL for full details.)
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2, or (at your option)
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
44 * General address-family operations.
47 #define SIN(sa) ((struct sockaddr_in *)(sa))
48 #define CSIN(sa) ((const struct sockaddr_in *)(sa))
50 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
51 #define CSIN6(sa) ((const struct sockaddr_in6 *)(sa))
53 /* This gadget (thanks, Richard Kettlewell) makes sure that we handle the
54 * same set of address families in each switch. */
55 #define AF_CASES(pre) \
56 case AF_INET: goto pre##_inet; \
57 case AF_INET6: goto pre##_inet6
59 static void unknown_af(int af) NONRETURNING;
60 static void unknown_af(int af) {
61 fprintf(stderr, "ADNS INTERNAL: unknown address family %d\n", af);
65 int adns__addrs_equal_raw(const struct sockaddr *a,
66 int bf, const void *b) {
67 if (a->sa_family != bf) return 0;
68 switch (a->sa_family) {
71 return ((const struct sockaddr_in*)a)->sin_addr.s_addr ==
72 ((const struct in_addr*)b)->s_addr;
74 return !memcmp(&((const struct sockaddr_in6*)a)->sin6_addr,
75 b, sizeof(struct in6_addr));
76 default: unknown_af(a->sa_family); return -1;
80 int adns__addrs_equal(const adns_sockaddr *a, const adns_sockaddr *b) {
81 return adns__addrs_equal_raw(&a->sa, b->sa.sa_family,
82 adns__sockaddr_addr(&b->sa));
85 int adns__sockaddrs_equal(const struct sockaddr *sa,
86 const struct sockaddr *sb) {
87 if (!adns__addrs_equal_raw(sa, sb->sa_family, adns__sockaddr_addr(sb)))
89 switch (sa->sa_family) {
92 const struct sockaddr_in *sina= CSIN(sa), *sinb= CSIN(sb);
93 return sina->sin_port == sinb->sin_port;
96 /* Don't check the flowlabel. That's apparently useful for routing
97 * performance, but doesn't affect the address in any important
99 const struct sockaddr_in6 *sin6a= CSIN6(sa), *sin6b= CSIN6(sb);
100 return sin6a->sin6_port == sin6b->sin6_port &&
101 sin6a->sin6_scope_id == sin6b->sin6_scope_id;
104 unknown_af(sa->sa_family);
109 int adns__addr_width(int af) {
113 af_inet6: return 128;
114 default: unknown_af(af); return -1;
118 void adns__prefix_mask(adns_sockaddr *sa, int len) {
119 int af= sa->sa.sa_family;
124 sa->inet.sin_addr.s_addr= htonl(!len ? 0 : 0xffffffff << (32-len));
127 int i= len/8, j= len%8;
128 unsigned char *m= sa->inet6.sin6_addr.s6_addr;
131 if (j) m[i++]= (0xff << (8-j)) & 0xff;
132 memset(m+i, 0, 16-i);
140 int adns__guess_prefix_length(const adns_sockaddr *sa) {
141 int af= sa->sa.sa_family;
145 unsigned a= (ntohl(sa->inet.sin_addr.s_addr) >> 24) & 0xff;
146 if (a < 128) return 8;
147 else if (a < 192) return 16;
148 else if (a < 224) return 24;
159 int adns__addr_matches(int af, const void *addr,
160 const adns_sockaddr *base, const adns_sockaddr *mask)
162 assert(base->sa.sa_family == mask->sa.sa_family);
163 if (af != base->sa.sa_family) return 0;
167 const struct in_addr *v4 = addr;
168 return (v4->s_addr & mask->inet.sin_addr.s_addr)
169 == base->inet.sin_addr.s_addr;
174 const char *b= base->inet6.sin6_addr.s6_addr;
175 const char *m= mask->inet6.sin6_addr.s6_addr;
176 for (i = 0; i < 16; i++)
177 if ((a[i] & m[i]) != b[i]) return 0;
186 const void *adns__sockaddr_addr(const struct sockaddr *sa) {
187 switch (sa->sa_family) {
190 const struct sockaddr_in *sin = CSIN(sa);
191 return &sin->sin_addr;
194 const struct sockaddr_in6 *sin6 = CSIN6(sa);
195 return &sin6->sin6_addr;
198 unknown_af(sa->sa_family);
202 void adns__addr_inject(const void *a, adns_sockaddr *sa) {
203 switch (sa->sa.sa_family) {
206 struct sockaddr_in *sin = &sa->inet;
207 memcpy(&sin->sin_addr, a, sizeof(sin->sin_addr));
211 struct sockaddr_in6 *sin6 = &sa->inet6;
212 memcpy(&sin6->sin6_addr, a, sizeof(sin6->sin6_addr));
216 unknown_af(sa->sa.sa_family);
221 * addr2text and text2addr
224 #define ADDRFAM_DEBUG
226 static void af_debug_func(const char *fmt, ...) {
230 vfprintf(stderr,fmt,al);
234 # define af_debug(fmt,...) \
235 (af_debug_func("%s: " fmt "\n", __func__, __VA_ARGS__))
237 # define af_debug(fmt,...) ((void)("" fmt "", __VA_ARGS__))
240 static bool addrtext_our_errno(int e) {
248 static bool addrtext_scope_use_ifname(const struct sockaddr *sa) {
249 const struct in6_addr *in6= &CSIN6(sa)->sin6_addr;
251 IN6_IS_ADDR_LINKLOCAL(in6) ||
252 IN6_IS_ADDR_MC_LINKLOCAL(in6);
255 int adns_text2addr(const char *text, uint16_t port, adns_queryflags flags,
256 struct sockaddr *sa, socklen_t *salen_io) {
258 char copybuf[INET6_ADDRSTRLEN];
259 const char *parse=text;
260 const char *scopestr=0;
265 #define INVAL(how) do{ \
266 af_debug("invalid: %s: `%s'", how, text); \
270 #define AFCORE(INETx,SINx,sinx) \
272 dst = &SINx(sa)->sinx##_addr; \
273 portp = &SINx(sa)->sinx##_port; \
274 needlen= sizeof(*SINx(sa));
276 if (!strchr(text, ':')) { /* INET */
278 AFCORE(INET,SIN,sin);
282 AFCORE(INET6,SIN6,sin6);
284 const char *percent= strchr(text, '%');
286 ptrdiff_t lhslen = percent - text;
287 if (lhslen >= INET6_ADDRSTRLEN) INVAL("scoped addr lhs too long");
288 memcpy(copybuf, text, lhslen);
294 af_debug("will parse scoped addr `%s' %% `%s'", parse, scopestr);
301 if (scopestr && (flags & adns_qf_addrlit_scope_forbid))
302 INVAL("scoped addr but _scope_forbid");
304 if (*salen_io < needlen) {
309 memset(sa, 0, needlen);
312 *portp = htons(port);
314 if (af == AF_INET && !(flags & adns_qf_addrlit_ipv4_quadonly)) {
315 /* we have to use inet_aton to deal with non-dotted-quad literals */
316 int r= inet_aton(parse,&SIN(sa)->sin_addr);
317 if (!r) INVAL("inet_aton rejected");
319 int r= inet_pton(af,parse,dst);
320 if (!r) INVAL("inet_pton rejected");
327 unsigned long scope= strtoul(scopestr,&ep,10);
328 if (errno==ERANGE) INVAL("numeric scope id too large for unsigned long");
331 if (scope > ~(uint32_t)0)
332 INVAL("numeric scope id too large for uint32_t");
334 if (flags & adns_qf_addrlit_scope_numeric)
335 INVAL("non-numeric scope but _scope_numeric");
336 if (!addrtext_scope_use_ifname(sa)) {
337 af_debug("cannot convert non-numeric scope"
338 " in non-link-local addr `%s'", text);
342 scope= if_nametoindex(scopestr);
344 /* RFC3493 says "No errors are defined". It's not clear
345 * whether that is supposed to mean if_nametoindex "can't
346 * fail" (other than by the supplied name not being that of an
347 * interface) which seems unrealistic, or that it conflates
348 * all its errors together by failing to set errno, or simply
349 * that they didn't bother to document the errors.
351 * glibc, FreeBSD and OpenBSD all set errno (to ENXIO when
352 * appropriate). See Debian bug #749349.
354 * We attempt to deal with this by clearing errno to start
355 * with, and then perhaps mapping the results. */
356 af_debug("if_nametoindex rejected scope name (errno=%s)",
360 } else if (addrtext_our_errno(errno)) {
361 /* we use these for other purposes, urgh. */
362 perror("adns: adns_text2addr: if_nametoindex"
363 " failed with unexpected error");
369 if (scope > ~(uint32_t)0) {
370 fprintf(stderr,"adns: adns_text2addr: if_nametoindex"
371 " returned an interface index >=2^32 which will not fit"
372 " in sockaddr_in6.sin6_scope_id");
378 SIN6(sa)->sin6_scope_id= scope;
379 } /* if (scopestr) */
385 int adns_addr2text(const struct sockaddr *sa, adns_queryflags flags,
386 char *buffer, int *buflen_io, int *port_r) {
390 if (*buflen_io < ADNS_ADDR2TEXT_BUFLEN) {
391 *buflen_io = ADNS_ADDR2TEXT_BUFLEN;
395 switch (sa->sa_family) {
397 af_inet: src= &CSIN(sa)->sin_addr; port= CSIN(sa)->sin_port; break;
398 af_inet6: src= &CSIN6(sa)->sin6_addr; port= CSIN6(sa)->sin6_port; break;
399 default: return EAFNOSUPPORT;
402 const char *ok= inet_ntop(sa->sa_family, src, buffer, *buflen_io);
405 if (sa->sa_family == AF_INET6) {
406 uint32_t scope = CSIN6(sa)->sin6_scope_id;
408 if (flags & adns_qf_addrlit_scope_forbid)
410 int scopeoffset = strlen(buffer);
411 int remain = *buflen_io - scopeoffset;
412 char *scopeptr = buffer + scopeoffset;
413 assert(remain >= IF_NAMESIZE+1/*%*/);
414 *scopeptr++= '%'; remain--;
416 af_debug("will print scoped addr `%.*s' %% %"PRIu32"",
417 scopeoffset,buffer, scope);
418 if (scope <= UINT_MAX /* so we can pass it to if_indextoname */
419 && !(flags & adns_qf_addrlit_scope_numeric)
420 && addrtext_scope_use_ifname(sa)) {
421 parsedname = if_indextoname(scope, scopeptr);
423 af_debug("if_indextoname rejected scope (errno=%s)",
426 /* fair enough, show it as a number then */
427 } else if (addrtext_our_errno(errno)) {
428 /* we use these for other purposes, urgh. */
429 perror("adns: adns_addr2text: if_indextoname"
430 " failed with unexpected error");
438 int r = snprintf(scopeptr, remain,
440 assert(r < *buflen_io - scopeoffset);
442 af_debug("printed scoped addr `%s'", buffer);
446 if (port_r) *port_r= ntohs(port);
450 char *adns__sockaddr_ntoa(const struct sockaddr *sa, char *buf) {
452 int len= ADNS_ADDR2TEXT_BUFLEN;
454 err= adns_addr2text(sa, 0, buf, &len, 0);
456 err= adns_addr2text(sa, adns_qf_addrlit_scope_numeric, buf, &len, 0);
462 * Reverse-domain parsing and construction.
465 int adns__make_reverse_domain(const struct sockaddr *sa, const char *zone,
466 char **buf_io, size_t bufsz,
472 const unsigned char *ap;
475 switch (sa->sa_family) {
479 if (!zone) zone= "in-addr.arpa";
483 if (!zone) zone= "ip6.arpa";
489 req += strlen(zone) + 1;
493 p= malloc(req); if (!p) return errno;
498 switch (sa->sa_family) {
501 aa= ntohl(CSIN(sa)->sin_addr.s_addr);
502 for (i=0; i<4; i++) {
503 p += sprintf(p, "%d", (int)(aa & 0xff));
509 ap= CSIN6(sa)->sin6_addr.s6_addr + 16;
510 for (i=0; i<16; i++) {
512 for (j=0; j<2; j++) {
514 *p++= (y < 10) ? y + '0' : y - 10 + 'a';
521 unknown_af(sa->sa_family);
529 static int inet_rev_parsecomp(const char *p, size_t n) {
531 if (n > 3) return -1;
534 if ('0' <= *p && *p <= '9') i= 10*i + *p++ - '0';
540 static void inet_rev_mkaddr(adns_sockaddr *addr, const byte *ipv) {
541 struct in_addr *v4 = &addr->inet.sin_addr;
542 v4->s_addr= htonl((ipv[3]<<24) | (ipv[2]<<16) |
543 (ipv[1]<<8) | (ipv[0]));
546 static int inet6_rev_parsecomp(const char *p, size_t n) {
547 if (n != 1) return -1;
548 else if ('0' <= *p && *p <= '9') return *p - '0';
549 else if ('a' <= *p && *p <= 'f') return *p - 'a' + 10;
550 else if ('A' <= *p && *p <= 'F') return *p - 'a' + 10;
554 static void inet6_rev_mkaddr(adns_sockaddr *addr, const byte *ipv) {
555 struct in6_addr *v6 = &addr->inet6.sin6_addr;
556 unsigned char *a= v6->s6_addr;
560 a[i]= (ipv[31-2*i] << 4) | (ipv[30-2*i] << 0);
563 static const struct revparse_domain {
564 int af; /* address family */
565 int nrevlab; /* n of reverse-address labels */
566 adns_rrtype rrtype; /* forward-lookup type */
568 int (*rev_parsecomp)(const char *p, size_t n);
569 /* parse a single component from a label; return the integer value, or -1
570 * if it was unintelligible.
573 void (*rev_mkaddr)(adns_sockaddr *addr, const byte *ipv);
574 /* write out the parsed protocol address from a vector of parsed components */
576 const char *const tail[3]; /* tail label names */
577 } revparse_domains[NREVDOMAINS] = {
578 { AF_INET, 4, adns_r_a, inet_rev_parsecomp, inet_rev_mkaddr,
579 { DNS_INADDR_ARPA, 0 } },
580 { AF_INET6, 32, adns_r_aaaa, inet6_rev_parsecomp, inet6_rev_mkaddr,
581 { DNS_IP6_ARPA, 0 } },
584 #define REVDOMAIN_MAP(rps, labnum) \
585 ((labnum) ? (rps)->map : (1 << NREVDOMAINS) - 1)
587 int adns__revparse_label(struct revparse_state *rps, int labnum,
588 const char *label, int lablen) {
589 unsigned f= REVDOMAIN_MAP(rps, labnum);
590 const struct revparse_domain *rpd;
595 for (rpd=revparse_domains, i=0, d=1; i<NREVDOMAINS; rpd++, i++, d <<= 1) {
596 if (!(f & d)) continue;
597 if (labnum >= rpd->nrevlab) {
598 tp = rpd->tail[labnum - rpd->nrevlab];
599 if (!tp || strncmp(label, tp, lablen) != 0 || tp[lablen])
602 ac= rpd->rev_parsecomp(label, lablen);
603 if (ac < 0) goto mismatch;
604 assert(labnum < sizeof(rps->ipv[i]));
605 rps->ipv[i][labnum]= ac;
618 int adns__revparse_done(struct revparse_state *rps, int nlabels,
619 adns_rrtype *rrtype_r, adns_sockaddr *addr_r) {
620 unsigned f= REVDOMAIN_MAP(rps, nlabels);
621 const struct revparse_domain *rpd;
625 for (rpd=revparse_domains, i=0, d=1; i<NREVDOMAINS; rpd++, i++, d <<= 1) {
626 if (!(f & d)) continue;
627 if (nlabels >= rpd->nrevlab && !rpd->tail[nlabels - rpd->nrevlab])
628 { found = i; continue; }
632 assert(found >= 0); assert(f == (1 << found));
634 rpd= &revparse_domains[found];
635 *rrtype_r= rpd->rrtype;
636 addr_r->sa.sa_family= rpd->af;
637 rpd->rev_mkaddr(addr_r, rps->ipv[found]);