]> git.meshlink.io Git - catta/blob - src/socket.c
use WSAGetlastError/FormatMessage in place of strerror(errno) on Windows
[catta] / src / socket.c
1 /***
2   This file is part of catta.
3
4   catta is free software; you can redistribute it and/or modify it
5   under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2.1 of the
7   License, or (at your option) any later version.
8
9   catta is distributed in the hope that it will be useful, but WITHOUT
10   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
12   Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public
15   License along with catta; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17   USA.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <inttypes.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/time.h>
31 #include <sys/ioctl.h>
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h>
34 #endif
35 #include <assert.h>
36
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <net/if.h>
42 #include <sys/uio.h>
43
44 #ifdef IP_RECVIF
45 #include <net/if_dl.h>
46 #endif
47
48 #include <catta/log.h>
49 #include "dns.h"
50 #include "fdutil.h"
51 #include "socket.h"
52 #include "addr-util.h"
53 #include "internal.h"
54
55 /* this is a portability hack */
56 #ifndef IPV6_ADD_MEMBERSHIP
57 #ifdef  IPV6_JOIN_GROUP
58 #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
59 #endif
60 #endif
61
62 #ifndef IPV6_DROP_MEMBERSHIP
63 #ifdef  IPV6_LEAVE_GROUP
64 #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
65 #endif
66 #endif
67
68 static void mdns_mcast_group_ipv4(struct sockaddr_in *ret_sa) {
69     assert(ret_sa);
70
71     memset(ret_sa, 0, sizeof(struct sockaddr_in));
72     ret_sa->sin_family = AF_INET;
73     ret_sa->sin_port = htons(CATTA_MDNS_PORT);
74     inet_pton(AF_INET, CATTA_IPV4_MCAST_GROUP, &ret_sa->sin_addr);
75 }
76
77 static void mdns_mcast_group_ipv6(struct sockaddr_in6 *ret_sa) {
78     assert(ret_sa);
79
80     memset(ret_sa, 0, sizeof(struct sockaddr_in6));
81     ret_sa->sin6_family = AF_INET6;
82     ret_sa->sin6_port = htons(CATTA_MDNS_PORT);
83     inet_pton(AF_INET6, CATTA_IPV6_MCAST_GROUP, &ret_sa->sin6_addr);
84 }
85
86 static void ipv4_address_to_sockaddr(struct sockaddr_in *ret_sa, const CattaIPv4Address *a, uint16_t port) {
87     assert(ret_sa);
88     assert(a);
89     assert(port > 0);
90
91     memset(ret_sa, 0, sizeof(struct sockaddr_in));
92     ret_sa->sin_family = AF_INET;
93     ret_sa->sin_port = htons(port);
94     memcpy(&ret_sa->sin_addr, a, sizeof(CattaIPv4Address));
95 }
96
97 static void ipv6_address_to_sockaddr(struct sockaddr_in6 *ret_sa, const CattaIPv6Address *a, uint16_t port) {
98     assert(ret_sa);
99     assert(a);
100     assert(port > 0);
101
102     memset(ret_sa, 0, sizeof(struct sockaddr_in6));
103     ret_sa->sin6_family = AF_INET6;
104     ret_sa->sin6_port = htons(port);
105     memcpy(&ret_sa->sin6_addr, a, sizeof(CattaIPv6Address));
106 }
107
108 int catta_mdns_mcast_join_ipv4(int fd, const CattaIPv4Address *a, int idx, int join) {
109 #ifdef HAVE_STRUCT_IP_MREQN
110     struct ip_mreqn mreq;
111 #else
112     struct ip_mreq mreq;
113 #endif
114     struct sockaddr_in sa;
115
116     assert(fd >= 0);
117     assert(idx >= 0);
118     assert(a);
119
120     memset(&mreq, 0, sizeof(mreq));
121 #ifdef HAVE_STRUCT_IP_MREQN
122     mreq.imr_ifindex = idx;
123     mreq.imr_address.s_addr = a->address;
124 #else
125     mreq.imr_interface.s_addr = a->address;
126 #endif
127     mdns_mcast_group_ipv4(&sa);
128     mreq.imr_multiaddr = sa.sin_addr;
129
130     /* Some network drivers have issues with dropping membership of
131      * mcast groups when the iface is down, but don't allow rejoining
132      * when it comes back up. This is an ugly workaround */
133     if (join)
134         setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void *)&mreq, sizeof(mreq));
135
136     if (setsockopt(fd, IPPROTO_IP, join ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, (void *)&mreq, sizeof(mreq)) < 0) {
137         catta_log_warn("%s failed: %s", join ? "IP_ADD_MEMBERSHIP" : "IP_DROP_MEMBERSHIP", errnostrsocket());
138         return -1;
139     }
140
141     return 0;
142 }
143
144 int catta_mdns_mcast_join_ipv6(int fd, const CattaIPv6Address *a, int idx, int join) {
145     struct ipv6_mreq mreq6;
146     struct sockaddr_in6 sa6;
147
148     assert(fd >= 0);
149     assert(idx >= 0);
150     assert(a);
151
152     memset(&mreq6, 0, sizeof(mreq6));
153     mdns_mcast_group_ipv6 (&sa6);
154     mreq6.ipv6mr_multiaddr = sa6.sin6_addr;
155     mreq6.ipv6mr_interface = idx;
156
157     if (join)
158         setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (void *)&mreq6, sizeof(mreq6));
159
160     if (setsockopt(fd, IPPROTO_IPV6, join ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, (void *)&mreq6, sizeof(mreq6)) < 0) {
161         catta_log_warn("%s failed: %s", join ? "IPV6_ADD_MEMBERSHIP" : "IPV6_DROP_MEMBERSHIP", errnostrsocket());
162         return -1;
163     }
164
165     return 0;
166 }
167
168 static int reuseaddr(int fd) {
169     int yes;
170
171     yes = 1;
172     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)) < 0) {
173         catta_log_warn("SO_REUSEADDR failed: %s", errnostrsocket());
174         return -1;
175     }
176
177 #ifdef SO_REUSEPORT
178     yes = 1;
179     if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&yes, sizeof(yes)) < 0) {
180         catta_log_warn("SO_REUSEPORT failed: %s", errnostrsocket());
181         return -1;
182     }
183 #endif
184
185     return 0;
186 }
187
188 static int bind_with_warn(int fd, const struct sockaddr *sa, socklen_t l) {
189
190     assert(fd >= 0);
191     assert(sa);
192     assert(l > 0);
193
194 #ifdef _WIN32
195     // Windows does not allow address reuse when SO_REUSEADDR was set after
196     // bind() on the first socket, so we must set it before.
197     // Note that this spoils the detection trickery below and the warning will
198     // not be logged.
199
200     if (reuseaddr(fd) < 0)
201         return -1;
202 #endif
203
204     if (bind(fd, sa, l) < 0) {
205
206         if (errno != EADDRINUSE) {
207             catta_log_warn("bind() failed: %s", errnostrsocket());
208             return -1;
209         }
210
211         catta_log_warn("*** WARNING: Detected another %s mDNS stack running on this host. This makes mDNS unreliable and is thus not recommended. ***",
212                        sa->sa_family == AF_INET ? "IPv4" : "IPv6");
213
214         /* Try again, this time with SO_REUSEADDR set */
215         if (reuseaddr(fd) < 0)
216             return -1;
217
218         if (bind(fd, sa, l) < 0) {
219             catta_log_warn("bind() failed: %s", errnostrsocket());
220             return -1;
221         }
222     } else {
223
224         /* We enable SO_REUSEADDR afterwards, to make sure that the
225          * user may run other mDNS implementations if he really
226          * wants. */
227
228         if (reuseaddr(fd) < 0)
229             return -1;
230     }
231
232     return 0;
233 }
234
235 static int ipv4_pktinfo(int fd) {
236     int yes;
237
238 #ifdef IP_PKTINFO
239     yes = 1;
240     if (setsockopt(fd, IPPROTO_IP, IP_PKTINFO, (void *)&yes, sizeof(yes)) < 0) {
241         catta_log_warn("IP_PKTINFO failed: %s", errnostrsocket());
242         return -1;
243     }
244 #else
245
246 #ifdef IP_RECVINTERFACE
247     yes = 1;
248     if (setsockopt (fd, IPPROTO_IP, IP_RECVINTERFACE, (void *)&yes, sizeof(yes)) < 0) {
249         catta_log_warn("IP_RECVINTERFACE failed: %s", errnostrsocket());
250         return -1;
251     }
252 #elif defined(IP_RECVIF)
253     yes = 1;
254     if (setsockopt (fd, IPPROTO_IP, IP_RECVIF, (void *)&yes, sizeof(yes)) < 0) {
255         catta_log_warn("IP_RECVIF failed: %s", errnostrsocket());
256         return -1;
257     }
258 #endif
259
260 #ifdef IP_RECVDSTADDR
261     yes = 1;
262     if (setsockopt (fd, IPPROTO_IP, IP_RECVDSTADDR, (void *)&yes, sizeof(yes)) < 0) {
263         catta_log_warn("IP_RECVDSTADDR failed: %s", errnostrsocket());
264         return -1;
265     }
266 #endif
267
268 #endif /* IP_PKTINFO */
269
270 #ifdef IP_RECVTTL
271     yes = 1;
272     if (setsockopt(fd, IPPROTO_IP, IP_RECVTTL, (void *)&yes, sizeof(yes)) < 0) {
273         catta_log_warn("IP_RECVTTL failed: %s", errnostrsocket());
274         return -1;
275     }
276 #endif
277
278     return 0;
279 }
280
281 static int ipv6_pktinfo(int fd) {
282     int yes;
283
284 #ifdef IPV6_RECVPKTINFO
285     yes = 1;
286     if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&yes, sizeof(yes)) < 0) {
287         catta_log_warn("IPV6_RECVPKTINFO failed: %s", errnostrsocket());
288         return -1;
289     }
290 #elif defined(IPV6_PKTINFO)
291     yes = 1;
292     if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, (void *)&yes, sizeof(yes)) < 0) {
293         catta_log_warn("IPV6_PKTINFO failed: %s", errnostrsocket());
294         return -1;
295     }
296 #endif
297
298 #ifdef IPV6_RECVHOPS
299     yes = 1;
300     if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPS, (void *)&yes, sizeof(yes)) < 0) {
301         catta_log_warn("IPV6_RECVHOPS failed: %s", errnostrsocket());
302         return -1;
303     }
304 #elif defined(IPV6_RECVHOPLIMIT)
305     yes = 1;
306     if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, (void *)&yes, sizeof(yes)) < 0) {
307         catta_log_warn("IPV6_RECVHOPLIMIT failed: %s", errnostrsocket());
308         return -1;
309     }
310 #elif defined(IPV6_HOPLIMIT)
311     yes = 1;
312     if (setsockopt(fd, IPPROTO_IPV6, IPV6_HOPLIMIT, (void *)&yes, sizeof(yes)) < 0) {
313         catta_log_warn("IPV6_HOPLIMIT failed: %s", errnostrsocket());
314         return -1;
315     }
316 #endif
317
318     return 0;
319 }
320
321 int catta_open_socket_ipv4(int no_reuse) {
322     struct sockaddr_in local;
323     int fd = -1, r, ittl;
324     uint8_t ttl, cyes;
325
326     if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
327         catta_log_warn("socket() failed: %s", errnostrsocket());
328         goto fail;
329     }
330
331     ttl = 255;
332     if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (void *)&ttl, sizeof(ttl)) < 0) {
333         catta_log_warn("IP_MULTICAST_TTL failed: %s", errnostrsocket());
334         goto fail;
335     }
336
337     ittl = 255;
338     if (setsockopt(fd, IPPROTO_IP, IP_TTL, (void *)&ittl, sizeof(ittl)) < 0) {
339         catta_log_warn("IP_TTL failed: %s", errnostrsocket());
340         goto fail;
341     }
342
343     cyes = 1;
344     if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, (void *)&cyes, sizeof(cyes)) < 0) {
345         catta_log_warn("IP_MULTICAST_LOOP failed: %s", errnostrsocket());
346         goto fail;
347     }
348
349     memset(&local, 0, sizeof(local));
350     local.sin_family = AF_INET;
351     local.sin_port = htons(CATTA_MDNS_PORT);
352
353     if (no_reuse)
354         r = bind(fd, (struct sockaddr*) &local, sizeof(local));
355     else
356         r = bind_with_warn(fd, (struct sockaddr*) &local, sizeof(local));
357
358     if (r < 0)
359         goto fail;
360
361     if (ipv4_pktinfo (fd) < 0)
362          goto fail;
363
364     if (catta_set_cloexec(fd) < 0) {
365         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
366         goto fail;
367     }
368
369     if (catta_set_nonblock(fd) < 0) {
370         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
371         goto fail;
372     }
373
374     return fd;
375
376 fail:
377     if (fd >= 0)
378         closesocket(fd);
379
380     return -1;
381 }
382
383 int catta_open_socket_ipv6(int no_reuse) {
384     struct sockaddr_in6 sa, local;
385     int fd = -1, yes, r;
386     int ttl;
387
388     mdns_mcast_group_ipv6(&sa);
389
390     if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
391         catta_log_warn("socket() failed: %s", errnostrsocket());
392         goto fail;
393     }
394
395     ttl = 255;
396     if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (void *)&ttl, sizeof(ttl)) < 0) {
397         catta_log_warn("IPV6_MULTICAST_HOPS failed: %s", errnostrsocket());
398         goto fail;
399     }
400
401     ttl = 255;
402     if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (void *)&ttl, sizeof(ttl)) < 0) {
403         catta_log_warn("IPV6_UNICAST_HOPS failed: %s", errnostrsocket());
404         goto fail;
405     }
406
407     yes = 1;
408     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&yes, sizeof(yes)) < 0) {
409         catta_log_warn("IPV6_V6ONLY failed: %s", errnostrsocket());
410         goto fail;
411     }
412
413     yes = 1;
414     if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (void *)&yes, sizeof(yes)) < 0) {
415         catta_log_warn("IPV6_MULTICAST_LOOP failed: %s", errnostrsocket());
416         goto fail;
417     }
418
419     memset(&local, 0, sizeof(local));
420     local.sin6_family = AF_INET6;
421     local.sin6_port = htons(CATTA_MDNS_PORT);
422
423     if (no_reuse)
424         r = bind(fd, (struct sockaddr*) &local, sizeof(local));
425     else
426         r = bind_with_warn(fd, (struct sockaddr*) &local, sizeof(local));
427
428     if (r < 0)
429         goto fail;
430
431     if (ipv6_pktinfo(fd) < 0)
432         goto fail;
433
434     if (catta_set_cloexec(fd) < 0) {
435         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
436         goto fail;
437     }
438
439     if (catta_set_nonblock(fd) < 0) {
440         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
441         goto fail;
442     }
443
444     return fd;
445
446 fail:
447     if (fd >= 0)
448         closesocket(fd);
449
450     return -1;
451 }
452
453 static int sendmsg_loop(int fd, struct msghdr *msg, int flags) {
454     assert(fd >= 0);
455     assert(msg);
456
457     for (;;) {
458
459         if (sendmsg(fd, msg, flags) >= 0)
460             break;
461
462         if (errno == EINTR)
463             continue;
464
465         if (errno != EAGAIN && errno != EWOULDBLOCK) {
466             char where[64];
467             struct sockaddr_in *sin = msg->msg_name;
468
469             inet_ntop(sin->sin_family, &sin->sin_addr, where, sizeof(where));
470             catta_log_debug("sendmsg() to %s failed: %s", where, errnostrsocket());
471             return -1;
472         }
473
474         if (catta_wait_for_write(fd) < 0)
475             return -1;
476     }
477
478     return 0;
479 }
480
481 int catta_send_dns_packet_ipv4(
482         int fd,
483         CattaIfIndex iface,
484         CattaDnsPacket *p,
485         const CattaIPv4Address *src_address,
486         const CattaIPv4Address *dst_address,
487         uint16_t dst_port) {
488
489     struct sockaddr_in sa;
490     struct msghdr msg;
491     struct iovec io;
492 #ifdef IP_PKTINFO
493     struct cmsghdr *cmsg;
494     size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_pktinfo)) / sizeof(size_t)) + 1];
495 #elif !defined(IP_MULTICAST_IF) && defined(IP_SENDSRCADDR)
496     struct cmsghdr *cmsg;
497     size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_addr)) / sizeof(size_t)) + 1];
498 #endif
499
500     assert(fd >= 0);
501     assert(p);
502     assert(catta_dns_packet_check_valid(p) >= 0);
503     assert(!dst_address || dst_port > 0);
504
505     if (!dst_address)
506         mdns_mcast_group_ipv4(&sa);
507     else
508         ipv4_address_to_sockaddr(&sa, dst_address, dst_port);
509
510     memset(&io, 0, sizeof(io));
511     io.iov_base = CATTA_DNS_PACKET_DATA(p);
512     io.iov_len = p->size;
513
514     memset(&msg, 0, sizeof(msg));
515     msg.msg_name = &sa;
516     msg.msg_namelen = sizeof(sa);
517     msg.msg_iov = &io;
518     msg.msg_iovlen = 1;
519     msg.msg_flags = 0;
520     msg.msg_control = NULL;
521     msg.msg_controllen = 0;
522
523 #ifdef IP_PKTINFO
524     if (iface > 0 || src_address) {
525         struct in_pktinfo *pkti;
526
527         memset(cmsg_data, 0, sizeof(cmsg_data));
528         msg.msg_control = cmsg_data;
529         msg.msg_controllen = CMSG_LEN(sizeof(struct in_pktinfo));
530
531         cmsg = CMSG_FIRSTHDR(&msg);
532         cmsg->cmsg_len = msg.msg_controllen;
533         cmsg->cmsg_level = IPPROTO_IP;
534         cmsg->cmsg_type = IP_PKTINFO;
535
536         pkti = (struct in_pktinfo*) CMSG_DATA(cmsg);
537
538         if (iface > 0)
539             pkti->ipi_ifindex = iface;
540
541 #ifdef HAVE_IPI_SPEC_DST
542         if (src_address)
543             pkti->ipi_spec_dst.s_addr = src_address->address;
544 #endif
545     }
546 #elif defined(IP_MULTICAST_IF)
547     if (src_address) {
548         struct in_addr any = { INADDR_ANY };
549         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (void *)(src_address ? &src_address->address : &any), sizeof(struct in_addr)) < 0) {
550             catta_log_warn("IP_MULTICAST_IF failed: %s", errnostrsocket());
551             return -1;
552         }
553     }
554 #elif defined(IP_SENDSRCADDR)
555     if (src_address) {
556         struct in_addr *addr;
557
558         memset(cmsg_data, 0, sizeof(cmsg_data));
559         msg.msg_control = cmsg_data;
560         msg.msg_controllen = CMSG_LEN(sizeof(struct in_addr));
561
562         cmsg = CMSG_FIRSTHDR(&msg);
563         cmsg->cmsg_len = msg.msg_controllen;
564         cmsg->cmsg_level = IPPROTO_IP;
565         cmsg->cmsg_type = IP_SENDSRCADDR;
566
567         addr = (struct in_addr *)CMSG_DATA(cmsg);
568         addr->s_addr =  src_address->address;
569     }
570 #elif defined(__GNUC__)
571 #warning "FIXME: We need some code to set the outgoing interface/local address here if IP_PKTINFO/IP_MULTICAST_IF is not available"
572 #endif
573
574     return sendmsg_loop(fd, &msg, 0);
575 }
576
577 int catta_send_dns_packet_ipv6(
578         int fd,
579         CattaIfIndex iface,
580         CattaDnsPacket *p,
581         const CattaIPv6Address *src_address,
582         const CattaIPv6Address *dst_address,
583         uint16_t dst_port) {
584
585     struct sockaddr_in6 sa;
586     struct msghdr msg;
587     struct iovec io;
588     struct cmsghdr *cmsg;
589     size_t cmsg_data[(CMSG_SPACE(sizeof(struct in6_pktinfo))/sizeof(size_t)) + 1];
590
591     assert(fd >= 0);
592     assert(p);
593     assert(catta_dns_packet_check_valid(p) >= 0);
594     assert(!dst_address || dst_port > 0);
595
596     if (!dst_address)
597         mdns_mcast_group_ipv6(&sa);
598     else
599         ipv6_address_to_sockaddr(&sa, dst_address, dst_port);
600
601     memset(&io, 0, sizeof(io));
602     io.iov_base = CATTA_DNS_PACKET_DATA(p);
603     io.iov_len = p->size;
604
605     memset(&msg, 0, sizeof(msg));
606     msg.msg_name = &sa;
607     msg.msg_namelen = sizeof(sa);
608     msg.msg_iov = &io;
609     msg.msg_iovlen = 1;
610     msg.msg_flags = 0;
611
612     if (iface > 0 || src_address) {
613         struct in6_pktinfo *pkti;
614
615         memset(cmsg_data, 0, sizeof(cmsg_data));
616         msg.msg_control = cmsg_data;
617         msg.msg_controllen = CMSG_LEN(sizeof(struct in6_pktinfo));
618
619         cmsg = CMSG_FIRSTHDR(&msg);
620         cmsg->cmsg_len = msg.msg_controllen;
621         cmsg->cmsg_level = IPPROTO_IPV6;
622         cmsg->cmsg_type = IPV6_PKTINFO;
623
624         pkti = (struct in6_pktinfo*) CMSG_DATA(cmsg);
625
626         if (iface > 0)
627             pkti->ipi6_ifindex = iface;
628
629         if (src_address)
630             memcpy(&pkti->ipi6_addr, src_address->address, sizeof(src_address->address));
631     } else {
632         msg.msg_control = NULL;
633         msg.msg_controllen = 0;
634     }
635
636     return sendmsg_loop(fd, &msg, 0);
637 }
638
639 CattaDnsPacket *catta_recv_dns_packet_ipv4(
640         int fd,
641         CattaIPv4Address *ret_src_address,
642         uint16_t *ret_src_port,
643         CattaIPv4Address *ret_dst_address,
644         CattaIfIndex *ret_iface,
645         uint8_t *ret_ttl) {
646
647     CattaDnsPacket *p= NULL;
648     struct msghdr msg;
649     struct iovec io;
650     size_t aux[1024 / sizeof(size_t)]; /* for alignment on ia64 ! */
651     ssize_t l;
652     struct cmsghdr *cmsg;
653     int found_addr = 0;
654     int ms;
655     struct sockaddr_in sa;
656
657     assert(fd >= 0);
658
659     if (ioctl(fd, FIONREAD, &ms) < 0) {
660         catta_log_warn("ioctl(): %s", errnostrsocket());
661         goto fail;
662     }
663
664     if (ms < 0) {
665         catta_log_warn("FIONREAD returned negative value.");
666         goto fail;
667     }
668
669     p = catta_dns_packet_new(ms + CATTA_DNS_PACKET_EXTRA_SIZE);
670
671     io.iov_base = CATTA_DNS_PACKET_DATA(p);
672     io.iov_len = p->max_size;
673
674     memset(&msg, 0, sizeof(msg));
675     msg.msg_name = &sa;
676     msg.msg_namelen = sizeof(sa);
677     msg.msg_iov = &io;
678     msg.msg_iovlen = 1;
679     msg.msg_control = aux;
680     msg.msg_controllen = sizeof(aux);
681     msg.msg_flags = 0;
682
683     if ((l = recvmsg(fd, &msg, 0)) < 0) {
684         /* Linux returns EAGAIN when an invalid IP packet has been
685         received. We suppress warnings in this case because this might
686         create quite a bit of log traffic on machines with unstable
687         links. (See #60) */
688
689         if (errno != EAGAIN)
690             catta_log_warn("recvmsg(): %s", errnostrsocket());
691
692         goto fail;
693     }
694
695     /* For corrupt packets FIONREAD returns zero size (See rhbz #607297). So
696      * fail after having read them. */
697     if (!ms)
698         goto fail;
699
700     if (sa.sin_addr.s_addr == INADDR_ANY)
701         /* Linux 2.4 behaves very strangely sometimes! */
702         goto fail;
703
704     assert(!(msg.msg_flags & MSG_CTRUNC));
705     assert(!(msg.msg_flags & MSG_TRUNC));
706
707     p->size = (size_t) l;
708
709     if (ret_src_port)
710         *ret_src_port = catta_port_from_sockaddr((struct sockaddr*) &sa);
711
712     if (ret_src_address) {
713         CattaAddress a;
714         catta_address_from_sockaddr((struct sockaddr*) &sa, &a);
715         *ret_src_address = a.data.ipv4;
716     }
717
718     if (ret_ttl)
719         *ret_ttl = 255;
720
721     if (ret_iface)
722         *ret_iface = CATTA_IF_UNSPEC;
723
724     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
725
726         if (cmsg->cmsg_level == IPPROTO_IP) {
727
728             switch (cmsg->cmsg_type) {
729 #ifdef IP_RECVTTL
730                 case IP_RECVTTL:
731 #endif
732                 case IP_TTL:
733                     if (ret_ttl)
734                         *ret_ttl = (uint8_t) (*(int *) CMSG_DATA(cmsg));
735
736                     break;
737
738 #ifdef IP_PKTINFO
739                 case IP_PKTINFO: {
740                     struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg);
741
742                     if (ret_iface && i->ipi_ifindex > 0)
743                         *ret_iface = (int) i->ipi_ifindex;
744
745                     if (ret_dst_address)
746                         ret_dst_address->address = i->ipi_addr.s_addr;
747
748                     found_addr = 1;
749
750                     break;
751                 }
752 #endif
753
754 #ifdef IP_RECVIF
755                 case IP_RECVIF: {
756                     struct sockaddr_dl *sdl = (struct sockaddr_dl *) CMSG_DATA (cmsg);
757
758                     if (ret_iface) {
759 #ifdef __sun
760                         if (*(uint_t*) sdl > 0)
761                             *ret_iface = *(uint_t*) sdl;
762 #else
763
764                         if (sdl->sdl_index > 0)
765                             *ret_iface = (int) sdl->sdl_index;
766 #endif
767                     }
768
769                     break;
770                 }
771 #endif
772
773 #ifdef IP_RECVDSTADDR
774                 case IP_RECVDSTADDR:
775                     if (ret_dst_address)
776                         memcpy(&ret_dst_address->address, CMSG_DATA (cmsg), 4);
777
778                     found_addr = 1;
779                     break;
780 #endif
781
782                 default:
783                     catta_log_warn("Unhandled cmsg_type: %d", cmsg->cmsg_type);
784                     break;
785             }
786         }
787     }
788
789     assert(found_addr);
790
791     return p;
792
793 fail:
794     if (p)
795         catta_dns_packet_free(p);
796
797     return NULL;
798 }
799
800 CattaDnsPacket *catta_recv_dns_packet_ipv6(
801         int fd,
802         CattaIPv6Address *ret_src_address,
803         uint16_t *ret_src_port,
804         CattaIPv6Address *ret_dst_address,
805         CattaIfIndex *ret_iface,
806         uint8_t *ret_ttl) {
807
808     CattaDnsPacket *p = NULL;
809     struct msghdr msg;
810     struct iovec io;
811     size_t aux[1024 / sizeof(size_t)];
812     ssize_t l;
813     int ms;
814     struct cmsghdr *cmsg;
815     int found_ttl = 0, found_iface = 0;
816     struct sockaddr_in6 sa;
817
818     assert(fd >= 0);
819
820     if (ioctl(fd, FIONREAD, &ms) < 0) {
821         catta_log_warn("ioctl(): %s", errnostrsocket());
822         goto fail;
823     }
824
825     if (ms < 0) {
826         catta_log_warn("FIONREAD returned negative value.");
827         goto fail;
828     }
829
830     p = catta_dns_packet_new(ms + CATTA_DNS_PACKET_EXTRA_SIZE);
831
832     io.iov_base = CATTA_DNS_PACKET_DATA(p);
833     io.iov_len = p->max_size;
834
835     memset(&msg, 0, sizeof(msg));
836     msg.msg_name = (struct sockaddr*) &sa;
837     msg.msg_namelen = sizeof(sa);
838
839     msg.msg_iov = &io;
840     msg.msg_iovlen = 1;
841     msg.msg_control = aux;
842     msg.msg_controllen = sizeof(aux);
843     msg.msg_flags = 0;
844
845     if ((l = recvmsg(fd, &msg, 0)) < 0) {
846         /* Linux returns EAGAIN when an invalid IP packet has been
847         received. We suppress warnings in this case because this might
848         create quite a bit of log traffic on machines with unstable
849         links. (See #60) */
850
851         if (errno != EAGAIN)
852             catta_log_warn("recvmsg(): %s", errnostrsocket());
853
854         goto fail;
855     }
856
857     /* For corrupt packets FIONREAD returns zero size (See rhbz #607297). So
858      * fail after having read them. */
859     if (!ms)
860         goto fail;
861
862     assert(!(msg.msg_flags & MSG_CTRUNC));
863     assert(!(msg.msg_flags & MSG_TRUNC));
864
865     p->size = (size_t) l;
866
867     if (ret_src_port)
868         *ret_src_port = catta_port_from_sockaddr((struct sockaddr*) &sa);
869
870     if (ret_src_address) {
871         CattaAddress a;
872         catta_address_from_sockaddr((struct sockaddr*) &sa, &a);
873         *ret_src_address = a.data.ipv6;
874     }
875
876     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
877
878         if (cmsg->cmsg_level == IPPROTO_IPV6) {
879
880             switch (cmsg->cmsg_type) {
881
882                 case IPV6_HOPLIMIT:
883
884                     if (ret_ttl)
885                         *ret_ttl = (uint8_t) (*(int *) CMSG_DATA(cmsg));
886
887                     found_ttl = 1;
888
889                     break;
890
891                 case IPV6_PKTINFO: {
892                     struct in6_pktinfo *i = (struct in6_pktinfo*) CMSG_DATA(cmsg);
893
894                     if (ret_iface && i->ipi6_ifindex > 0)
895                         *ret_iface = i->ipi6_ifindex;
896
897                     if (ret_dst_address)
898                         memcpy(ret_dst_address->address, i->ipi6_addr.s6_addr, 16);
899
900                     found_iface = 1;
901                     break;
902                 }
903
904                 default:
905                     catta_log_warn("Unhandled cmsg_type: %d", cmsg->cmsg_type);
906                     break;
907             }
908         }
909     }
910
911     assert(found_iface);
912     assert(found_ttl);
913
914     return p;
915
916 fail:
917     if (p)
918         catta_dns_packet_free(p);
919
920     return NULL;
921 }
922
923 int catta_open_unicast_socket_ipv4(void) {
924     struct sockaddr_in local;
925     int fd = -1;
926
927     if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
928         catta_log_warn("socket() failed: %s", errnostrsocket());
929         goto fail;
930     }
931
932     memset(&local, 0, sizeof(local));
933     local.sin_family = AF_INET;
934
935     if (bind(fd, (struct sockaddr*) &local, sizeof(local)) < 0) {
936         catta_log_warn("bind() failed: %s", errnostrsocket());
937         goto fail;
938     }
939
940     if (ipv4_pktinfo(fd) < 0) {
941          goto fail;
942     }
943
944     if (catta_set_cloexec(fd) < 0) {
945         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
946         goto fail;
947     }
948
949     if (catta_set_nonblock(fd) < 0) {
950         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
951         goto fail;
952     }
953
954     return fd;
955
956 fail:
957     if (fd >= 0)
958         closesocket(fd);
959
960     return -1;
961 }
962
963 int catta_open_unicast_socket_ipv6(void) {
964     struct sockaddr_in6 local;
965     int fd = -1, yes;
966
967     if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
968         catta_log_warn("socket() failed: %s", errnostrsocket());
969         goto fail;
970     }
971
972     yes = 1;
973     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&yes, sizeof(yes)) < 0) {
974         catta_log_warn("IPV6_V6ONLY failed: %s", errnostrsocket());
975         goto fail;
976     }
977
978     memset(&local, 0, sizeof(local));
979     local.sin6_family = AF_INET6;
980
981     if (bind(fd, (struct sockaddr*) &local, sizeof(local)) < 0) {
982         catta_log_warn("bind() failed: %s", errnostrsocket());
983         goto fail;
984     }
985
986     if (ipv6_pktinfo(fd) < 0)
987         goto fail;
988
989     if (catta_set_cloexec(fd) < 0) {
990         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
991         goto fail;
992     }
993
994     if (catta_set_nonblock(fd) < 0) {
995         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
996         goto fail;
997     }
998
999     return fd;
1000
1001 fail:
1002     if (fd >= 0)
1003         closesocket(fd);
1004
1005     return -1;
1006 }