chiark / gitweb /
New public-facing functions for address/text conversions.
[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 <sys/socket.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <net/if.h>
40
41 #include "internal.h"
42
43 /*
44  * General address-family operations.
45  */
46
47 #define SIN(sa) ((struct sockaddr_in *)(sa))
48 #define CSIN(sa) ((const struct sockaddr_in *)(sa))
49
50 #define SIN6(sa) ((struct sockaddr_in6 *)(sa))
51 #define CSIN6(sa) ((const struct sockaddr_in6 *)(sa))
52
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
58
59 static void unknown_af(int af) {
60   fprintf(stderr, "ADNS INTERNAL: unknown address family %d\n", af);
61   abort();
62 }
63
64 #define IN6_ADDR_EQUALP(a, b)                                           \
65   (!memcmp((a).s6_addr, (b).s6_addr, sizeof((a).s6_addr)))
66
67 int adns__genaddr_equal_p(int af, const union gen_addr *a,
68                           int bf, const void *b) {
69   const union gen_addr *bb= b;
70   if (af != bf) return 0;
71   switch (af) {
72   AF_CASES(af);
73   af_inet: return a->v4.s_addr == bb->v4.s_addr;
74   af_inet6: return IN6_ADDR_EQUALP(a->v6, bb->v6);
75   default: unknown_af(af); return -1;
76   }
77 }
78
79 int adns__sockaddr_equal_p(const struct sockaddr *sa,
80                            const struct sockaddr *sb) {
81   if (sa->sa_family != sb->sa_family) return 0;
82   switch (sa->sa_family) {
83   AF_CASES(af);
84   af_inet: {
85     const struct sockaddr_in *sina= CSIN(sa), *sinb= CSIN(sb);
86     return (sina->sin_addr.s_addr == sinb->sin_addr.s_addr &&
87             sina->sin_port == sinb->sin_port);
88   }
89   af_inet6: {
90     /* Don't check the flowlabel.  That's apparently useful for routing
91      * performance, but doesn't affect the address in any important
92      * respect. */
93     const struct sockaddr_in6 *sin6a= CSIN6(sa), *sin6b= CSIN6(sb);
94     return (IN6_ADDR_EQUALP(sin6a->sin6_addr, sin6b->sin6_addr) &&
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__addr_width(int af) {
105   switch (af) {
106   AF_CASES(af);
107   af_inet: return 32;
108   af_inet6: return 128;
109   default: unknown_af(af); return -1;
110   }
111 }
112
113 void adns__prefix_mask(int af, int len, union gen_addr *mask_r) {
114   switch (af) {
115   AF_CASES(af);
116   af_inet:
117     assert(len <= 32);
118     mask_r->v4.s_addr= htonl(!len ? 0 : 0xffffffff << (32-len));
119     break;
120   af_inet6: {
121     int i= len/8, j= len%8;
122     unsigned char *m= mask_r->v6.s6_addr;
123     assert(len <= 128);
124     memset(m, 0xff, i);
125     if (j) m[i++]= (0xff << (8-j)) & 0xff;
126     memset(m+i, 0, 16-i);
127   } break;
128   default:
129     unknown_af(af);
130     break;
131   }
132 }
133
134 int adns__guess_prefix_length(int af, const union gen_addr *addr) {
135   switch (af) {
136   AF_CASES(af);
137   af_inet: {
138     unsigned a= (ntohl(addr->v4.s_addr) >> 24) & 0xff;
139     if (a < 128) return 8;
140     else if (a < 192) return 16;
141     else if (a < 224) return 24;
142     else return -1;
143   } break;
144   af_inet6:
145     return 64;
146   default:
147     unknown_af(af);
148     return -1;
149   }
150 }
151
152 int adns__addr_match_p(int addraf, const union gen_addr *addr,
153                        int netaf, const union gen_addr *base,
154                        const union gen_addr *mask)
155 {
156   if (addraf != netaf) return 0;
157   switch (addraf) {
158   AF_CASES(af);
159   af_inet:
160     return (addr->v4.s_addr & mask->v4.s_addr) == base->v4.s_addr;
161   af_inet6: {
162     int i;
163     const char *a= addr->v6.s6_addr;
164     const char *b= base->v6.s6_addr;
165     const char *m= mask->v6.s6_addr;
166     for (i = 0; i < 16; i++)
167       if ((a[i] & m[i]) != b[i]) return 0;
168     return 1;
169   } break;
170   default:
171     unknown_af(addraf);
172     return -1;
173   }
174 }
175
176 void adns__sockaddr_extract(const struct sockaddr *sa,
177                             union gen_addr *a_r, int *port_r) {
178   switch (sa->sa_family) {
179   AF_CASES(af);
180   af_inet: {
181     const struct sockaddr_in *sin = CSIN(sa);
182     if (port_r) *port_r= ntohs(sin->sin_port);
183     if (a_r) a_r->v4= sin->sin_addr;
184     break;
185   }
186   af_inet6: {
187     const struct sockaddr_in6 *sin6 = CSIN6(sa);
188     if (port_r) *port_r= ntohs(sin6->sin6_port);
189     if (a_r) a_r->v6= sin6->sin6_addr;
190     break;
191   }
192   default:
193     unknown_af(sa->sa_family);
194   }
195 }
196
197 void adns__sockaddr_inject(const union gen_addr *a, int port,
198                            struct sockaddr *sa) {
199   switch (sa->sa_family) {
200   AF_CASES(af);
201   af_inet: {
202     struct sockaddr_in *sin = SIN(sa);
203     if (port != -1) sin->sin_port= htons(port);
204     if (a) sin->sin_addr= a->v4;
205     break;
206   }
207   af_inet6: {
208     struct sockaddr_in6 *sin6 = SIN6(sa);
209     if (port != -1) sin6->sin6_port= htons(port);
210     if (a) sin6->sin6_addr= a->v6;
211     break;
212   }
213   default:
214     unknown_af(sa->sa_family);
215   }
216 }
217
218 /*
219  * addr2text and text2addr
220  */
221
222 #define ADDRFAM_DEBUG
223 #ifdef ADDRFAM_DEBUG
224 static void af_debug_func(const char *fmt, ...) {
225   int esave= errno;
226   va_list al;
227   va_start(al,fmt);
228   vfprintf(stderr,fmt,al);
229   va_end(al);
230   errno= esave;
231 }
232 # define af_debug(fmt,...) \
233   (af_debug_func("%s: " fmt "\n", __func__, __VA_ARGS__))
234 #else
235 # define af_debug(fmt,...) ((void)("" fmt "", __VA_ARGS__))
236 #endif
237
238 static bool addrtext_our_errno(int e) {
239   return
240     e==EAFNOSUPPORT ||
241     e==EINVAL ||
242     e==ENOSPC ||
243     e==ENOSYS;
244 }
245
246 static bool addrtext_scope_use_ifname(const struct sockaddr *sa) {
247   const struct in6_addr *in6= &CSIN6(sa)->sin6_addr;
248   return
249     IN6_IS_ADDR_LINKLOCAL(in6) ||
250     IN6_IS_ADDR_MC_LINKLOCAL(in6);
251 }
252
253 int adns_text2addr(const char *text, uint16_t port, adns_queryflags flags,
254                    struct sockaddr *sa, socklen_t *salen_io) {
255   int af;
256   char copybuf[INET6_ADDRSTRLEN];
257   const char *parse=text;
258   const char *scopestr=0;
259   socklen_t needlen;
260   void *dst;
261   uint16_t *portp;
262
263 #define INVAL(how) do{                          \
264   af_debug("invalid: %s: `%s'", how, text);     \
265   return EINVAL;                                \
266 }while(0)
267
268 #define AFCORE(INETx,SINx,sinx)                 \
269     af= AF_##INETx;                             \
270     dst = &SINx(sa)->sinx##_addr;               \
271     portp = &SINx(sa)->sinx##_port;             \
272     needlen= sizeof(*SINx(sa));
273
274   if (!strchr(text, ':')) { /* INET */
275
276     AFCORE(INET,SIN,sin);
277
278   } else { /* INET6 */
279
280     AFCORE(INET6,SIN6,sin6);
281
282     const char *percent= strchr(text, '%');
283     if (percent) {
284       ptrdiff_t lhslen = percent - text;
285       if (lhslen >= INET6_ADDRSTRLEN) INVAL("scoped addr lhs too long");
286       memcpy(copybuf, text, lhslen);
287       copybuf[lhslen]= 0;
288
289       parse= copybuf;
290       scopestr= percent+1;
291
292       af_debug("will parse scoped addr `%s' %% `%s'", parse, scopestr);
293     }
294
295   }
296
297 #undef AFCORE
298
299   if (scopestr && (flags & adns_qf_addrlit_scope_forbid))
300     INVAL("scoped addr but _scope_forbid");
301
302   if (*salen_io < needlen) {
303     *salen_io = needlen;
304     return ENOSPC;
305   }
306
307   memset(sa, 0, needlen);
308
309   sa->sa_family= af;
310   *portp = htons(port);
311
312   if (af == AF_INET && !(flags & adns_qf_addrlit_ipv4_quadonly)) {
313     /* we have to use inet_aton to deal with non-dotted-quad literals */
314     int r= inet_aton(parse,&SIN(sa)->sin_addr);
315     if (!r) INVAL("inet_aton rejected");
316   } else {
317     int r= inet_pton(af,parse,dst);
318     if (!r) INVAL("inet_pton rejected");
319     assert(r>0);
320   }
321
322   if (scopestr) {
323     errno=0;
324     char *ep;
325     unsigned long scope= strtoul(scopestr,&ep,10);
326     if (errno==ERANGE) INVAL("numeric scope id too large for unsigned long");
327     assert(!errno);
328     if (!*ep) {
329       if (scope > ~(uint32_t)0)
330         INVAL("numeric scope id too large for uint32_t");
331     } else { /* !!*ep */
332       if (flags & adns_qf_addrlit_scope_numeric)
333         INVAL("non-numeric scope but _scope_numeric");
334       if (!addrtext_scope_use_ifname(sa)) {
335         af_debug("cannot convert non-numeric scope"
336                  " in non-link-local addr `%s'", text);
337         return ENOSYS;
338       }
339       errno= 0;
340       scope= if_nametoindex(scopestr);
341       if (!scope) {
342         /* RFC3493 says "No errors are defined".  It's not clear
343          * whether that is supposed to mean if_nametoindex "can't
344          * fail" (other than by the supplied name not being that of an
345          * interface) which seems unrealistic, or that it conflates
346          * all its errors together by failing to set errno, or simply
347          * that they didn't bother to document the errors.
348          *
349          * glibc, FreeBSD and OpenBSD all set errno (to ENXIO when
350          * appropriate).  See Debian bug #749349.
351          *
352          * We attempt to deal with this by clearing errno to start
353          * with, and then perhaps mapping the results. */
354         af_debug("if_nametoindex rejected scope name (errno=%s)",
355                  strerror(errno));
356         if (errno==0) {
357           return ENXIO;
358         } else if (addrtext_our_errno(errno)) {
359           /* we use these for other purposes, urgh. */
360           perror("adns: adns_text2addr: if_nametoindex"
361                  " failed with unexpected error");
362           return EIO;
363         } else {
364           return errno;
365         }
366       } else { /* ix>0 */
367         if (scope > ~(uint32_t)0) {
368           fprintf(stderr,"adns: adns_text2addr: if_nametoindex"
369                   " returned an interface index >=2^32 which will not fit"
370                   " in sockaddr_in6.sin6_scope_id");
371           return EIO;
372         }
373       }
374     } /* else; !!*ep */
375
376     SIN6(sa)->sin6_scope_id= scope;
377   } /* if (scopestr) */
378
379   *salen_io = needlen;
380   return 0;
381 }
382
383 int adns_addr2text(const struct sockaddr *sa, adns_queryflags flags,
384                    char *buffer, int *buflen_io, int *port_r) {
385   const void *src;
386   int port;
387
388   if (*buflen_io < ADNS_ADDR2TEXT_BUFLEN) {
389     *buflen_io = ADNS_ADDR2TEXT_BUFLEN;
390     return ENOSPC;
391   }
392
393   switch (sa->sa_family) {
394     AF_CASES(af);
395     af_inet:  src= &CSIN(sa)->sin_addr;    port= CSIN(sa)->sin_port;    break;
396     af_inet6: src= &CSIN6(sa)->sin6_addr;  port= CSIN6(sa)->sin6_port;  break;
397     default: return EAFNOSUPPORT;
398   }
399
400   const char *ok= inet_ntop(sa->sa_family, src, buffer, *buflen_io);
401   assert(ok);
402
403   if (sa->sa_family == AF_INET6) {
404     uint32_t scope = CSIN6(sa)->sin6_scope_id;
405     if (scope) {
406       if (flags & adns_qf_addrlit_scope_forbid)
407         return EINVAL;
408       int scopeoffset = strlen(buffer);
409       int remain = *buflen_io - scopeoffset;
410       char *scopeptr =  buffer + scopeoffset;
411       assert(remain >= IF_NAMESIZE+1/*%*/);
412       *scopeptr++= '%'; remain--;
413       bool parsedname = 0;
414       af_debug("will print scoped addr %s %% %"PRIu32"", buffer, scope);
415       if (scope <= UINT_MAX /* so we can pass it to if_indextoname */
416           && !(flags & adns_qf_addrlit_scope_numeric)
417           && addrtext_scope_use_ifname(sa)) {
418         parsedname = if_indextoname(scope, scopeptr);
419         if (!parsedname) {
420           af_debug("if_indextoname rejected scope (errno=%s)",
421                    strerror(errno));
422           if (errno==ENXIO) {
423             /* fair enough, show it as a number then */
424           } else if (addrtext_our_errno(errno)) {
425             /* we use these for other purposes, urgh. */
426             perror("adns: adns_addr2text: if_indextoname"
427                    " failed with unexpected error");
428             return EIO;
429           } else {
430             return errno;
431           }
432         }
433       }
434       if (!parsedname) {
435         int r = snprintf(scopeptr, remain,
436                          "%"PRIu32"", scope);
437         assert(r < *buflen_io - scopeoffset);
438       }
439       af_debug("printed scoped addr `%s'", buffer);
440     }
441   }
442
443   if (port_r) *port_r= ntohs(port);
444   return 0;
445 }