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