chiark / gitweb /
99e2faba82b256f2af9b3d670710ea90fa6a7017
[adns.git] / src / addrfam.c
1 /*
2  * addrfam.c
3  * - address-family specific code
4  */
5 /*
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.)
11  *  
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)
15  *  any later version.
16  *  
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.
21  *  
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. 
25  */
26
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <limits.h>
30 #include <unistd.h>
31 #include <inttypes.h>
32 #include <stddef.h>
33 #include <stdbool.h>
34
35 #include <sys/types.h>
36 #include <netdb.h>
37 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <netinet/in.h>
41 #include <net/if.h>
42
43 #include "internal.h"
44
45 /*
46  * General address-family operations.
47  */
48
49 #define SIN(sa) ((struct sockaddr_in *)(sa))
50 #define CSIN(sa) ((const struct sockaddr_in *)(sa))
51
52 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
53 #define CSIN6(sa) ((const struct sockaddr_in6 *)(sa))
54
55 /* This gadget (thanks, Richard Kettlewell) makes sure that we handle the
56  * same set of address families in each switch. */
57 #define AF_CASES(pre)                                                   \
58   case AF_INET: goto pre##_inet;                                        \
59   case AF_INET6: goto pre##_inet6
60
61 static void unknown_af(int af) {
62   fprintf(stderr, "ADNS INTERNAL: unknown address family %d\n", af);
63   abort();
64 }
65
66 int adns__af_supported_p(int af)
67 {
68   switch (af) {
69     AF_CASES(af);
70     af_inet: af_inet6: return 1;
71     default: return 0;
72   }
73 }
74
75 int adns__sockaddr_equal_p(const struct sockaddr *sa,
76                            const struct sockaddr *sb)
77 {
78   if (sa->sa_family != sb->sa_family) return 0;
79   switch (sa->sa_family) {
80     AF_CASES(af);
81     af_inet: {
82       const struct sockaddr_in *sina = CSIN(sa), *sinb = CSIN(sb);
83       return (sina->sin_addr.s_addr == sinb->sin_addr.s_addr &&
84               sina->sin_port == sinb->sin_port);
85     }
86     af_inet6: {
87       /* Don't check the flowlabel.  That's apparently useful for routing
88        * performance, but doesn't affect the address in any important
89        * respect.
90        */
91       const struct sockaddr_in6 *sin6a = CSIN6(sa), *sin6b = CSIN6(sb);
92       return (memcmp(sin6a->sin6_addr.s6_addr,
93                      sin6b->sin6_addr.s6_addr,
94                      sizeof(sin6a->sin6_addr.s6_addr)) == 0 &&
95               sin6a->sin6_port == sin6b->sin6_port &&
96               sin6a->sin6_scope_id == sin6b->sin6_scope_id);
97     }
98     default:
99       unknown_af(sa->sa_family);
100       return -1;
101   }
102 }
103
104 int adns__gen_pton(const char *p, int *af_r, union gen_addr *addr_r)
105 {
106   static const int aflist[] = { AF_INET6, AF_INET };
107   int i, rc;
108
109   for (i = 0; i < sizeof(aflist)/sizeof(*aflist); i++) {
110     rc = inet_pton(aflist[i], p, addr_r);
111     assert(rc >= 0);
112     if (rc) { *af_r = aflist[i]; return 1; }
113   }
114   return 0;
115 }
116
117 int adns__addr_width(int af)
118 {
119   switch (af) {
120     AF_CASES(af);
121     af_inet: return 32;
122     af_inet6: return 128;
123     default: unknown_af(af); return -1;
124   }
125 }
126
127 void adns__prefix_mask(int af, int len, union gen_addr *mask_r)
128 {
129   switch (af) {
130     AF_CASES(af);
131     af_inet:
132       assert(len <= 32);
133       mask_r->v4.s_addr = htonl(!len ? 0 : 0xffffffff << (32 - len));
134       break;
135     af_inet6: {
136       int i = len/8, j = len%8;
137       unsigned char *m = mask_r->v6.s6_addr;
138
139       assert(len <= 128);
140       memset(m, 0xff, i);
141       if (j) m[i++] = (0xff << (8-j)) & 0xff;
142       memset(m+i, 0, 16-i);
143     } break;
144     default:
145       unknown_af(af);
146       break;
147   }
148 }
149
150 int adns__guess_prefix_length(int af, const union gen_addr *addr)
151 {
152   switch (af) {
153     AF_CASES(af);
154     af_inet: {
155       unsigned a = (ntohl(addr->v4.s_addr) >> 24) & 0xff;
156
157       if (a < 128) return 8;
158       else if (a < 192) return 16;
159       else if (a < 224) return 24;
160       else return -1;
161     } break;
162     af_inet6:
163       return 64;
164     default:
165       unknown_af(af);
166       return -1;
167   }
168 }
169
170 int adns__addr_match_p(int addraf, const union gen_addr *addr,
171                        int netaf, const union gen_addr *base,
172                        const union gen_addr *mask)
173 {
174   if (addraf != netaf) return 0;
175   switch (addraf) {
176     AF_CASES(af);
177     af_inet:
178       return (addr->v4.s_addr & mask->v4.s_addr) == base->v4.s_addr;
179     af_inet6: {
180       int i;
181       const char *a = addr->v6.s6_addr;
182       const char *b = base->v6.s6_addr;
183       const char *m = mask->v6.s6_addr;
184
185       for (i = 0; i < 16; i++)
186         if ((a[i] & m[i]) != b[i]) return 0;
187       return 1;
188     } break;
189     default:
190       unknown_af(addraf);
191       return -1;
192   }
193 }
194
195 const void *adns__sockaddr_to_inaddr(const struct sockaddr *sa)
196 {
197   switch (sa->sa_family) {
198     AF_CASES(af);
199     af_inet: return &CSIN(sa)->sin_addr;
200     af_inet6: return &CSIN6(sa)->sin6_addr;
201     default: unknown_af(sa->sa_family); return 0;
202   }
203 }
204
205 /*
206  * addr2text and text2addr
207  */
208
209 #define ADDRFAM_DEBUG
210 #ifdef ADDRFAM_DEBUG
211 static void af_debug_func(const char *fmt, ...) {
212   int esave= errno;
213   va_list al;
214   va_start(al,fmt);
215   vfprintf(stderr,fmt,al);
216   va_end(al);
217   errno= esave;
218 }
219 # define af_debug(fmt,...) \
220   (af_debug_func("%s: " fmt "\n", __func__, __VA_ARGS__))
221 #else
222 # define af_debug(fmt,...) ((void)("" fmt "", __VA_ARGS__))
223 #endif
224
225 static bool addrtext_our_errno(int e) {
226   return
227     e==EAFNOSUPPORT ||
228     e==EINVAL ||
229     e==ENOSPC ||
230     e==ENOSYS;
231 }
232
233 static bool addrtext_scope_use_ifname(const struct sockaddr *sa) {
234   const struct in6_addr *in6= &CSIN6(sa)->sin6_addr;
235   return
236     IN6_IS_ADDR_LINKLOCAL(in6) ||
237     IN6_IS_ADDR_MC_LINKLOCAL(in6);
238 }
239
240 int adns_text2addr(const char *text, uint16_t port, adns_queryflags flags,
241                    struct sockaddr *sa, socklen_t *salen_io) {
242   int af;
243   char copybuf[INET6_ADDRSTRLEN];
244   const char *parse=text;
245   const char *scopestr=0;
246   socklen_t needlen;
247   void *dst;
248   uint16_t *portp;
249
250 #define INVAL(how) do{                          \
251   af_debug("invalid: %s: `%s'", how, text);     \
252   return EINVAL;                                \
253 }while(0)
254
255 #define AFCORE(INETx,SINx,sinx)                 \
256     af= AF_##INETx;                             \
257     dst = &SINx(sa)->sinx##_addr;               \
258     portp = &SINx(sa)->sinx##_port;             \
259     needlen= sizeof(*SINx(sa));
260
261   if (!strchr(text, ':')) { /* INET */
262
263     AFCORE(INET,SIN,sin);
264
265   } else { /* INET6 */
266
267     AFCORE(INET6,SIN6,sin6);
268
269     const char *percent= strchr(text, '%');
270     if (percent) {
271       ptrdiff_t lhslen = percent - text;
272       if (lhslen >= INET6_ADDRSTRLEN) INVAL("scoped addr lhs too long");
273       memcpy(copybuf, text, lhslen);
274       copybuf[lhslen]= 0;
275
276       parse= copybuf;
277       scopestr= percent+1;
278
279       af_debug("will parse scoped addr `%s' %% `%s'", parse, scopestr);
280     }
281
282   }
283
284 #undef AFCORE
285
286   if (scopestr && (flags & adns_qf_addrlit_scope_forbid))
287     INVAL("scoped addr but _scope_forbid");
288
289   if (*salen_io < needlen) {
290     *salen_io = needlen;
291     return ENOSPC;
292   }
293
294   memset(sa, 0, needlen);
295
296   sa->sa_family= af;
297   *portp = htons(port);
298
299   if (af == AF_INET && !(flags & adns_qf_addrlit_ipv4_quadonly)) {
300     /* we have to use inet_aton to deal with non-dotted-quad literals */
301     int r= inet_aton(parse,&SIN(sa)->sin_addr);
302     if (!r) INVAL("inet_aton rejected");
303   } else {
304     int r= inet_pton(af,parse,dst);
305     if (!r) INVAL("inet_pton rejected");
306     assert(r>0);
307   }
308
309   if (scopestr) {
310     errno=0;
311     char *ep;
312     unsigned long scope= strtoul(scopestr,&ep,10);
313     if (errno==ERANGE) INVAL("numeric scope id too large for unsigned long");
314     assert(!errno);
315     if (!*ep) {
316       if (scope > ~(uint32_t)0)
317         INVAL("numeric scope id too large for uint32_t");
318     } else { /* !!*ep */
319       if (flags & adns_qf_addrlit_scope_numeric)
320         INVAL("non-numeric scope but _scope_numeric");
321       if (!addrtext_scope_use_ifname(sa)) {
322         af_debug("cannot convert non-numeric scope"
323                  " in non-link-local addr `%s'", text);
324         return ENOSYS;
325       }
326       errno= 0;
327       scope= if_nametoindex(scopestr);
328       if (!scope) {
329         /* RFC3493 says "No errors are defined".  It's not clear
330          * whether that is supposed to mean if_nametoindex "can't
331          * fail" (other than by the supplied name not being that of an
332          * interface) which seems unrealistic, or that it conflates
333          * all its errors together by failing to set errno, or simply
334          * that they didn't bother to document the errors.
335          *
336          * glibc, FreeBSD and OpenBSD all set errno (to ENXIO when
337          * appropriate).  See Debian bug #749349.
338          *
339          * We attempt to deal with this by clearing errno to start
340          * with, and then perhaps mapping the results. */
341         af_debug("if_nametoindex rejected scope name (errno=%s)",
342                  strerror(errno));
343         if (errno==0) {
344           return ENXIO;
345         } else if (addrtext_our_errno(errno)) {
346           /* we use these for other purposes, urgh. */
347           perror("adns: adns_text2addr: if_nametoindex"
348                  " failed with unexpected error");
349           return EIO;
350         } else {
351           return errno;
352         }
353       } else { /* ix>0 */
354         if (scope > ~(uint32_t)0) {
355           fprintf(stderr,"adns: adns_text2addr: if_nametoindex"
356                   " returned an interface index >=2^32 which will not fit"
357                   " in sockaddr_in6.sin6_scope_id");
358           return EIO;
359         }
360       }
361     } /* else; !!*ep */
362
363     SIN6(sa)->sin6_scope_id= scope;
364   } /* if (scopestr) */
365
366   *salen_io = needlen;
367   return 0;
368 }
369
370 int adns_addr2text(const struct sockaddr *sa, adns_queryflags flags,
371                    char *buffer, int *buflen_io, int *port_r) {
372   const void *src;
373   int port;
374
375   if (*buflen_io < ADNS_ADDR2TEXT_BUFLEN) {
376     *buflen_io = ADNS_ADDR2TEXT_BUFLEN;
377     return ENOSPC;
378   }
379
380   switch (sa->sa_family) {
381     AF_CASES(af);
382     af_inet:  src= &CSIN(sa)->sin_addr;    port= CSIN(sa)->sin_port;    break;
383     af_inet6: src= &CSIN6(sa)->sin6_addr;  port= CSIN6(sa)->sin6_port;  break;
384     default: return EAFNOSUPPORT;
385   }
386
387   const char *ok= inet_ntop(sa->sa_family, src, buffer, *buflen_io);
388   assert(ok);
389
390   if (sa->sa_family == AF_INET6) {
391     uint32_t scope = CSIN6(sa)->sin6_scope_id;
392     if (scope) {
393       if (flags & adns_qf_addrlit_scope_forbid)
394         return EINVAL;
395       int scopeoffset = strlen(buffer);
396       int remain = *buflen_io - scopeoffset;
397       char *scopeptr =  buffer + scopeoffset;
398       assert(remain >= IF_NAMESIZE+1/*%*/);
399       *scopeptr++= '%'; remain--;
400       bool parsedname = 0;
401       af_debug("will print scoped addr %s %% %"PRIu32"", buffer, scope);
402       if (scope <= UINT_MAX /* so we can pass it to if_indextoname */
403           && !(flags & adns_qf_addrlit_scope_numeric)
404           && addrtext_scope_use_ifname(sa)) {
405         parsedname = if_indextoname(scope, scopeptr);
406         if (!parsedname) {
407           af_debug("if_indextoname rejected scope (errno=%s)",
408                    strerror(errno));
409           if (errno==ENXIO) {
410             /* fair enough, show it as a number then */
411           } else if (addrtext_our_errno(errno)) {
412             /* we use these for other purposes, urgh. */
413             perror("adns: adns_addr2text: if_indextoname"
414                    " failed with unexpected error");
415             return EIO;
416           } else {
417             return errno;
418           }
419         }
420       }
421       if (!parsedname) {
422         int r = snprintf(scopeptr, remain,
423                          "%"PRIu32"", scope);
424         assert(r < *buflen_io - scopeoffset);
425       }
426       af_debug("printed scoped addr `%s'", buffer);
427     }
428   }
429
430   if (port_r) *port_r= ntohs(port);
431   return 0;
432 }
433
434 /*
435  * Reverse-domain parsing and construction.
436  */
437
438 int adns__make_reverse_domain(const struct sockaddr *sa,
439                               const char *zone,
440                               char **buf_io, size_t bufsz,
441                               char **buf_free_r)
442 {
443   size_t req;
444   char *p;
445   unsigned c, y;
446   unsigned long aa;
447   const unsigned char *ap;
448   int i, j;
449
450   switch (sa->sa_family) {
451     AF_CASES(af);
452     af_inet:
453       req = 4 * 4;
454       if (!zone) zone = "in-addr.arpa";
455       break;
456     af_inet6:
457       req = 2 * 32;
458       if (!zone) zone = "ip6.arpa";
459       break;
460     default:
461       return ENOSYS;
462   }
463
464   req += strlen(zone) + 1;
465   if (req <= bufsz)
466     p = *buf_io;
467   else {
468     p = malloc(req); if (!p) return errno;
469     *buf_free_r = p;
470   }
471
472   *buf_io = p;
473   switch (sa->sa_family) {
474     AF_CASES(bf);
475     bf_inet:
476       aa = ntohl(CSIN(sa)->sin_addr.s_addr);
477       for (i = 0; i < 4; i++) {
478         p += sprintf(p, "%d", (int)(aa & 0xff));
479         *p++ = '.';
480         aa >>= 8;
481       }
482       break;
483     bf_inet6:
484       ap = CSIN6(sa)->sin6_addr.s6_addr + 16;
485       for (i = 0; i < 16; i++) {
486         c = *--ap;
487         for (j = 0; j < 2; j++) {
488           y = c & 0xf;
489           if (y < 10) *p++ = y + '0';
490           else *p++ = y - 10 + 'a';
491           c >>= 4;
492           *p++ = '.';
493         }
494       }
495       break;
496     default:
497       unknown_af(sa->sa_family);
498   }
499
500   strcpy(p, zone);
501   return 0;
502 }
503
504
505 static int inet_rev_parsecomp(const char *p, size_t n)
506 {
507   int i = 0;
508   if (n > 3) return -1;
509
510   while (n--) {
511     if ('0' <= *p && *p <= '9') i = 10*i + *p++ - '0';
512     else return -1;
513   }
514   return i;
515 }
516
517 static void inet_rev_mkaddr(union gen_addr *addr, const byte *ipv)
518 {
519   addr->v4.s_addr = htonl((ipv[3]<<24) | (ipv[2]<<16) |
520                           (ipv[1]<<8) | (ipv[0]));
521 }
522
523 static int inet6_rev_parsecomp(const char *p, size_t n)
524 {
525   if (n != 1) return -1;
526   else if ('0' <= *p && *p <= '9') return *p - '0';
527   else if ('a' <= *p && *p <= 'f') return *p - 'a' + 10;
528   else if ('A' <= *p && *p <= 'F') return *p - 'a' + 10;
529   else return -1;
530 }
531
532 static void inet6_rev_mkaddr(union gen_addr *addr, const byte *ipv)
533 {
534   unsigned char *a = addr->v6.s6_addr;
535   int i;
536
537   for (i = 0; i < 16; i++)
538     a[i] = (ipv[31-2*i] << 4) | (ipv[30-2*i] << 0);
539 }
540
541 static const struct revparse_domain {
542   int af;                               /* address family */
543   int nrevlab;                          /* n of reverse-address labels */
544   adns_rrtype rrtype;                   /* forward-lookup type */
545
546   int (*rev_parsecomp)(const char *p, size_t n);
547   /* parse a single component from a label; return the integer value, or -1
548    * if it was unintelligible.
549    */
550
551   void (*rev_mkaddr)(union gen_addr *addr, const byte *ipv);
552   /* write out the parsed address from a vector of parsed components */
553
554   const char *const tail[3];            /* tail label names */
555 } revparse_domains[NREVDOMAINS] = {
556   { AF_INET, 4, adns_r_a, inet_rev_parsecomp, inet_rev_mkaddr,
557     { DNS_INADDR_ARPA, 0 } },
558   { AF_INET6, 32, adns_r_aaaa, inet6_rev_parsecomp, inet6_rev_mkaddr,
559     { DNS_IP6_ARPA, 0 } },
560 };
561
562 #define REVDOMAIN_MAP(rps, labnum) \
563   ((labnum) ? (rps)->map : (1 << NREVDOMAINS) - 1)
564
565 int adns__revparse_label(struct revparse_state *rps, int labnum,
566                          const char *label, int lablen)
567 {
568   unsigned f = REVDOMAIN_MAP(rps, labnum);
569   const struct revparse_domain *rpd;
570   const char *tp;
571   unsigned d;
572   int i, ac;
573
574   for (rpd=revparse_domains, i=0, d=1; i<NREVDOMAINS; rpd++, i++, d <<= 1) {
575     if (!(f & d)) continue;
576     if (labnum >= rpd->nrevlab) {
577       tp = rpd->tail[labnum - rpd->nrevlab];
578       if (!tp || strncmp(label, tp, lablen) != 0 || tp[lablen])
579         goto mismatch;
580     } else {
581       ac = rpd->rev_parsecomp(label, lablen);
582       if (ac < 0) goto mismatch;
583       assert(labnum < sizeof(rps->ipv[i]));
584       rps->ipv[i][labnum] = ac;
585     }
586     continue;
587
588   mismatch:
589     f &= ~d;
590     if (!f) return -1;
591   }
592
593   rps->map = f;
594   return 0;
595 }
596
597 int adns__revparse_done(struct revparse_state *rps, int nlabels,
598                         adns_rrtype *rrtype_r, struct af_addr *addr_r)
599 {
600   unsigned f = REVDOMAIN_MAP(rps, nlabels);
601   const struct revparse_domain *rpd;
602   unsigned d;
603   int i, found = -1;
604
605   for (rpd=revparse_domains, i=0, d=1; i<NREVDOMAINS; rpd++, i++, d <<= 1) {
606     if (!(f & d)) continue;
607     if (nlabels >= rpd->nrevlab && !rpd->tail[nlabels - rpd->nrevlab])
608       { found = i; continue; }
609     f &= ~d;
610     if (!f) return -1;
611   }
612   assert(found >= 0); assert(f == (1 << found));
613
614   rpd = &revparse_domains[found];
615   *rrtype_r = rpd->rrtype;
616   addr_r->af = rpd->af;
617   rpd->rev_mkaddr(&addr_r->addr, rps->ipv[found]);
618   return 0;
619 }