chiark / gitweb /
Merge branch 'mdw/gstdecode'
[disorder] / lib / addr.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004, 2007, 2008, 2013 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/addr.c
19  * @brief Socket address support */
20
21 #include "common.h"
22
23 #include <sys/types.h>
24 #if HAVE_SYS_SOCKET_H
25 # include <sys/socket.h>
26 #endif
27 #if HAVE_NETINET_IN_H
28 # include <netinet/in.h>
29 #endif
30 #if HAVE_ARPA_INET_H
31 # include <arpa/inet.h>
32 #endif
33 #if HAVE_SYS_UN_H
34 # include <sys/un.h>
35 #endif
36 #if HAVE_WS2TCPIP_H
37 # include <Ws2tcpip.h>
38 #endif
39
40 #include "log.h"
41 #include "printf.h"
42 #include "addr.h"
43 #include "mem.h"
44 #include "syscalls.h"
45 #include "configuration.h"
46 #include "vector.h"
47
48 /** @brief Convert a pair of strings to an address
49  * @param a Pointer to string list
50  * @param pref Hints structure for getaddrinfo, or NULL
51  * @param namep Where to store address description, or NULL
52  * @return Address info structure or NULL on error
53  *
54  * This converts one or two strings into an address specification suitable
55  * for passing to socket(), bind() etc.
56  *
57  * If there is only one string then it is assumed to be the service
58  * name (port number).  If there are two then the first is the host
59  * name and the second the service name.
60  *
61  * @p namep is used to return a description of the address suitable
62  * for use in log messages.
63  *
64  * If an error occurs a message is logged and a null pointer returned.
65  */
66 struct addrinfo *get_address(const struct stringlist *a,
67                              const struct addrinfo *pref,
68                              char **namep) {
69   struct addrinfo *res;
70   char *name;
71   int rc;
72   char errbuf[1024];
73
74   switch(a->n) {  
75   case 1:
76     byte_xasprintf(&name, "host * service %s", a->s[0]);
77     if((rc = getaddrinfo(0, a->s[0], pref, &res))) {
78       disorder_error(0, "getaddrinfo %s: %s", a->s[0],
79                      format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
80       return 0;
81     }
82     break;
83   case 2:
84     byte_xasprintf(&name, "host %s service %s", a->s[0], a->s[1]);
85     if((rc = getaddrinfo(a->s[0], a->s[1], pref, &res))) {
86       disorder_error(0, "getaddrinfo %s %s: %s",
87                      a->s[0], a->s[1],
88                      format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
89       return 0;
90     }
91     break;
92   default:
93     disorder_error(0, "invalid network address specification (n=%d)", a->n);
94     return 0;
95   }
96   if(!res || (pref && res->ai_socktype != pref->ai_socktype)) {
97     disorder_error(0, "getaddrinfo didn't give us a suitable socket address");
98     if(res)
99       freeaddrinfo(res);
100     return 0;
101   }
102   if(namep)
103     *namep = name;
104   return res;
105 }
106
107 /** @brief Comparison function for address information
108  *
109  * Suitable for qsort().
110  */
111 int addrinfocmp(const struct addrinfo *a,
112                 const struct addrinfo *b) {
113   if(a->ai_family != b->ai_family) return a->ai_family - b->ai_family;
114   if(a->ai_socktype != b->ai_socktype) return a->ai_socktype - b->ai_socktype;
115   if(a->ai_protocol != b->ai_protocol) return a->ai_protocol - b->ai_protocol;
116   return sockaddrcmp(a->ai_addr, b->ai_addr);
117 }
118
119 /** @brief Comparison function for socket addresses
120  *
121  * Suitable for qsort().
122  */
123 int sockaddrcmp(const struct sockaddr *a,
124                 const struct sockaddr *b) {
125   const struct sockaddr_in *ina, *inb;
126   const struct sockaddr_in6 *in6a, *in6b;
127   
128   if(a->sa_family != b->sa_family) return a->sa_family - b->sa_family;
129   switch(a->sa_family) {
130   case PF_INET:
131     ina = (const struct sockaddr_in *)a;
132     inb = (const struct sockaddr_in *)b;
133     if(ina->sin_port != inb->sin_port) return ina->sin_port - inb->sin_port;
134     return ina->sin_addr.s_addr - inb->sin_addr.s_addr;
135     break;
136   case PF_INET6:
137     in6a = (const struct sockaddr_in6 *)a;
138     in6b = (const struct sockaddr_in6 *)b;
139     if(in6a->sin6_port != in6b->sin6_port)
140       return in6a->sin6_port - in6b->sin6_port;
141     return memcmp(&in6a->sin6_addr, &in6b->sin6_addr,
142                   sizeof (struct in6_addr));
143   default:
144     disorder_fatal(0, "unsupported protocol family %d", a->sa_family);
145   }
146 }
147
148 /** @brief Return nonzero if @p sin4 is an IPv4 multicast address */
149 static inline int multicast4(const struct sockaddr_in *sin4) {
150   return IN_MULTICAST(ntohl(sin4->sin_addr.s_addr));
151 }
152
153 /** @brief Return nonzero if @p sin6 is an IPv6 multicast address */
154 static inline int multicast6(const struct sockaddr_in6 *sin6) {
155   return IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr);
156 }
157
158 /** @brief Return true if @p sa represents a multicast address */
159 int multicast(const struct sockaddr *sa) {
160   switch(sa->sa_family) {
161   case AF_INET:
162     return multicast4((const struct sockaddr_in *)sa);
163   case AF_INET6:
164     return multicast6((const struct sockaddr_in6 *)sa);
165   default:
166     return 0;
167   }
168 }
169
170 /** @brief Format an IPv4 address */
171 static inline char *format_sockaddr4(const struct sockaddr_in *sin4) {
172   char buffer[1024], *r;
173
174   if(sin4->sin_port)
175     byte_xasprintf(&r, "%s port %u",
176                    inet_ntop(sin4->sin_family, (void *)&sin4->sin_addr,
177                              buffer, sizeof buffer),
178                    ntohs(sin4->sin_port));
179   else
180     byte_xasprintf(&r, "%s",
181                    inet_ntop(sin4->sin_family, (void *)&sin4->sin_addr,
182                              buffer, sizeof buffer));
183   return r;
184 }
185
186 /** @brief Format an IPv6 address */
187 static inline char *format_sockaddr6(const struct sockaddr_in6 *sin6) {
188   char buffer[1024], *r;
189
190   if(sin6->sin6_port)
191     byte_xasprintf(&r, "%s port %u",
192                    inet_ntop(sin6->sin6_family, (void *)&sin6->sin6_addr,
193                              buffer, sizeof buffer),
194                    ntohs(sin6->sin6_port));
195   else
196     byte_xasprintf(&r, "%s",
197                    inet_ntop(sin6->sin6_family, (void *)&sin6->sin6_addr,
198                              buffer, sizeof buffer));
199   return r;
200 }
201
202 #if HAVE_SYS_UN_H
203 /** @brief Format a UNIX socket address */
204 static inline char *format_sockaddrun(const struct sockaddr_un *sun) {
205   return xstrdup(sun->sun_path);
206 }
207 #endif
208     
209 /** @brief Construct a text description a sockaddr
210  * @param sa Socket address
211  * @return Human-readable form of address
212  */
213 char *format_sockaddr(const struct sockaddr *sa) {
214   switch(sa->sa_family) {
215   case AF_INET:
216     return format_sockaddr4((const struct sockaddr_in *)sa);
217   case AF_INET6:
218     return format_sockaddr6((const struct sockaddr_in6 *)sa);
219 #if HAVE_SYS_UN_H
220   case AF_UNIX:
221     return format_sockaddrun((const struct sockaddr_un *)sa);
222 #endif
223   default:
224     return 0;
225   }
226 }
227
228 /** @brief Parse the text form of a network address
229  * @param na Where to store result
230  * @param nvec Number of strings
231  * @param vec List of strings
232  * @return 0 on success, -1 on syntax error
233  */
234 int netaddress_parse(struct netaddress *na,
235                      int nvec,
236                      char **vec) {
237   const char *port;
238   long p;
239   int e;
240
241   na->af = AF_UNSPEC;
242   if(nvec > 0 && vec[0][0] == '-') {
243     if(!strcmp(vec[0], "-4"))
244       na->af = AF_INET;
245     else if(!strcmp(vec[0], "-6")) 
246       na->af = AF_INET6;
247     else if(!strcmp(vec[0], "-unix"))
248       na->af = AF_UNIX;
249     else if(!strcmp(vec[0], "-"))
250       na->af = AF_UNSPEC;
251     else
252       return -1;
253     --nvec;
254     ++vec;
255   }
256   if(nvec == 0)
257     return -1;
258   /* Possibilities are:
259    *
260    *       /path/to/unix/socket      an AF_UNIX socket
261    *       * PORT                    any address, specific port
262    *       PORT                      any address, specific port
263    *       ADDRESS PORT              specific address, specific port
264    */
265   if(vec[0][0] == '/' && na->af == AF_UNSPEC)
266     na->af = AF_UNIX;
267   if(na->af == AF_UNIX) {
268     if(nvec != 1)
269       return -1;
270     na->address = xstrdup(vec[0]);
271     na->port = -1;                      /* makes no sense */
272   } else {
273     switch(nvec) {
274     case 1:
275       na->address = NULL;
276       port = vec[0];
277       break;
278     case 2:
279       if(!strcmp(vec[0], "*"))
280         na->address = NULL;
281       else
282         na->address = xstrdup(vec[0]);
283       port = vec[1];
284       break;
285     default:
286       return -1;
287     }
288     if(port[strspn(port, "0123456789")])
289       return -1;
290     e = xstrtol(&p, port, NULL, 10);
291
292     if(e)
293       return -1;
294     if(p > 65535)
295       return -1;
296     na->port = (int)p;
297   }
298   return 0;
299 }
300
301 /** @brief Format a @ref netaddress structure
302  * @param na Network address to format
303  * @param nvecp Where to put string count, or NULL
304  * @param vecp Where to put strings
305  *
306  * The formatted form is suitable for passing to netaddress_parse().
307  */
308 void netaddress_format(const struct netaddress *na,
309                        int *nvecp,
310                        char ***vecp) {
311   struct vector v[1];
312
313   vector_init(v);
314   switch(na->af) {
315   case AF_UNSPEC: vector_append(v, xstrdup("-")); break;
316   case AF_INET: vector_append(v, xstrdup("-4")); break;
317   case AF_INET6: vector_append(v, xstrdup("-6")); break;
318   case AF_UNIX: vector_append(v, xstrdup("-unix")); break;
319   }
320   if(na->address)
321     vector_append(v, xstrdup(na->address));
322   else
323     vector_append(v, xstrdup("*"));
324   if(na->port != -1) {
325     char buffer[64];
326
327     byte_snprintf(buffer, sizeof buffer, "%d", na->port);
328     vector_append(v, xstrdup(buffer));
329   }
330   vector_terminate(v);
331   if(nvecp)
332     *nvecp = v->nvec;
333   if(vecp)
334     *vecp = v->vec;
335 }
336
337 /** @brief Resolve a network address
338  * @param na Address structure
339  * @param passive True if passive (bindable) address is desired
340  * @param protocol Protocol number desired (e.g. @c IPPROTO_TCP)
341  * @return List of suitable addresses or NULL
342  */
343 struct addrinfo *netaddress_resolve(const struct netaddress *na,
344                                     int passive,
345                                     int protocol) {
346   struct addrinfo *res, hints[1];
347   char service[64];
348   int rc;
349   char errbuf[1024];
350
351   memset(hints, 0, sizeof hints);
352   hints->ai_family = na->af;
353   hints->ai_protocol = protocol;
354   hints->ai_flags = passive ? AI_PASSIVE : 0;
355   byte_snprintf(service, sizeof service, "%d", na->port);
356   rc = getaddrinfo(na->address, service, hints, &res);
357   if(rc) {
358     disorder_error(0, "getaddrinfo %s %d: %s",
359                    na->address ? na->address : "*",
360                    na->port,
361                    format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
362     return NULL;
363   }
364   return res;
365 }
366
367 /*
368 Local Variables:
369 c-basic-offset:2
370 comment-column:40
371 End:
372 */