chiark / gitweb /
lib/addr.c: Handle `AF_UNIX' sockets in `netaddress_resolve'.
[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 <stddef.h>
24
25 #include <sys/types.h>
26 #if HAVE_SYS_SOCKET_H
27 # include <sys/socket.h>
28 #endif
29 #if HAVE_NETINET_IN_H
30 # include <netinet/in.h>
31 #endif
32 #if HAVE_ARPA_INET_H
33 # include <arpa/inet.h>
34 #endif
35 #if HAVE_SYS_UN_H
36 # include <sys/un.h>
37 #endif
38 #if HAVE_WS2TCPIP_H
39 # include <Ws2tcpip.h>
40 #endif
41
42 #include "log.h"
43 #include "printf.h"
44 #include "addr.h"
45 #include "mem.h"
46 #include "syscalls.h"
47 #include "configuration.h"
48 #include "vector.h"
49
50 /** @brief Convert a pair of strings to an address
51  * @param a Pointer to string list
52  * @param pref Hints structure for getaddrinfo, or NULL
53  * @param namep Where to store address description, or NULL
54  * @return Address info structure or NULL on error
55  *
56  * This converts one or two strings into an address specification suitable
57  * for passing to socket(), bind() etc.
58  *
59  * If there is only one string then it is assumed to be the service
60  * name (port number).  If there are two then the first is the host
61  * name and the second the service name.
62  *
63  * @p namep is used to return a description of the address suitable
64  * for use in log messages.
65  *
66  * If an error occurs a message is logged and a null pointer returned.
67  */
68 struct addrinfo *get_address(const struct stringlist *a,
69                              const struct addrinfo *pref,
70                              char **namep) {
71   struct addrinfo *res;
72   char *name;
73   int rc;
74   char errbuf[1024];
75
76   switch(a->n) {  
77   case 1:
78     byte_xasprintf(&name, "host * service %s", a->s[0]);
79     if((rc = getaddrinfo(0, a->s[0], pref, &res))) {
80       disorder_error(0, "getaddrinfo %s: %s", a->s[0],
81                      format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
82       return 0;
83     }
84     break;
85   case 2:
86     byte_xasprintf(&name, "host %s service %s", a->s[0], a->s[1]);
87     if((rc = getaddrinfo(a->s[0], a->s[1], pref, &res))) {
88       disorder_error(0, "getaddrinfo %s %s: %s",
89                      a->s[0], a->s[1],
90                      format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
91       return 0;
92     }
93     break;
94   default:
95     disorder_error(0, "invalid network address specification (n=%d)", a->n);
96     return 0;
97   }
98   if(!res || (pref && res->ai_socktype != pref->ai_socktype)) {
99     disorder_error(0, "getaddrinfo didn't give us a suitable socket address");
100     if(res)
101       freeaddrinfo(res);
102     return 0;
103   }
104   if(namep)
105     *namep = name;
106   return res;
107 }
108
109 /** @brief Comparison function for address information
110  *
111  * Suitable for qsort().
112  */
113 int addrinfocmp(const struct addrinfo *a,
114                 const struct addrinfo *b) {
115   if(a->ai_family != b->ai_family) return a->ai_family - b->ai_family;
116   if(a->ai_socktype != b->ai_socktype) return a->ai_socktype - b->ai_socktype;
117   if(a->ai_protocol != b->ai_protocol) return a->ai_protocol - b->ai_protocol;
118   return sockaddrcmp(a->ai_addr, b->ai_addr);
119 }
120
121 /** @brief Comparison function for socket addresses
122  *
123  * Suitable for qsort().
124  */
125 int sockaddrcmp(const struct sockaddr *a,
126                 const struct sockaddr *b) {
127   const struct sockaddr_in *ina, *inb;
128   const struct sockaddr_in6 *in6a, *in6b;
129   
130   if(a->sa_family != b->sa_family) return a->sa_family - b->sa_family;
131   switch(a->sa_family) {
132   case PF_INET:
133     ina = (const struct sockaddr_in *)a;
134     inb = (const struct sockaddr_in *)b;
135     if(ina->sin_port != inb->sin_port) return ina->sin_port - inb->sin_port;
136     return ina->sin_addr.s_addr - inb->sin_addr.s_addr;
137     break;
138   case PF_INET6:
139     in6a = (const struct sockaddr_in6 *)a;
140     in6b = (const struct sockaddr_in6 *)b;
141     if(in6a->sin6_port != in6b->sin6_port)
142       return in6a->sin6_port - in6b->sin6_port;
143     return memcmp(&in6a->sin6_addr, &in6b->sin6_addr,
144                   sizeof (struct in6_addr));
145   default:
146     disorder_fatal(0, "unsupported protocol family %d", a->sa_family);
147   }
148 }
149
150 /** @brief Return nonzero if @p sin4 is an IPv4 multicast address */
151 static inline int multicast4(const struct sockaddr_in *sin4) {
152   return IN_MULTICAST(ntohl(sin4->sin_addr.s_addr));
153 }
154
155 /** @brief Return nonzero if @p sin6 is an IPv6 multicast address */
156 static inline int multicast6(const struct sockaddr_in6 *sin6) {
157   return IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr);
158 }
159
160 /** @brief Return true if @p sa represents a multicast address */
161 int multicast(const struct sockaddr *sa) {
162   switch(sa->sa_family) {
163   case AF_INET:
164     return multicast4((const struct sockaddr_in *)sa);
165   case AF_INET6:
166     return multicast6((const struct sockaddr_in6 *)sa);
167   default:
168     return 0;
169   }
170 }
171
172 /** @brief Format an IPv4 address */
173 static inline char *format_sockaddr4(const struct sockaddr_in *sin4) {
174   char buffer[1024], *r;
175
176   if(sin4->sin_port)
177     byte_xasprintf(&r, "%s port %u",
178                    inet_ntop(sin4->sin_family, (void *)&sin4->sin_addr,
179                              buffer, sizeof buffer),
180                    ntohs(sin4->sin_port));
181   else
182     byte_xasprintf(&r, "%s",
183                    inet_ntop(sin4->sin_family, (void *)&sin4->sin_addr,
184                              buffer, sizeof buffer));
185   return r;
186 }
187
188 /** @brief Format an IPv6 address */
189 static inline char *format_sockaddr6(const struct sockaddr_in6 *sin6) {
190   char buffer[1024], *r;
191
192   if(sin6->sin6_port)
193     byte_xasprintf(&r, "%s port %u",
194                    inet_ntop(sin6->sin6_family, (void *)&sin6->sin6_addr,
195                              buffer, sizeof buffer),
196                    ntohs(sin6->sin6_port));
197   else
198     byte_xasprintf(&r, "%s",
199                    inet_ntop(sin6->sin6_family, (void *)&sin6->sin6_addr,
200                              buffer, sizeof buffer));
201   return r;
202 }
203
204 #if HAVE_SYS_UN_H
205 /** @brief Format a UNIX socket address */
206 static inline char *format_sockaddrun(const struct sockaddr_un *sun) {
207   return xstrdup(sun->sun_path);
208 }
209 #endif
210     
211 /** @brief Construct a text description a sockaddr
212  * @param sa Socket address
213  * @return Human-readable form of address
214  */
215 char *format_sockaddr(const struct sockaddr *sa) {
216   switch(sa->sa_family) {
217   case AF_INET:
218     return format_sockaddr4((const struct sockaddr_in *)sa);
219   case AF_INET6:
220     return format_sockaddr6((const struct sockaddr_in6 *)sa);
221 #if HAVE_SYS_UN_H
222   case AF_UNIX:
223     return format_sockaddrun((const struct sockaddr_un *)sa);
224 #endif
225   default:
226     return 0;
227   }
228 }
229
230 /** @brief Parse the text form of a network address
231  * @param na Where to store result
232  * @param nvec Number of strings
233  * @param vec List of strings
234  * @return 0 on success, -1 on syntax error
235  */
236 int netaddress_parse(struct netaddress *na,
237                      int nvec,
238                      char **vec) {
239   const char *port;
240   long p;
241   int e;
242
243   na->af = AF_UNSPEC;
244   if(nvec > 0 && vec[0][0] == '-') {
245     if(!strcmp(vec[0], "-4"))
246       na->af = AF_INET;
247     else if(!strcmp(vec[0], "-6")) 
248       na->af = AF_INET6;
249     else if(!strcmp(vec[0], "-unix"))
250       na->af = AF_UNIX;
251     else if(!strcmp(vec[0], "-"))
252       na->af = AF_UNSPEC;
253     else
254       return -1;
255     --nvec;
256     ++vec;
257   }
258   if(nvec == 0)
259     return -1;
260   /* Possibilities are:
261    *
262    *       /path/to/unix/socket      an AF_UNIX socket
263    *       * PORT                    any address, specific port
264    *       PORT                      any address, specific port
265    *       ADDRESS PORT              specific address, specific port
266    */
267   if(vec[0][0] == '/' && na->af == AF_UNSPEC)
268     na->af = AF_UNIX;
269   if(na->af == AF_UNIX) {
270     if(nvec != 1)
271       return -1;
272     na->address = xstrdup(vec[0]);
273     na->port = -1;                      /* makes no sense */
274   } else {
275     switch(nvec) {
276     case 1:
277       na->address = NULL;
278       port = vec[0];
279       break;
280     case 2:
281       if(!strcmp(vec[0], "*"))
282         na->address = NULL;
283       else
284         na->address = xstrdup(vec[0]);
285       port = vec[1];
286       break;
287     default:
288       return -1;
289     }
290     if(port[strspn(port, "0123456789")])
291       return -1;
292     e = xstrtol(&p, port, NULL, 10);
293
294     if(e)
295       return -1;
296     if(p > 65535)
297       return -1;
298     na->port = (int)p;
299   }
300   return 0;
301 }
302
303 /** @brief Format a @ref netaddress structure
304  * @param na Network address to format
305  * @param nvecp Where to put string count, or NULL
306  * @param vecp Where to put strings
307  *
308  * The formatted form is suitable for passing to netaddress_parse().
309  */
310 void netaddress_format(const struct netaddress *na,
311                        int *nvecp,
312                        char ***vecp) {
313   struct vector v[1];
314
315   vector_init(v);
316   switch(na->af) {
317   case AF_UNSPEC: vector_append(v, xstrdup("-")); break;
318   case AF_INET: vector_append(v, xstrdup("-4")); break;
319   case AF_INET6: vector_append(v, xstrdup("-6")); break;
320   case AF_UNIX: vector_append(v, xstrdup("-unix")); break;
321   }
322   if(na->address)
323     vector_append(v, xstrdup(na->address));
324   else
325     vector_append(v, xstrdup("*"));
326   if(na->port != -1) {
327     char buffer[64];
328
329     byte_snprintf(buffer, sizeof buffer, "%d", na->port);
330     vector_append(v, xstrdup(buffer));
331   }
332   vector_terminate(v);
333   if(nvecp)
334     *nvecp = v->nvec;
335   if(vecp)
336     *vecp = v->vec;
337 }
338
339 /** @brief Resolve a network address
340  * @param na Address structure
341  * @param passive True if passive (bindable) address is desired
342  * @param protocol Protocol number desired (e.g. @c IPPROTO_TCP)
343  * @return List of suitable addresses or NULL
344  *
345  * Free the address using netaddress_freeaddrinfo() because it might not
346  * have come from getaddrinfo() directly.
347  */
348 struct addrinfo *netaddress_resolve(const struct netaddress *na,
349                                     int passive,
350                                     int protocol) {
351   struct addrinfo *res, hints[1];
352   struct sockaddr_un *sun;
353   char service[64];
354   int rc;
355   char errbuf[1024];
356
357 #if HAVE_SYS_UN_H
358   if (na->af == AF_UNIX) {
359     /* `getaddrinfo' won't work, so we make our own one */
360     res = xmalloc(sizeof(*res));
361     res->ai_flags = 0;
362     res->ai_family = AF_UNIX;
363     res->ai_socktype = (protocol == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM);
364     res->ai_protocol = 0;
365     res->ai_addrlen = offsetof(struct sockaddr_un, sun_path) +
366       strlen(na->address) + 1;
367     sun = xmalloc(res->ai_addrlen);
368     sun->sun_family = AF_UNIX;
369     strcpy(sun->sun_path, na->address);
370     res->ai_addr = (struct sockaddr *)sun;
371     res->ai_canonname = sun->sun_path;
372     res->ai_next = 0;
373   } else
374 #endif
375   {
376     /* get the system to do the heavy lifting */
377     memset(hints, 0, sizeof hints);
378     hints->ai_family = na->af;
379     hints->ai_protocol = protocol;
380     hints->ai_flags = passive ? AI_PASSIVE : 0;
381     byte_snprintf(service, sizeof service, "%d", na->port);
382     rc = getaddrinfo(na->address, service, hints, &res);
383     if(rc) {
384       disorder_error(0, "getaddrinfo %s %d: %s",
385                      na->address ? na->address : "*",
386                      na->port,
387                      format_error(ec_getaddrinfo, rc, errbuf, sizeof errbuf));
388       return NULL;
389     }
390     assert(res->ai_family != AF_UNIX);
391   }
392   return res;
393 }
394
395 /** @brief Free an address-info list from netaddress_resovle()
396  * @param res Address-info list
397  */
398 void netaddress_freeaddrinfo(struct addrinfo *res) {
399 #if HAVE_SYS_UN_H
400   if(res->ai_family == AF_UNIX) {
401     xfree(res->ai_addr);
402     xfree(res);
403   } else
404 #endif
405     freeaddrinfo(res);
406 }
407
408 /*
409 Local Variables:
410 c-basic-offset:2
411 comment-column:40
412 End:
413 */