]> git.meshlink.io Git - catta/blob - src/socket.c
set IPv4 source address correctly 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 *sa = msg->msg_name;
468
469             if(sa->sa_family == AF_INET)
470                 inet_ntop(sa->sa_family, &((struct sockaddr_in *)sa)->sin_addr, where, sizeof(where));
471             else
472                 inet_ntop(sa->sa_family, &((struct sockaddr_in6 *)sa)->sin6_addr, where, sizeof(where));
473             catta_log_debug("sendmsg() to %s failed: %s", where, errnostrsocket());
474             return -1;
475         }
476
477         if (catta_wait_for_write(fd) < 0)
478             return -1;
479     }
480
481     return 0;
482 }
483
484 int catta_send_dns_packet_ipv4(
485         int fd,
486         CattaIfIndex iface,
487         CattaDnsPacket *p,
488         const CattaIPv4Address *src_address,
489         const CattaIPv4Address *dst_address,
490         uint16_t dst_port) {
491
492     struct sockaddr_in sa;
493     struct msghdr msg;
494     struct iovec io;
495 #ifdef IP_PKTINFO
496     struct cmsghdr *cmsg;
497     size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_pktinfo)) / sizeof(size_t)) + 1];
498 #elif !defined(IP_MULTICAST_IF) && defined(IP_SENDSRCADDR)
499     struct cmsghdr *cmsg;
500     size_t cmsg_data[( CMSG_SPACE(sizeof(struct in_addr)) / sizeof(size_t)) + 1];
501 #endif
502
503     assert(fd >= 0);
504     assert(p);
505     assert(catta_dns_packet_check_valid(p) >= 0);
506     assert(!dst_address || dst_port > 0);
507
508     if (!dst_address)
509         mdns_mcast_group_ipv4(&sa);
510     else
511         ipv4_address_to_sockaddr(&sa, dst_address, dst_port);
512
513     memset(&io, 0, sizeof(io));
514     io.iov_base = CATTA_DNS_PACKET_DATA(p);
515     io.iov_len = p->size;
516
517     memset(&msg, 0, sizeof(msg));
518     msg.msg_name = &sa;
519     msg.msg_namelen = sizeof(sa);
520     msg.msg_iov = &io;
521     msg.msg_iovlen = 1;
522     msg.msg_flags = 0;
523     msg.msg_control = NULL;
524     msg.msg_controllen = 0;
525
526 #ifdef IP_PKTINFO
527     if (iface > 0 || src_address) {
528         struct in_pktinfo *pkti;
529
530         memset(cmsg_data, 0, sizeof(cmsg_data));
531         msg.msg_control = cmsg_data;
532         msg.msg_controllen = CMSG_LEN(sizeof(struct in_pktinfo));
533
534         cmsg = CMSG_FIRSTHDR(&msg);
535         cmsg->cmsg_len = msg.msg_controllen;
536         cmsg->cmsg_level = IPPROTO_IP;
537         cmsg->cmsg_type = IP_PKTINFO;
538
539         pkti = (struct in_pktinfo*) CMSG_DATA(cmsg);
540
541         if (iface > 0)
542             pkti->ipi_ifindex = iface;
543
544 #ifdef HAVE_IPI_SPEC_DST
545         if (src_address)
546             pkti->ipi_spec_dst.s_addr = src_address->address;
547 #else
548         if (src_address)
549             pkti->ipi_addr.s_addr = src_address->address;
550 #endif
551     }
552 #elif defined(IP_MULTICAST_IF)
553     if (src_address) {
554         struct in_addr any = { INADDR_ANY };
555         if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (void *)(src_address ? &src_address->address : &any), sizeof(struct in_addr)) < 0) {
556             catta_log_warn("IP_MULTICAST_IF failed: %s", errnostrsocket());
557             return -1;
558         }
559     }
560 #elif defined(IP_SENDSRCADDR)
561     if (src_address) {
562         struct in_addr *addr;
563
564         memset(cmsg_data, 0, sizeof(cmsg_data));
565         msg.msg_control = cmsg_data;
566         msg.msg_controllen = CMSG_LEN(sizeof(struct in_addr));
567
568         cmsg = CMSG_FIRSTHDR(&msg);
569         cmsg->cmsg_len = msg.msg_controllen;
570         cmsg->cmsg_level = IPPROTO_IP;
571         cmsg->cmsg_type = IP_SENDSRCADDR;
572
573         addr = (struct in_addr *)CMSG_DATA(cmsg);
574         addr->s_addr =  src_address->address;
575     }
576 #elif defined(__GNUC__)
577 #warning "FIXME: We need some code to set the outgoing interface/local address here if IP_PKTINFO/IP_MULTICAST_IF is not available"
578 #endif
579
580     return sendmsg_loop(fd, &msg, 0);
581 }
582
583 int catta_send_dns_packet_ipv6(
584         int fd,
585         CattaIfIndex iface,
586         CattaDnsPacket *p,
587         const CattaIPv6Address *src_address,
588         const CattaIPv6Address *dst_address,
589         uint16_t dst_port) {
590
591     struct sockaddr_in6 sa;
592     struct msghdr msg;
593     struct iovec io;
594     struct cmsghdr *cmsg;
595     size_t cmsg_data[(CMSG_SPACE(sizeof(struct in6_pktinfo))/sizeof(size_t)) + 1];
596
597     assert(fd >= 0);
598     assert(p);
599     assert(catta_dns_packet_check_valid(p) >= 0);
600     assert(!dst_address || dst_port > 0);
601
602     if (!dst_address)
603         mdns_mcast_group_ipv6(&sa);
604     else
605         ipv6_address_to_sockaddr(&sa, dst_address, dst_port);
606
607     memset(&io, 0, sizeof(io));
608     io.iov_base = CATTA_DNS_PACKET_DATA(p);
609     io.iov_len = p->size;
610
611     memset(&msg, 0, sizeof(msg));
612     msg.msg_name = &sa;
613     msg.msg_namelen = sizeof(sa);
614     msg.msg_iov = &io;
615     msg.msg_iovlen = 1;
616     msg.msg_flags = 0;
617
618     if (iface > 0 || src_address) {
619         struct in6_pktinfo *pkti;
620
621         memset(cmsg_data, 0, sizeof(cmsg_data));
622         msg.msg_control = cmsg_data;
623         msg.msg_controllen = CMSG_LEN(sizeof(struct in6_pktinfo));
624
625         cmsg = CMSG_FIRSTHDR(&msg);
626         cmsg->cmsg_len = msg.msg_controllen;
627         cmsg->cmsg_level = IPPROTO_IPV6;
628         cmsg->cmsg_type = IPV6_PKTINFO;
629
630         pkti = (struct in6_pktinfo*) CMSG_DATA(cmsg);
631
632         if (iface > 0)
633             pkti->ipi6_ifindex = iface;
634
635         if (src_address)
636             memcpy(&pkti->ipi6_addr, src_address->address, sizeof(src_address->address));
637     } else {
638         msg.msg_control = NULL;
639         msg.msg_controllen = 0;
640     }
641
642     return sendmsg_loop(fd, &msg, 0);
643 }
644
645 CattaDnsPacket *catta_recv_dns_packet_ipv4(
646         int fd,
647         CattaIPv4Address *ret_src_address,
648         uint16_t *ret_src_port,
649         CattaIPv4Address *ret_dst_address,
650         CattaIfIndex *ret_iface,
651         uint8_t *ret_ttl) {
652
653     CattaDnsPacket *p= NULL;
654     struct msghdr msg;
655     struct iovec io;
656     size_t aux[1024 / sizeof(size_t)]; /* for alignment on ia64 ! */
657     ssize_t l;
658     struct cmsghdr *cmsg;
659     int found_addr = 0;
660     int ms;
661     struct sockaddr_in sa;
662
663     assert(fd >= 0);
664
665     if (ioctl(fd, FIONREAD, &ms) < 0) {
666         catta_log_warn("ioctl(): %s", errnostrsocket());
667         goto fail;
668     }
669
670     if (ms < 0) {
671         catta_log_warn("FIONREAD returned negative value.");
672         goto fail;
673     }
674
675     p = catta_dns_packet_new(ms + CATTA_DNS_PACKET_EXTRA_SIZE);
676
677     io.iov_base = CATTA_DNS_PACKET_DATA(p);
678     io.iov_len = p->max_size;
679
680     memset(&msg, 0, sizeof(msg));
681     msg.msg_name = &sa;
682     msg.msg_namelen = sizeof(sa);
683     msg.msg_iov = &io;
684     msg.msg_iovlen = 1;
685     msg.msg_control = aux;
686     msg.msg_controllen = sizeof(aux);
687     msg.msg_flags = 0;
688
689     if ((l = recvmsg(fd, &msg, 0)) < 0) {
690         /* Linux returns EAGAIN when an invalid IP packet has been
691         received. We suppress warnings in this case because this might
692         create quite a bit of log traffic on machines with unstable
693         links. (See #60) */
694
695         if (errno != EAGAIN)
696             catta_log_warn("recvmsg(): %s", errnostrsocket());
697
698         goto fail;
699     }
700
701     /* For corrupt packets FIONREAD returns zero size (See rhbz #607297). So
702      * fail after having read them. */
703     if (!ms)
704         goto fail;
705
706     if (sa.sin_addr.s_addr == INADDR_ANY)
707         /* Linux 2.4 behaves very strangely sometimes! */
708         goto fail;
709
710     assert(!(msg.msg_flags & MSG_CTRUNC));
711     assert(!(msg.msg_flags & MSG_TRUNC));
712
713     p->size = (size_t) l;
714
715     if (ret_src_port)
716         *ret_src_port = catta_port_from_sockaddr((struct sockaddr*) &sa);
717
718     if (ret_src_address) {
719         CattaAddress a;
720         catta_address_from_sockaddr((struct sockaddr*) &sa, &a);
721         *ret_src_address = a.data.ipv4;
722     }
723
724     if (ret_ttl)
725         *ret_ttl = 255;
726
727     if (ret_iface)
728         *ret_iface = CATTA_IF_UNSPEC;
729
730     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
731
732         if (cmsg->cmsg_level == IPPROTO_IP) {
733
734             switch (cmsg->cmsg_type) {
735 #ifdef IP_RECVTTL
736                 case IP_RECVTTL:
737 #endif
738                 case IP_TTL:
739                     if (ret_ttl)
740                         *ret_ttl = (uint8_t) (*(int *) CMSG_DATA(cmsg));
741
742                     break;
743
744 #ifdef IP_PKTINFO
745                 case IP_PKTINFO: {
746                     struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg);
747
748                     if (ret_iface && i->ipi_ifindex > 0)
749                         *ret_iface = (int) i->ipi_ifindex;
750
751                     if (ret_dst_address)
752                         ret_dst_address->address = i->ipi_addr.s_addr;
753
754                     found_addr = 1;
755
756                     break;
757                 }
758 #endif
759
760 #ifdef IP_RECVIF
761                 case IP_RECVIF: {
762                     struct sockaddr_dl *sdl = (struct sockaddr_dl *) CMSG_DATA (cmsg);
763
764                     if (ret_iface) {
765 #ifdef __sun
766                         if (*(uint_t*) sdl > 0)
767                             *ret_iface = *(uint_t*) sdl;
768 #else
769
770                         if (sdl->sdl_index > 0)
771                             *ret_iface = (int) sdl->sdl_index;
772 #endif
773                     }
774
775                     break;
776                 }
777 #endif
778
779 #ifdef IP_RECVDSTADDR
780                 case IP_RECVDSTADDR:
781                     if (ret_dst_address)
782                         memcpy(&ret_dst_address->address, CMSG_DATA (cmsg), 4);
783
784                     found_addr = 1;
785                     break;
786 #endif
787
788                 default:
789                     catta_log_warn("Unhandled cmsg_type: %d", cmsg->cmsg_type);
790                     break;
791             }
792         }
793     }
794
795     assert(found_addr);
796
797     return p;
798
799 fail:
800     if (p)
801         catta_dns_packet_free(p);
802
803     return NULL;
804 }
805
806 CattaDnsPacket *catta_recv_dns_packet_ipv6(
807         int fd,
808         CattaIPv6Address *ret_src_address,
809         uint16_t *ret_src_port,
810         CattaIPv6Address *ret_dst_address,
811         CattaIfIndex *ret_iface,
812         uint8_t *ret_ttl) {
813
814     CattaDnsPacket *p = NULL;
815     struct msghdr msg;
816     struct iovec io;
817     size_t aux[1024 / sizeof(size_t)];
818     ssize_t l;
819     int ms;
820     struct cmsghdr *cmsg;
821     int found_ttl = 0, found_iface = 0;
822     struct sockaddr_in6 sa;
823
824     assert(fd >= 0);
825
826     if (ioctl(fd, FIONREAD, &ms) < 0) {
827         catta_log_warn("ioctl(): %s", errnostrsocket());
828         goto fail;
829     }
830
831     if (ms < 0) {
832         catta_log_warn("FIONREAD returned negative value.");
833         goto fail;
834     }
835
836     p = catta_dns_packet_new(ms + CATTA_DNS_PACKET_EXTRA_SIZE);
837
838     io.iov_base = CATTA_DNS_PACKET_DATA(p);
839     io.iov_len = p->max_size;
840
841     memset(&msg, 0, sizeof(msg));
842     msg.msg_name = (struct sockaddr*) &sa;
843     msg.msg_namelen = sizeof(sa);
844
845     msg.msg_iov = &io;
846     msg.msg_iovlen = 1;
847     msg.msg_control = aux;
848     msg.msg_controllen = sizeof(aux);
849     msg.msg_flags = 0;
850
851     if ((l = recvmsg(fd, &msg, 0)) < 0) {
852         /* Linux returns EAGAIN when an invalid IP packet has been
853         received. We suppress warnings in this case because this might
854         create quite a bit of log traffic on machines with unstable
855         links. (See #60) */
856
857         if (errno != EAGAIN)
858             catta_log_warn("recvmsg(): %s", errnostrsocket());
859
860         goto fail;
861     }
862
863     /* For corrupt packets FIONREAD returns zero size (See rhbz #607297). So
864      * fail after having read them. */
865     if (!ms)
866         goto fail;
867
868     assert(!(msg.msg_flags & MSG_CTRUNC));
869     assert(!(msg.msg_flags & MSG_TRUNC));
870
871     p->size = (size_t) l;
872
873     if (ret_src_port)
874         *ret_src_port = catta_port_from_sockaddr((struct sockaddr*) &sa);
875
876     if (ret_src_address) {
877         CattaAddress a;
878         catta_address_from_sockaddr((struct sockaddr*) &sa, &a);
879         *ret_src_address = a.data.ipv6;
880     }
881
882     for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
883
884         if (cmsg->cmsg_level == IPPROTO_IPV6) {
885
886             switch (cmsg->cmsg_type) {
887
888                 case IPV6_HOPLIMIT:
889
890                     if (ret_ttl)
891                         *ret_ttl = (uint8_t) (*(int *) CMSG_DATA(cmsg));
892
893                     found_ttl = 1;
894
895                     break;
896
897                 case IPV6_PKTINFO: {
898                     struct in6_pktinfo *i = (struct in6_pktinfo*) CMSG_DATA(cmsg);
899
900                     if (ret_iface && i->ipi6_ifindex > 0)
901                         *ret_iface = i->ipi6_ifindex;
902
903                     if (ret_dst_address)
904                         memcpy(ret_dst_address->address, i->ipi6_addr.s6_addr, 16);
905
906                     found_iface = 1;
907                     break;
908                 }
909
910                 default:
911                     catta_log_warn("Unhandled cmsg_type: %d", cmsg->cmsg_type);
912                     break;
913             }
914         }
915     }
916
917     assert(found_iface);
918     assert(found_ttl);
919
920     return p;
921
922 fail:
923     if (p)
924         catta_dns_packet_free(p);
925
926     return NULL;
927 }
928
929 int catta_open_unicast_socket_ipv4(void) {
930     struct sockaddr_in local;
931     int fd = -1;
932
933     if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
934         catta_log_warn("socket() failed: %s", errnostrsocket());
935         goto fail;
936     }
937
938     memset(&local, 0, sizeof(local));
939     local.sin_family = AF_INET;
940
941     if (bind(fd, (struct sockaddr*) &local, sizeof(local)) < 0) {
942         catta_log_warn("bind() failed: %s", errnostrsocket());
943         goto fail;
944     }
945
946     if (ipv4_pktinfo(fd) < 0) {
947          goto fail;
948     }
949
950     if (catta_set_cloexec(fd) < 0) {
951         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
952         goto fail;
953     }
954
955     if (catta_set_nonblock(fd) < 0) {
956         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
957         goto fail;
958     }
959
960     return fd;
961
962 fail:
963     if (fd >= 0)
964         closesocket(fd);
965
966     return -1;
967 }
968
969 int catta_open_unicast_socket_ipv6(void) {
970     struct sockaddr_in6 local;
971     int fd = -1, yes;
972
973     if ((fd = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
974         catta_log_warn("socket() failed: %s", errnostrsocket());
975         goto fail;
976     }
977
978     yes = 1;
979     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&yes, sizeof(yes)) < 0) {
980         catta_log_warn("IPV6_V6ONLY failed: %s", errnostrsocket());
981         goto fail;
982     }
983
984     memset(&local, 0, sizeof(local));
985     local.sin6_family = AF_INET6;
986
987     if (bind(fd, (struct sockaddr*) &local, sizeof(local)) < 0) {
988         catta_log_warn("bind() failed: %s", errnostrsocket());
989         goto fail;
990     }
991
992     if (ipv6_pktinfo(fd) < 0)
993         goto fail;
994
995     if (catta_set_cloexec(fd) < 0) {
996         catta_log_warn("FD_CLOEXEC failed: %s", errnostrsocket());
997         goto fail;
998     }
999
1000     if (catta_set_nonblock(fd) < 0) {
1001         catta_log_warn("O_NONBLOCK failed: %s", errnostrsocket());
1002         goto fail;
1003     }
1004
1005     return fd;
1006
1007 fail:
1008     if (fd >= 0)
1009         closesocket(fd);
1010
1011     return -1;
1012 }