]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/mDNSPosix.c
mDNSResponder-1096.60.2.tar.gz
[apple/mdnsresponder.git] / mDNSPosix / mDNSPosix.c
1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
2 *
3 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
20 #include "DNSCommon.h"
21 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
22 #include "PlatformCommon.h"
23 #include "dns_sd.h"
24 #include "dnssec.h"
25 #include "nsec.h"
26
27 #include <assert.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <syslog.h>
34 #include <stdarg.h>
35 #include <fcntl.h>
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <sys/socket.h>
39 #include <sys/uio.h>
40 #include <sys/select.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <time.h> // platform support for UTC time
44 #include <ifaddrs.h>
45
46 #if USES_NETLINK
47 #include <asm/types.h>
48 #include <linux/netlink.h>
49 #include <linux/rtnetlink.h>
50 #else // USES_NETLINK
51 #include <net/route.h>
52 #include <net/if.h>
53 #endif // USES_NETLINK
54
55 #include "mDNSUNP.h"
56 #include "GenLinkedList.h"
57 #include "dnsproxy.h"
58
59 // ***************************************************************************
60 // Structures
61
62 // Context record for interface change callback
63 struct IfChangeRec
64 {
65 int NotifySD;
66 mDNS *mDNS;
67 };
68 typedef struct IfChangeRec IfChangeRec;
69
70 // Note that static data is initialized to zero in (modern) C.
71 static PosixEventSource *gEventSources; // linked list of PosixEventSource's
72 static sigset_t gEventSignalSet; // Signals which event loop listens for
73 static sigset_t gEventSignals; // Signals which were received while inside loop
74
75 static PosixNetworkInterface *gRecentInterfaces;
76
77 // ***************************************************************************
78 // Globals (for debugging)
79
80 static int num_registered_interfaces = 0;
81 static int num_pkts_accepted = 0;
82 static int num_pkts_rejected = 0;
83
84 // ***************************************************************************
85 // Locals
86 mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
87 const char *taskName, mDNSPosixEventCallback callback, void *context);
88 mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeSource, mDNSBool removeSource, int flags);
89 mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
90 const char *taskName, mDNSPosixEventCallback callback, void *context);
91 // ***************************************************************************
92 // Functions
93
94 #if MDNS_MALLOC_DEBUGGING
95 mDNSexport void mDNSPlatformValidateLists(void)
96 {
97 // This should validate gEventSources and any other Posix-specific stuff that gets allocated.
98 }
99 #endif
100
101 int gMDNSPlatformPosixVerboseLevel = 0;
102
103 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
104
105 mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
106 {
107 switch (sa->sa_family)
108 {
109 case AF_INET:
110 {
111 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
112 ipAddr->type = mDNSAddrType_IPv4;
113 ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
114 if (ipPort) ipPort->NotAnInteger = sin->sin_port;
115 break;
116 }
117
118 #if HAVE_IPV6
119 case AF_INET6:
120 {
121 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
122 #ifndef NOT_HAVE_SA_LEN
123 assert(sin6->sin6_len == sizeof(*sin6));
124 #endif
125 ipAddr->type = mDNSAddrType_IPv6;
126 ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
127 if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
128 break;
129 }
130 #endif
131
132 default:
133 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
134 ipAddr->type = mDNSAddrType_None;
135 if (ipPort) ipPort->NotAnInteger = 0;
136 break;
137 }
138 }
139
140 #if COMPILER_LIKES_PRAGMA_MARK
141 #pragma mark ***** Send and Receive
142 #endif
143
144 // mDNS core calls this routine when it needs to send a packet.
145 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
146 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
147 mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
148 {
149 int err = 0;
150 struct sockaddr_storage to;
151 PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
152 int sendingsocket = -1;
153
154 (void)src; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
155 (void) useBackgroundTrafficClass;
156
157 assert(m != NULL);
158 assert(msg != NULL);
159 assert(end != NULL);
160 assert((((char *) end) - ((char *) msg)) > 0);
161
162 if (dstPort.NotAnInteger == 0)
163 {
164 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
165 return PosixErrorToStatus(EINVAL);
166 }
167 if (dst->type == mDNSAddrType_IPv4)
168 {
169 struct sockaddr_in *sin = (struct sockaddr_in*)&to;
170 #ifndef NOT_HAVE_SA_LEN
171 sin->sin_len = sizeof(*sin);
172 #endif
173 sin->sin_family = AF_INET;
174 sin->sin_port = dstPort.NotAnInteger;
175 sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
176 sendingsocket = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
177 }
178
179 #if HAVE_IPV6
180 else if (dst->type == mDNSAddrType_IPv6)
181 {
182 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
183 mDNSPlatformMemZero(sin6, sizeof(*sin6));
184 #ifndef NOT_HAVE_SA_LEN
185 sin6->sin6_len = sizeof(*sin6);
186 #endif
187 sin6->sin6_family = AF_INET6;
188 sin6->sin6_port = dstPort.NotAnInteger;
189 sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
190 sendingsocket = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
191 }
192 #endif
193
194 if (sendingsocket >= 0)
195 err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
196
197 if (err > 0) err = 0;
198 else if (err < 0)
199 {
200 static int MessageCount = 0;
201 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
202 if (!mDNSAddressIsAllDNSLinkGroup(dst))
203 if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
204
205 if (MessageCount < 1000)
206 {
207 MessageCount++;
208 if (thisIntf)
209 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
210 errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
211 else
212 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
213 }
214 }
215
216 return PosixErrorToStatus(err);
217 }
218
219 mDNSlocal void TCPReadCallback(int fd, void *context)
220 {
221 TCPSocket *sock = context;
222 (void)fd;
223
224 if (sock->flags & kTCPSocketFlags_UseTLS)
225 {
226 // implement
227 }
228 else
229 {
230 sock->callback(sock, sock->context, mDNSfalse, sock->err);
231 }
232 }
233
234 mDNSlocal void tcpConnectCallback(int fd, void *context)
235 {
236 TCPSocket *sock = context;
237 mDNSBool c = !sock->connected;
238 int result;
239 socklen_t len = sizeof result;
240
241 sock->connected = mDNStrue;
242
243 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &len) < 0)
244 {
245 LogInfo("ERROR: TCPConnectCallback - unable to get connect error: socket %d: Error %d (%s)",
246 sock->events.fd, result, strerror(result));
247 sock->err = mStatus_ConnFailed;
248 }
249 else
250 {
251 if (result != 0)
252 {
253 sock->err = mStatus_ConnFailed;
254 if (result == EHOSTUNREACH || result == EADDRNOTAVAIL || result == ENETDOWN)
255 {
256 LogInfo("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
257 sock->events.fd, result, strerror(result));
258 }
259 else
260 {
261 LogMsg("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
262 sock->events.fd, result, strerror(result));
263 }
264 }
265 else
266 {
267 // The connection succeeded.
268 sock->connected = mDNStrue;
269 // Select for read events.
270 sock->events.fd = fd;
271 requestReadEvents(&sock->events, "mDNSPosix::tcpConnectCallback", TCPReadCallback, sock);
272 }
273 }
274
275 if (sock->callback)
276 {
277 sock->callback(sock, sock->context, c, sock->err);
278 // Here sock must be assumed to be invalid, in case the callback freed it.
279 return;
280 }
281 }
282
283 // This routine is called when the main loop detects that data is available on a socket.
284 mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
285 {
286 mDNSAddr senderAddr, destAddr;
287 mDNSIPPort senderPort;
288 ssize_t packetLen;
289 DNSMessage packet;
290 struct my_in_pktinfo packetInfo;
291 struct sockaddr_storage from;
292 socklen_t fromLen;
293 int flags;
294 mDNSu8 ttl;
295 mDNSBool reject;
296 const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
297
298 assert(m != NULL);
299 assert(skt >= 0);
300
301 fromLen = sizeof(from);
302 flags = 0;
303 packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
304
305 if (packetLen >= 0)
306 {
307 SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
308 SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
309
310 // If we have broken IP_RECVDSTADDR functionality (so far
311 // I've only seen this on OpenBSD) then apply a hack to
312 // convince mDNS Core that this isn't a spoof packet.
313 // Basically what we do is check to see whether the
314 // packet arrived as a multicast and, if so, set its
315 // destAddr to the mDNS address.
316 //
317 // I must admit that I could just be doing something
318 // wrong on OpenBSD and hence triggering this problem
319 // but I'm at a loss as to how.
320 //
321 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
322 // no way to tell the destination address or interface this packet arrived on,
323 // so all we can do is just assume it's a multicast
324
325 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
326 if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
327 {
328 destAddr.type = senderAddr.type;
329 if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
330 else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
331 }
332 #endif
333
334 // We only accept the packet if the interface on which it came
335 // in matches the interface associated with this socket.
336 // We do this match by name or by index, depending on which
337 // information is available. recvfrom_flags sets the name
338 // to "" if the name isn't available, or the index to -1
339 // if the index is available. This accomodates the various
340 // different capabilities of our target platforms.
341
342 reject = mDNSfalse;
343 if (!intf)
344 {
345 // Ignore multicasts accidentally delivered to our unicast receiving socket
346 if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
347 }
348 else
349 {
350 if (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
351 else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
352
353 if (reject)
354 {
355 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
356 &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
357 &intf->coreIntf.ip, intf->intfName, intf->index, skt);
358 packetLen = -1;
359 num_pkts_rejected++;
360 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
361 {
362 fprintf(stderr,
363 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
364 num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
365 num_pkts_accepted = 0;
366 num_pkts_rejected = 0;
367 }
368 }
369 else
370 {
371 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
372 &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
373 num_pkts_accepted++;
374 }
375 }
376 }
377
378 if (packetLen >= 0)
379 mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
380 &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
381 }
382
383 mDNSexport TCPSocket *mDNSPlatformTCPSocket(TCPSocketFlags flags, mDNSAddr_Type addrType, mDNSIPPort * port,
384 domainname *hostname, mDNSBool useBackgroundTrafficClass)
385 {
386 TCPSocket *sock;
387 int len = sizeof (TCPSocket);
388
389 (void)useBackgroundTrafficClass;
390
391 if (hostname)
392 {
393 len += sizeof (domainname);
394 }
395 sock = malloc(len);
396
397 if (sock == NULL)
398 {
399 LogMsg("mDNSPlatformTCPSocket: no memory for socket");
400 return NULL;
401 }
402 memset(sock, 0, sizeof *sock);
403
404 if (hostname)
405 {
406 sock->hostname = (domainname *)(sock + 1);
407 LogMsg("mDNSPlatformTCPSocket: hostname %##s", hostname->c);
408 AssignDomainName(sock->hostname, hostname);
409 }
410
411 sock->events.fd = -1;
412 if (!mDNSPosixTCPSocketSetup(&sock->events.fd, addrType, port, &sock->port))
413 {
414 if (sock->events.fd != -1) close(sock->events.fd);
415 free(sock);
416 return mDNSNULL;
417 }
418
419 // Set up the other fields in the structure.
420 sock->flags = flags;
421 sock->err = mStatus_NoError;
422 sock->setup = mDNSfalse;
423 sock->connected = mDNSfalse;
424 return sock;
425 }
426
427 mDNSexport mStatus mDNSPlatformTCPSocketSetCallback(TCPSocket *sock, TCPConnectionCallback callback, void *context)
428 {
429 sock->callback = callback;
430 sock->context = context;
431 return mStatus_NoError;
432 }
433
434 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int fd)
435 {
436 TCPSocket *sock;
437
438 // XXX Add!
439 if (flags & kTCPSocketFlags_UseTLS)
440 {
441 return mDNSNULL; // not supported yet.
442 }
443
444 sock = (TCPSocket *) mDNSPlatformMemAllocateClear(sizeof *sock);
445 if (!sock)
446 {
447 return mDNSNULL;
448 }
449
450 sock->events.fd = fd;
451 sock->flags = flags;
452 sock->connected = mDNStrue;
453 return sock;
454 }
455
456
457 mDNSlocal void tcpListenCallback(int fd, void *context)
458 {
459 TCPListener *listener = context;
460 TCPSocket *sock;
461
462 sock = mDNSPosixDoTCPListenCallback(fd, listener->addressType, listener->socketFlags,
463 listener->callback, listener->context);
464 if (sock != NULL)
465 {
466 requestReadEvents(&sock->events, "mDNSPosix::tcpListenCallback", TCPReadCallback, sock);
467 }
468 }
469
470 mDNSexport TCPListener *mDNSPlatformTCPListen(mDNSAddr_Type addrType, mDNSIPPort *port, mDNSAddr *addr,
471 TCPSocketFlags socketFlags, mDNSBool reuseAddr, int queueLength,
472 TCPAcceptedCallback callback, void *context)
473 {
474 TCPListener *ret;
475 int fd = -1;
476
477 if (!mDNSPosixTCPListen(&fd, addrType, port, addr, reuseAddr, queueLength))
478 {
479 if (fd != -1)
480 {
481 close(fd);
482 }
483 return mDNSNULL;
484 }
485
486 // Allocate a listener structure
487 ret = (TCPListener *) mDNSPlatformMemAllocateClear(sizeof *ret);
488 if (ret == NULL)
489 {
490 LogMsg("mDNSPlatformTCPListen: no memory for TCPListener struct.");
491 close(fd);
492 return mDNSNULL;
493 }
494 ret->events.fd = fd;
495 ret->callback = callback;
496 ret->context = context;
497 ret->addressType = addrType;
498 ret->socketFlags = socketFlags;
499
500 // When we get a connection, mDNSPosixListenCallback will be called, and it will invoke the
501 // callback we were passed.
502 requestReadEvents(&ret->events, "tcpListenCallback", tcpListenCallback, ret);
503 return ret;
504 }
505
506 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
507 {
508 return sock->events.fd;
509 }
510
511 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport,
512 mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context)
513 {
514 int result;
515 union {
516 struct sockaddr sa;
517 struct sockaddr_in sin;
518 struct sockaddr_in6 sin6;
519 } addr;
520 socklen_t len;
521
522 sock->callback = callback;
523 sock->context = context;
524 sock->setup = mDNSfalse;
525 sock->connected = mDNSfalse;
526 sock->err = mStatus_NoError;
527
528 result = fcntl(sock->events.fd, F_GETFL, 0);
529 if (result < 0)
530 {
531 LogMsg("mDNSPlatformTCPConnect: F_GETFL failed: %s", strerror(errno));
532 return mStatus_UnknownErr;
533 }
534
535 result = fcntl(sock->events.fd, F_SETFL, result | O_NONBLOCK);
536 if (result < 0)
537 {
538 LogMsg("mDNSPlatformTCPConnect: F_SETFL failed: %s", strerror(errno));
539 return mStatus_UnknownErr;
540 }
541
542 // If we've been asked to bind to a single interface, do it. See comment in mDNSMacOSX.c for more info.
543 if (InterfaceID)
544 {
545 PosixNetworkInterface *iface = (PosixNetworkInterface *)InterfaceID;
546 #if defined(SO_BINDTODEVICE)
547 result = setsockopt(sock->events.fd,
548 SOL_SOCKET, SO_BINDTODEVICE, iface->intfName, strlen(iface->intfName));
549 if (result < 0)
550 {
551 LogMsg("mDNSPlatformTCPConnect: SO_BINDTODEVICE failed on %s: %s", iface->intfName, strerror(errno));
552 return mStatus_BadParamErr;
553 }
554 #else
555 if (dst->type == mDNSAddrType_IPv4)
556 {
557 #if defined(IP_BOUND_IF)
558 result = setsockopt(sock->events.fd, IPPROTO_IP, IP_BOUND_IF, &iface->index, sizeof iface->index);
559 if (result < 0)
560 {
561 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
562 iface->intfName, iface->index, strerror(errno));
563 return mStatus_BadParamErr;
564 }
565 #else
566 (void)iface;
567 #endif // IP_BOUND_IF
568 }
569 else
570 { // IPv6
571 #if defined(IPV6_BOUND_IF)
572 result = setsockopt(sock->events.fd, IPPROTO_IPV6, IPV6_BOUND_IF, &iface->index, sizeof iface->index);
573 if (result < 0)
574 {
575 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
576 iface->intfName, iface->index, strerror(errno));
577 return mStatus_BadParamErr;
578 }
579 #else
580 (void)iface;
581 #endif // IPV6_BOUND_IF
582 }
583 #endif // SO_BINDTODEVICE
584 }
585
586 memset(&addr, 0, sizeof addr);
587 if (dst->type == mDNSAddrType_IPv4)
588 {
589 addr.sa.sa_family = AF_INET;
590 addr.sin.sin_port = dstport.NotAnInteger;
591 len = sizeof (struct sockaddr_in);
592 addr.sin.sin_addr.s_addr = dst->ip.v4.NotAnInteger;
593 }
594 else
595 {
596 addr.sa.sa_family = AF_INET6;
597 len = sizeof (struct sockaddr_in6);
598 addr.sin6.sin6_port = dstport.NotAnInteger;
599 memcpy(&addr.sin6.sin6_addr.s6_addr, &dst->ip.v6, sizeof addr.sin6.sin6_addr.s6_addr);
600 }
601 #ifndef NOT_HAVE_SA_LEN
602 addr.sa.sa_len = len;
603 #endif
604
605 result = connect(sock->events.fd, (struct sockaddr *)&addr, len);
606 if (result < 0)
607 {
608 if (errno == EINPROGRESS)
609 {
610 requestWriteEvents(&sock->events, "mDNSPlatformConnect", tcpConnectCallback, sock);
611 return mStatus_ConnPending;
612 }
613 if (errno == EHOSTUNREACH || errno == EADDRNOTAVAIL || errno == ENETDOWN)
614 {
615 LogInfo("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s)",
616 sock->events.fd, errno, strerror(errno));
617 }
618 else
619 {
620 LogMsg("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s) length %d",
621 sock->events.fd, errno, strerror(errno), len);
622 }
623 return mStatus_ConnFailed;
624 }
625
626 LogMsg("NOTE: mDNSPlatformTCPConnect completed synchronously");
627 return mStatus_NoError;
628 }
629
630 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
631 {
632 if (sock)
633 { // can sock really be NULL when this is called?
634 shutdown(sock->events.fd, SHUT_RDWR);
635 stopReadOrWriteEvents(sock->events.fd, mDNSfalse, mDNStrue,
636 PosixEventFlag_Read | PosixEventFlag_Write);
637 close(sock->events.fd);
638 free(sock);
639 }
640 }
641
642 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
643 {
644 ssize_t nread;
645
646 *closed = mDNSfalse;
647 if (sock->flags & kTCPSocketFlags_UseTLS)
648 {
649 // Implement...
650 nread = -1;
651 *closed = mDNStrue;
652 } else {
653 nread = mDNSPosixReadTCP(sock->events.fd, buf, buflen, closed);
654 }
655 return nread;
656 }
657
658 mDNSexport mDNSBool mDNSPlatformTCPWritable(TCPSocket *sock)
659 {
660 fd_set w;
661 int nfds = sock->events.fd + 1;
662 int count;
663 struct timeval tv;
664
665 if (nfds > FD_SETSIZE)
666 {
667 LogMsg("ERROR: mDNSPlatformTCPWritable called on an fd that won't fit in an fd_set.");
668 return mDNStrue; // hope for the best?
669 }
670 FD_SET(sock->events.fd, &w);
671 tv.tv_sec = tv.tv_usec = 0;
672 count = select(nfds, NULL, &w, NULL, &tv);
673 if (count > 0)
674 {
675 return mDNStrue;
676 }
677 return mDNSfalse;
678 }
679
680 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
681 {
682 if (sock->flags & kTCPSocketFlags_UseTLS)
683 {
684 // implement
685 return -1;
686 }
687 else
688 {
689 return mDNSPosixWriteTCP(sock->events.fd, msg, len);
690 }
691 }
692
693 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNSIPPort port)
694 {
695 (void)port; // Unused
696 return NULL;
697 }
698
699 mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
700 {
701 (void)sock; // Unused
702 }
703
704 mDNSexport void mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID)
705 {
706 (void)InterfaceID; // Unused
707 }
708
709 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
710 {
711 (void)msg; // Unused
712 (void)end; // Unused
713 (void)InterfaceID; // Unused
714 }
715
716 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
717 {
718 (void)tpa; // Unused
719 (void)tha; // Unused
720 (void)InterfaceID; // Unused
721 }
722
723 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
724 {
725 return(mStatus_UnsupportedErr);
726 }
727
728 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
729 {
730 }
731
732 mDNSexport void mDNSPlatformSetAllowSleep(mDNSBool allowSleep, const char *reason)
733 {
734 (void) allowSleep;
735 (void) reason;
736 }
737
738 #if COMPILER_LIKES_PRAGMA_MARK
739 #pragma mark -
740 #pragma mark - /etc/hosts support
741 #endif
742
743 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
744 {
745 (void)m; // unused
746 (void)rr;
747 (void)result;
748 }
749
750
751 #if COMPILER_LIKES_PRAGMA_MARK
752 #pragma mark ***** DDNS Config Platform Functions
753 #endif
754
755 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
756 DNameListElem **BrowseDomains, mDNSBool ackConfig)
757 {
758 (void) setservers;
759 (void) setsearch;
760 (void) ackConfig;
761
762 if (fqdn ) fqdn->c[0] = 0;
763 if (RegDomains ) *RegDomains = NULL;
764 if (BrowseDomains) *BrowseDomains = NULL;
765
766 return mDNStrue;
767 }
768
769 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
770 {
771 (void) v4;
772 (void) v6;
773 (void) router;
774
775 return mStatus_UnsupportedErr;
776 }
777
778 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
779 {
780 (void) dname;
781 (void) status;
782 }
783
784 #if COMPILER_LIKES_PRAGMA_MARK
785 #pragma mark ***** Init and Term
786 #endif
787
788 // This gets the current hostname, truncating it at the first dot if necessary
789 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
790 {
791 int len = 0;
792 gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
793 while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
794 namelabel->c[0] = len;
795 }
796
797 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
798 // Other platforms can either get the information from the appropriate place,
799 // or they can alternatively just require all registering services to provide an explicit name
800 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
801 {
802 // On Unix we have no better name than the host name, so we just use that.
803 GetUserSpecifiedRFC1034ComputerName(namelabel);
804 }
805
806 mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
807 {
808 char line[256];
809 char nameserver[16];
810 char keyword[11];
811 int numOfServers = 0;
812 FILE *fp = fopen(filePath, "r");
813 if (fp == NULL) return -1;
814 while (fgets(line,sizeof(line),fp))
815 {
816 struct in_addr ina;
817 line[255]='\0'; // just to be safe
818 if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue; // it will skip whitespaces
819 if (strncasecmp(keyword,"nameserver",10)) continue;
820 if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
821 {
822 mDNSAddr DNSAddr;
823 DNSAddr.type = mDNSAddrType_IPv4;
824 DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
825 mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, mDNSfalse, mDNSfalse, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
826 numOfServers++;
827 }
828 }
829 fclose(fp);
830 return (numOfServers > 0) ? 0 : -1;
831 }
832
833 // Searches the interface list looking for the named interface.
834 // Returns a pointer to if it found, or NULL otherwise.
835 mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
836 {
837 PosixNetworkInterface *intf;
838
839 assert(m != NULL);
840 assert(intfName != NULL);
841
842 intf = (PosixNetworkInterface*)(m->HostInterfaces);
843 while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
844 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
845
846 return intf;
847 }
848
849 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
850 {
851 PosixNetworkInterface *intf;
852
853 assert(m != NULL);
854
855 if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
856 if (index == kDNSServiceInterfaceIndexP2P ) return(mDNSInterface_P2P);
857 if (index == kDNSServiceInterfaceIndexAny ) return(mDNSInterface_Any);
858
859 intf = (PosixNetworkInterface*)(m->HostInterfaces);
860 while ((intf != NULL) && (mDNSu32) intf->index != index)
861 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
862
863 return (mDNSInterfaceID) intf;
864 }
865
866 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
867 {
868 PosixNetworkInterface *intf;
869 (void) suppressNetworkChange; // Unused
870
871 assert(m != NULL);
872
873 if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
874 if (id == mDNSInterface_P2P ) return(kDNSServiceInterfaceIndexP2P);
875 if (id == mDNSInterface_Any ) return(kDNSServiceInterfaceIndexAny);
876
877 intf = (PosixNetworkInterface*)(m->HostInterfaces);
878 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
879 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
880
881 if (intf) return intf->index;
882
883 // If we didn't find the interface, check the RecentInterfaces list as well
884 intf = gRecentInterfaces;
885 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
886 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
887
888 return intf ? intf->index : 0;
889 }
890
891 // Frees the specified PosixNetworkInterface structure. The underlying
892 // interface must have already been deregistered with the mDNS core.
893 mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
894 {
895 int rv;
896 assert(intf != NULL);
897 if (intf->intfName != NULL) free((void *)intf->intfName);
898 if (intf->multicastSocket4 != -1)
899 {
900 rv = close(intf->multicastSocket4);
901 assert(rv == 0);
902 }
903 #if HAVE_IPV6
904 if (intf->multicastSocket6 != -1)
905 {
906 rv = close(intf->multicastSocket6);
907 assert(rv == 0);
908 }
909 #endif
910
911 // Move interface to the RecentInterfaces list for a minute
912 intf->LastSeen = mDNSPlatformUTC();
913 intf->coreIntf.next = &gRecentInterfaces->coreIntf;
914 gRecentInterfaces = intf;
915 }
916
917 // Grab the first interface, deregister it, free it, and repeat until done.
918 mDNSlocal void ClearInterfaceList(mDNS *const m)
919 {
920 assert(m != NULL);
921
922 while (m->HostInterfaces)
923 {
924 PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
925 mDNS_DeregisterInterface(m, &intf->coreIntf, NormalActivation);
926 if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
927 FreePosixNetworkInterface(intf);
928 }
929 num_registered_interfaces = 0;
930 num_pkts_accepted = 0;
931 num_pkts_rejected = 0;
932 }
933
934 // Sets up a send/receive socket.
935 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
936 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
937 mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
938 {
939 int err = 0;
940 static const int kOn = 1;
941 static const int kIntTwoFiveFive = 255;
942 static const unsigned char kByteTwoFiveFive = 255;
943 const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
944
945 (void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
946 assert(intfAddr != NULL);
947 assert(sktPtr != NULL);
948 assert(*sktPtr == -1);
949
950 // Open the socket...
951 if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
952 #if HAVE_IPV6
953 else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
954 #endif
955 else return EINVAL;
956
957 if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
958
959 // ... with a shared UDP port, if it's for multicast receiving
960 if (err == 0 && port.NotAnInteger)
961 {
962 // <rdar://problem/20946253> Suggestions from Jonny Törnbom at Axis Communications
963 // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
964 // Linux kernel versions 3.9 introduces support for socket option
965 // SO_REUSEPORT, however this is not implemented the same as on *BSD
966 // systems. Linux version implements a "port hijacking" prevention
967 // mechanism, limiting processes wanting to bind to an already existing
968 // addr:port to have the same effective UID as the first who bound it. What
969 // this meant for us was that the daemon ran as one user and when for
970 // instance mDNSClientPosix was executed by another user, it wasn't allowed
971 // to bind to the socket. Our suggestion was to switch the order in which
972 // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
973 // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
974 #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
975 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
976 #elif defined(SO_REUSEPORT)
977 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
978 #else
979 #error This platform has no way to avoid address busy errors on multicast.
980 #endif
981 if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
982
983 #if TARGET_OS_MAC
984 // Enable inbound packets on IFEF_AWDL interface.
985 // Only done for multicast sockets, since we don't expect unicast socket operations
986 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
987 #ifndef SO_RECV_ANYIF
988 #define SO_RECV_ANYIF 0x1104 /* unrestricted inbound processing */
989 #endif
990 if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
991 #endif
992 }
993
994 // We want to receive destination addresses and interface identifiers.
995 if (intfAddr->sa_family == AF_INET)
996 {
997 struct ip_mreq imr;
998 struct sockaddr_in bindAddr;
999 if (err == 0)
1000 {
1001 #if defined(IP_PKTINFO) // Linux
1002 err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
1003 if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
1004 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
1005 #if defined(IP_RECVDSTADDR)
1006 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
1007 if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
1008 #endif
1009 #if defined(IP_RECVIF)
1010 if (err == 0)
1011 {
1012 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
1013 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
1014 }
1015 #endif
1016 #else
1017 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
1018 #endif
1019 }
1020 #if defined(IP_RECVTTL) // Linux
1021 if (err == 0)
1022 {
1023 setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
1024 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
1025 }
1026 #endif
1027
1028 // Add multicast group membership on this interface
1029 if (err == 0 && JoinMulticastGroup)
1030 {
1031 imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
1032 imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
1033 err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
1034 if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
1035 }
1036
1037 // Specify outgoing interface too
1038 if (err == 0 && JoinMulticastGroup)
1039 {
1040 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
1041 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
1042 }
1043
1044 // Per the mDNS spec, send unicast packets with TTL 255
1045 if (err == 0)
1046 {
1047 err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
1048 if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
1049 }
1050
1051 // and multicast packets with TTL 255 too
1052 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
1053 if (err == 0)
1054 {
1055 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
1056 if (err < 0 && errno == EINVAL)
1057 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
1058 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
1059 }
1060
1061 // And start listening for packets
1062 if (err == 0)
1063 {
1064 bindAddr.sin_family = AF_INET;
1065 bindAddr.sin_port = port.NotAnInteger;
1066 bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
1067 err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
1068 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
1069 }
1070 } // endif (intfAddr->sa_family == AF_INET)
1071
1072 #if HAVE_IPV6
1073 else if (intfAddr->sa_family == AF_INET6)
1074 {
1075 struct ipv6_mreq imr6;
1076 struct sockaddr_in6 bindAddr6;
1077 #if defined(IPV6_PKTINFO)
1078 if (err == 0)
1079 {
1080 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
1081 if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
1082 }
1083 #else
1084 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
1085 #endif
1086 #if defined(IPV6_HOPLIMIT)
1087 if (err == 0)
1088 {
1089 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
1090 if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
1091 }
1092 #endif
1093
1094 // Add multicast group membership on this interface
1095 if (err == 0 && JoinMulticastGroup)
1096 {
1097 imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
1098 imr6.ipv6mr_interface = interfaceIndex;
1099 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
1100 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
1101 if (err < 0)
1102 {
1103 err = errno;
1104 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
1105 perror("setsockopt - IPV6_JOIN_GROUP");
1106 }
1107 }
1108
1109 // Specify outgoing interface too
1110 if (err == 0 && JoinMulticastGroup)
1111 {
1112 u_int multicast_if = interfaceIndex;
1113 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
1114 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
1115 }
1116
1117 // We want to receive only IPv6 packets on this socket.
1118 // Without this option, we may get IPv4 addresses as mapped addresses.
1119 if (err == 0)
1120 {
1121 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
1122 if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
1123 }
1124
1125 // Per the mDNS spec, send unicast packets with TTL 255
1126 if (err == 0)
1127 {
1128 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
1129 if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
1130 }
1131
1132 // and multicast packets with TTL 255 too
1133 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
1134 if (err == 0)
1135 {
1136 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
1137 if (err < 0 && errno == EINVAL)
1138 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
1139 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
1140 }
1141
1142 // And start listening for packets
1143 if (err == 0)
1144 {
1145 mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
1146 #ifndef NOT_HAVE_SA_LEN
1147 bindAddr6.sin6_len = sizeof(bindAddr6);
1148 #endif
1149 bindAddr6.sin6_family = AF_INET6;
1150 bindAddr6.sin6_port = port.NotAnInteger;
1151 bindAddr6.sin6_flowinfo = 0;
1152 bindAddr6.sin6_addr = in6addr_any; // Want to receive multicasts AND unicasts on this socket
1153 bindAddr6.sin6_scope_id = 0;
1154 err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
1155 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
1156 }
1157 } // endif (intfAddr->sa_family == AF_INET6)
1158 #endif
1159
1160 // Set the socket to non-blocking.
1161 if (err == 0)
1162 {
1163 err = fcntl(*sktPtr, F_GETFL, 0);
1164 if (err < 0) err = errno;
1165 else
1166 {
1167 err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
1168 if (err < 0) err = errno;
1169 }
1170 }
1171
1172 // Clean up
1173 if (err != 0 && *sktPtr != -1)
1174 {
1175 int rv;
1176 rv = close(*sktPtr);
1177 assert(rv == 0);
1178 *sktPtr = -1;
1179 }
1180 assert((err == 0) == (*sktPtr != -1));
1181 return err;
1182 }
1183
1184 // Creates a PosixNetworkInterface for the interface whose IP address is
1185 // intfAddr and whose name is intfName and registers it with mDNS core.
1186 mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
1187 {
1188 int err = 0;
1189 PosixNetworkInterface *intf;
1190 PosixNetworkInterface *alias = NULL;
1191
1192 assert(m != NULL);
1193 assert(intfAddr != NULL);
1194 assert(intfName != NULL);
1195 assert(intfMask != NULL);
1196
1197 // Allocate the interface structure itself.
1198 intf = (PosixNetworkInterface*)calloc(1, sizeof(*intf));
1199 if (intf == NULL) { assert(0); err = ENOMEM; }
1200
1201 // And make a copy of the intfName.
1202 if (err == 0)
1203 {
1204 #ifdef LINUX
1205 char *s;
1206 int len;
1207 s = strchr(intfName, ':');
1208 if (s != NULL)
1209 {
1210 len = (s - intfName) + 1;
1211 }
1212 else
1213 {
1214 len = strlen(intfName) + 1;
1215 }
1216 intf->intfName = malloc(len);
1217 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
1218 memcpy(intf->intfName, intfName, len - 1);
1219 intfName[len - 1] = 0;
1220 #else
1221 intf->intfName = strdup(intfName);
1222 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
1223 #endif
1224 }
1225
1226 if (err == 0)
1227 {
1228 // Set up the fields required by the mDNS core.
1229 SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
1230 SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
1231
1232 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
1233 strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
1234 intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
1235
1236 intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
1237 intf->coreIntf.McastTxRx = mDNStrue;
1238
1239 // Set up the extra fields in PosixNetworkInterface.
1240 assert(intf->intfName != NULL); // intf->intfName already set up above
1241 intf->index = intfIndex;
1242 intf->multicastSocket4 = -1;
1243 #if HAVE_IPV6
1244 intf->multicastSocket6 = -1;
1245 #endif
1246 alias = SearchForInterfaceByName(m, intf->intfName);
1247 if (alias == NULL) alias = intf;
1248 intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
1249
1250 if (alias != intf)
1251 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
1252 }
1253
1254 // Set up the multicast socket
1255 if (err == 0)
1256 {
1257 if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
1258 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
1259 #if HAVE_IPV6
1260 else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
1261 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
1262 #endif
1263 }
1264
1265 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
1266 // and skip the probe phase of the probe/announce packet sequence.
1267 intf->coreIntf.DirectLink = mDNSfalse;
1268 #ifdef DIRECTLINK_INTERFACE_NAME
1269 if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
1270 intf->coreIntf.DirectLink = mDNStrue;
1271 #endif
1272 intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;
1273
1274 // The interface is all ready to go, let's register it with the mDNS core.
1275 if (err == 0)
1276 err = mDNS_RegisterInterface(m, &intf->coreIntf, NormalActivation);
1277
1278 // Clean up.
1279 if (err == 0)
1280 {
1281 num_registered_interfaces++;
1282 debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
1283 if (gMDNSPlatformPosixVerboseLevel > 0)
1284 fprintf(stderr, "Registered interface %s\n", intf->intfName);
1285 }
1286 else
1287 {
1288 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
1289 debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
1290 if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
1291 }
1292
1293 assert((err == 0) == (intf != NULL));
1294
1295 return err;
1296 }
1297
1298 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
1299 mDNSlocal int SetupInterfaceList(mDNS *const m)
1300 {
1301 mDNSBool foundav4 = mDNSfalse;
1302 int err = 0;
1303 struct ifaddrs *intfList;
1304 struct ifaddrs *firstLoopback = NULL;
1305 int firstLoopbackIndex = 0;
1306
1307 assert(m != NULL);
1308 debugf("SetupInterfaceList");
1309
1310 if (getifaddrs(&intfList) < 0)
1311 {
1312 err = errno;
1313 }
1314 if (intfList == NULL) err = ENOENT;
1315
1316 if (err == 0)
1317 {
1318 struct ifaddrs *i = intfList;
1319 while (i)
1320 {
1321 if ( ((i->ifa_addr->sa_family == AF_INET)
1322 #if HAVE_IPV6
1323 || (i->ifa_addr->sa_family == AF_INET6)
1324 #endif
1325 ) && (i->ifa_flags & IFF_UP) && !(i->ifa_flags & IFF_POINTOPOINT))
1326 {
1327 int ifIndex = if_nametoindex(i->ifa_name);
1328 if (ifIndex == 0)
1329 {
1330 continue;
1331 }
1332 if (i->ifa_flags & IFF_LOOPBACK)
1333 {
1334 if (firstLoopback == NULL)
1335 {
1336 firstLoopback = i;
1337 firstLoopbackIndex = ifIndex;
1338 }
1339 }
1340 else
1341 {
1342 if (SetupOneInterface(m, i->ifa_addr, i->ifa_netmask, i->ifa_name, ifIndex) == 0)
1343 {
1344 if (i->ifa_addr->sa_family == AF_INET)
1345 {
1346 foundav4 = mDNStrue;
1347 }
1348 }
1349 }
1350 }
1351 i = i->ifa_next;
1352 }
1353
1354 // If we found no normal interfaces but we did find a loopback interface, register the
1355 // loopback interface. This allows self-discovery if no interfaces are configured.
1356 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
1357 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
1358 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
1359 if (!foundav4 && firstLoopback)
1360 {
1361 (void)SetupOneInterface(m, firstLoopback->ifa_addr, firstLoopback->ifa_netmask, firstLoopback->ifa_name,
1362 firstLoopbackIndex);
1363 }
1364 }
1365
1366 // Clean up.
1367 if (intfList != NULL) freeifaddrs(intfList);
1368
1369 // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
1370 PosixNetworkInterface **ri = &gRecentInterfaces;
1371 const mDNSs32 utc = mDNSPlatformUTC();
1372 while (*ri)
1373 {
1374 PosixNetworkInterface *pi = *ri;
1375 if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
1376 else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
1377 }
1378
1379 return err;
1380 }
1381
1382 #if USES_NETLINK
1383
1384 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1385
1386 // Open a socket that will receive interface change notifications
1387 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1388 {
1389 mStatus err = mStatus_NoError;
1390 struct sockaddr_nl snl;
1391 int sock;
1392 int ret;
1393
1394 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1395 if (sock < 0)
1396 return errno;
1397
1398 // Configure read to be non-blocking because inbound msg size is not known in advance
1399 (void) fcntl(sock, F_SETFL, O_NONBLOCK);
1400
1401 /* Subscribe the socket to Link & IP addr notifications. */
1402 mDNSPlatformMemZero(&snl, sizeof snl);
1403 snl.nl_family = AF_NETLINK;
1404 snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
1405 ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
1406 if (0 == ret)
1407 *pFD = sock;
1408 else
1409 err = errno;
1410
1411 return err;
1412 }
1413
1414 #if MDNS_DEBUGMSGS
1415 mDNSlocal void PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
1416 {
1417 const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1418 const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1419
1420 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
1421 pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
1422 pNLMsg->nlmsg_flags);
1423
1424 if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
1425 {
1426 struct ifinfomsg *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
1427 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
1428 pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
1429
1430 }
1431 else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
1432 {
1433 struct ifaddrmsg *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
1434 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
1435 pIfAddr->ifa_index, pIfAddr->ifa_flags);
1436 }
1437 printf("\n");
1438 }
1439 #endif
1440
1441 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1442 // Read through the messages on sd and if any indicate that any interface records should
1443 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1444 {
1445 ssize_t readCount;
1446 char buff[4096];
1447 struct nlmsghdr *pNLMsg = (struct nlmsghdr*) buff;
1448 mDNSu32 result = 0;
1449
1450 // The structure here is more complex than it really ought to be because,
1451 // unfortunately, there's no good way to size a buffer in advance large
1452 // enough to hold all pending data and so avoid message fragmentation.
1453 // (Note that FIONREAD is not supported on AF_NETLINK.)
1454
1455 readCount = read(sd, buff, sizeof buff);
1456 while (1)
1457 {
1458 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1459 // If not, discard already-processed messages in buffer and read more data.
1460 if (((char*) &pNLMsg[1] > (buff + readCount)) || // i.e. *pNLMsg extends off end of buffer
1461 ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
1462 {
1463 if (buff < (char*) pNLMsg) // we have space to shuffle
1464 {
1465 // discard processed data
1466 readCount -= ((char*) pNLMsg - buff);
1467 memmove(buff, pNLMsg, readCount);
1468 pNLMsg = (struct nlmsghdr*) buff;
1469
1470 // read more data
1471 readCount += read(sd, buff + readCount, sizeof buff - readCount);
1472 continue; // spin around and revalidate with new readCount
1473 }
1474 else
1475 break; // Otherwise message does not fit in buffer
1476 }
1477
1478 #if MDNS_DEBUGMSGS
1479 PrintNetLinkMsg(pNLMsg);
1480 #endif
1481
1482 // Process the NetLink message
1483 if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
1484 result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
1485 else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
1486 result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
1487
1488 // Advance pNLMsg to the next message in the buffer
1489 if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
1490 {
1491 ssize_t len = readCount - ((char*)pNLMsg - buff);
1492 pNLMsg = NLMSG_NEXT(pNLMsg, len);
1493 }
1494 else
1495 break; // all done!
1496 }
1497
1498 return result;
1499 }
1500
1501 #else // USES_NETLINK
1502
1503 // Open a socket that will receive interface change notifications
1504 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1505 {
1506 *pFD = socket(AF_ROUTE, SOCK_RAW, 0);
1507
1508 if (*pFD < 0)
1509 return mStatus_UnknownErr;
1510
1511 // Configure read to be non-blocking because inbound msg size is not known in advance
1512 (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
1513
1514 return mStatus_NoError;
1515 }
1516
1517 #if MDNS_DEBUGMSGS
1518 mDNSlocal void PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
1519 {
1520 const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1521 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1522 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1523
1524 int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
1525
1526 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
1527 }
1528 #endif
1529
1530 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1531 // Read through the messages on sd and if any indicate that any interface records should
1532 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1533 {
1534 ssize_t readCount;
1535 char buff[4096];
1536 struct ifa_msghdr *pRSMsg = (struct ifa_msghdr*) buff;
1537 mDNSu32 result = 0;
1538
1539 readCount = read(sd, buff, sizeof buff);
1540 if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
1541 return mStatus_UnsupportedErr; // cannot decipher message
1542
1543 #if MDNS_DEBUGMSGS
1544 PrintRoutingSocketMsg(pRSMsg);
1545 #endif
1546
1547 // Process the message
1548 if (pRSMsg->ifam_type == RTM_NEWADDR || pRSMsg->ifam_type == RTM_DELADDR ||
1549 pRSMsg->ifam_type == RTM_IFINFO)
1550 {
1551 if (pRSMsg->ifam_type == RTM_IFINFO)
1552 result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
1553 else
1554 result |= 1 << pRSMsg->ifam_index;
1555 }
1556
1557 return result;
1558 }
1559
1560 #endif // USES_NETLINK
1561
1562 // Called when data appears on interface change notification socket
1563 mDNSlocal void InterfaceChangeCallback(int fd, void *context)
1564 {
1565 IfChangeRec *pChgRec = (IfChangeRec*) context;
1566 fd_set readFDs;
1567 mDNSu32 changedInterfaces = 0;
1568 struct timeval zeroTimeout = { 0, 0 };
1569
1570 (void)fd; // Unused
1571
1572 FD_ZERO(&readFDs);
1573 FD_SET(pChgRec->NotifySD, &readFDs);
1574
1575 do
1576 {
1577 changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
1578 }
1579 while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
1580
1581 // Currently we rebuild the entire interface list whenever any interface change is
1582 // detected. If this ever proves to be a performance issue in a multi-homed
1583 // configuration, more care should be paid to changedInterfaces.
1584 if (changedInterfaces)
1585 mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
1586 }
1587
1588 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1589 mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
1590 {
1591 mStatus err;
1592 IfChangeRec *pChgRec;
1593
1594 pChgRec = (IfChangeRec*) mDNSPlatformMemAllocateClear(sizeof *pChgRec);
1595 if (pChgRec == NULL)
1596 return mStatus_NoMemoryErr;
1597
1598 pChgRec->mDNS = m;
1599 err = OpenIfNotifySocket(&pChgRec->NotifySD);
1600 if (err == 0)
1601 err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
1602 if (err)
1603 mDNSPlatformMemFree(pChgRec);
1604
1605 return err;
1606 }
1607
1608 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1609 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1610 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1611 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
1612 {
1613 int err;
1614 int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1615 struct sockaddr_in s5353;
1616 s5353.sin_family = AF_INET;
1617 s5353.sin_port = MulticastDNSPort.NotAnInteger;
1618 s5353.sin_addr.s_addr = 0;
1619 err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
1620 close(s);
1621 if (err) debugf("No unicast UDP responses");
1622 else debugf("Unicast UDP responses okay");
1623 return(err == 0);
1624 }
1625
1626 // mDNS core calls this routine to initialise the platform-specific data.
1627 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
1628 {
1629 int err = 0;
1630 struct sockaddr sa;
1631 assert(m != NULL);
1632
1633 if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
1634
1635 // Tell mDNS core the names of this machine.
1636
1637 // Set up the nice label
1638 m->nicelabel.c[0] = 0;
1639 GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
1640 if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
1641
1642 // Set up the RFC 1034-compliant label
1643 m->hostlabel.c[0] = 0;
1644 GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
1645 if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
1646
1647 mDNS_SetFQDN(m);
1648
1649 sa.sa_family = AF_INET;
1650 m->p->unicastSocket4 = -1;
1651 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
1652 #if HAVE_IPV6
1653 sa.sa_family = AF_INET6;
1654 m->p->unicastSocket6 = -1;
1655 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
1656 #endif
1657
1658 // Tell mDNS core about the network interfaces on this machine.
1659 if (err == mStatus_NoError) err = SetupInterfaceList(m);
1660
1661 // Tell mDNS core about DNS Servers
1662 mDNS_Lock(m);
1663 if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
1664 mDNS_Unlock(m);
1665
1666 if (err == mStatus_NoError)
1667 {
1668 err = WatchForInterfaceChange(m);
1669 // Failure to observe interface changes is non-fatal.
1670 if (err != mStatus_NoError)
1671 {
1672 fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
1673 err = mStatus_NoError;
1674 }
1675 }
1676
1677 // We don't do asynchronous initialization on the Posix platform, so by the time
1678 // we get here the setup will already have succeeded or failed. If it succeeded,
1679 // we should just call mDNSCoreInitComplete() immediately.
1680 if (err == mStatus_NoError)
1681 mDNSCoreInitComplete(m, mStatus_NoError);
1682
1683 return PosixErrorToStatus(err);
1684 }
1685
1686 // mDNS core calls this routine to clean up the platform-specific data.
1687 // In our case all we need to do is to tear down every network interface.
1688 mDNSexport void mDNSPlatformClose(mDNS *const m)
1689 {
1690 int rv;
1691 assert(m != NULL);
1692 ClearInterfaceList(m);
1693 if (m->p->unicastSocket4 != -1)
1694 {
1695 rv = close(m->p->unicastSocket4);
1696 assert(rv == 0);
1697 }
1698 #if HAVE_IPV6
1699 if (m->p->unicastSocket6 != -1)
1700 {
1701 rv = close(m->p->unicastSocket6);
1702 assert(rv == 0);
1703 }
1704 #endif
1705 }
1706
1707 // This is used internally by InterfaceChangeCallback.
1708 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1709 // can call it in response to a SIGHUP (mainly for debugging purposes).
1710 mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
1711 {
1712 int err;
1713 // This is a pretty heavyweight way to process interface changes --
1714 // destroying the entire interface list and then making fresh one from scratch.
1715 // We should make it like the OS X version, which leaves unchanged interfaces alone.
1716 ClearInterfaceList(m);
1717 err = SetupInterfaceList(m);
1718 return PosixErrorToStatus(err);
1719 }
1720
1721 #if COMPILER_LIKES_PRAGMA_MARK
1722 #pragma mark ***** Locking
1723 #endif
1724
1725 // On the Posix platform, locking is a no-op because we only ever enter
1726 // mDNS core on the main thread.
1727
1728 // mDNS core calls this routine when it wants to prevent
1729 // the platform from reentering mDNS core code.
1730 mDNSexport void mDNSPlatformLock (const mDNS *const m)
1731 {
1732 (void) m; // Unused
1733 }
1734
1735 // mDNS core calls this routine when it release the lock taken by
1736 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1737 mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
1738 {
1739 (void) m; // Unused
1740 }
1741
1742 #if COMPILER_LIKES_PRAGMA_MARK
1743 #pragma mark ***** Strings
1744 #endif
1745
1746 mDNSexport mDNSu32 mDNSPlatformStrLCopy(void *dst, const void *src, mDNSu32 len)
1747 {
1748 #if HAVE_STRLCPY
1749 return ((mDNSu32)strlcpy((char *)dst, (const char *)src, len));
1750 #else
1751 size_t srcLen;
1752
1753 srcLen = strlen((const char *)src);
1754 if (srcLen < len)
1755 {
1756 memcpy(dst, src, srcLen + 1);
1757 }
1758 else if (len > 0)
1759 {
1760 memcpy(dst, src, len - 1);
1761 ((char *)dst)[len - 1] = '\0';
1762 }
1763
1764 return ((mDNSu32)srcLen);
1765 #endif
1766 }
1767
1768 // mDNS core calls this routine to get the length of a C string.
1769 // On the Posix platform this maps directly to the ANSI C strlen.
1770 mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
1771 {
1772 return strlen((const char*)src);
1773 }
1774
1775 // mDNS core calls this routine to copy memory.
1776 // On the Posix platform this maps directly to the ANSI C memcpy.
1777 mDNSexport void mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
1778 {
1779 memcpy(dst, src, len);
1780 }
1781
1782 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1783 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1784 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
1785 {
1786 return memcmp(dst, src, len) == 0;
1787 }
1788
1789 // If the caller wants to know the exact return of memcmp, then use this instead
1790 // of mDNSPlatformMemSame
1791 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
1792 {
1793 return (memcmp(dst, src, len));
1794 }
1795
1796 mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
1797 {
1798 return (qsort(base, nel, width, compar));
1799 }
1800
1801 // DNSSEC stub functions
1802 mDNSexport void VerifySignature(mDNS *const m, DNSSECVerifier *dv, DNSQuestion *q)
1803 {
1804 (void)m;
1805 (void)dv;
1806 (void)q;
1807 }
1808
1809 mDNSexport mDNSBool AddNSECSForCacheRecord(mDNS *const m, CacheRecord *crlist, CacheRecord *negcr, mDNSu8 rcode)
1810 {
1811 (void)m;
1812 (void)crlist;
1813 (void)negcr;
1814 (void)rcode;
1815 return mDNSfalse;
1816 }
1817
1818 mDNSexport void BumpDNSSECStats(mDNS *const m, DNSSECStatsAction action, DNSSECStatsType type, mDNSu32 value)
1819 {
1820 (void)m;
1821 (void)action;
1822 (void)type;
1823 (void)value;
1824 }
1825
1826 // Proxy stub functions
1827 mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
1828 {
1829 (void) q;
1830 (void) h;
1831 (void) msg;
1832 (void) ptr;
1833 (void) limit;
1834
1835 return ptr;
1836 }
1837
1838 mDNSexport void DNSProxyInit(mDNSu32 IpIfArr[], mDNSu32 OpIf)
1839 {
1840 (void) IpIfArr;
1841 (void) OpIf;
1842 }
1843
1844 mDNSexport void DNSProxyTerminate(void)
1845 {
1846 }
1847
1848 // mDNS core calls this routine to clear blocks of memory.
1849 // On the Posix platform this is a simple wrapper around ANSI C memset.
1850 mDNSexport void mDNSPlatformMemZero(void *dst, mDNSu32 len)
1851 {
1852 memset(dst, 0, len);
1853 }
1854
1855 #if !MDNS_MALLOC_DEBUGGING
1856 mDNSexport void *mDNSPlatformMemAllocate(mDNSu32 len) { return(mallocL("mDNSPlatformMemAllocate", len)); }
1857 mDNSexport void *mDNSPlatformMemAllocateClear(mDNSu32 len) { return(callocL(name, len)); }
1858 mDNSexport void mDNSPlatformMemFree (void *mem) { freeL("mDNSPlatformMemFree", mem); }
1859 #endif
1860
1861 #if _PLATFORM_HAS_STRONG_PRNG_
1862 mDNSexport mDNSu32 mDNSPlatformRandomNumber(void)
1863 {
1864 return(arc4random());
1865 }
1866 #else
1867 mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
1868 {
1869 struct timeval tv;
1870 gettimeofday(&tv, NULL);
1871 return(tv.tv_usec);
1872 }
1873 #endif
1874
1875 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
1876
1877 mDNSexport mStatus mDNSPlatformTimeInit(void)
1878 {
1879 // No special setup is required on Posix -- we just use gettimeofday();
1880 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1881 // We should find a better way to do this
1882 return(mStatus_NoError);
1883 }
1884
1885 mDNSexport mDNSs32 mDNSPlatformRawTime()
1886 {
1887 struct timespec tm;
1888 int ret = clock_gettime(CLOCK_MONOTONIC, &tm);
1889 assert(ret == 0); // This call will only fail if the number of seconds does not fit in an object of type time_t.
1890
1891 // tm.tv_sec is seconds since some unspecified starting point (it is usually the system start up time)
1892 // tm.tv_nsec is nanoseconds since the start of this second (i.e. values 0 to 999999999)
1893 // We use the lower 22 bits of tm.tv_sec for the top 22 bits of our result
1894 // and we multiply tm.tv_nsec by 2 / 1953125 to get a value in the range 0-1023 to go in the bottom 10 bits.
1895 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1896 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1897
1898 return ((tm.tv_sec << 10) | (tm.tv_nsec * 2 / 1953125));
1899 }
1900
1901 mDNSexport mDNSs32 mDNSPlatformUTC(void)
1902 {
1903 return time(NULL);
1904 }
1905
1906 mDNSexport void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
1907 {
1908 (void) InterfaceID;
1909 (void) EthAddr;
1910 (void) IPAddr;
1911 (void) iteration;
1912 }
1913
1914 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID)
1915 {
1916 (void) rr;
1917 (void) InterfaceID;
1918
1919 return 1;
1920 }
1921
1922 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
1923 {
1924 (void) q;
1925 (void) intf;
1926
1927 return 1;
1928 }
1929
1930 // Used for debugging purposes. For now, just set the buffer to zero
1931 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
1932 {
1933 (void) te;
1934 if (bufsize) buf[0] = 0;
1935 }
1936
1937 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
1938 {
1939 (void) sadd; // Unused
1940 (void) dadd; // Unused
1941 (void) lport; // Unused
1942 (void) rport; // Unused
1943 (void) seq; // Unused
1944 (void) ack; // Unused
1945 (void) win; // Unused
1946 }
1947
1948 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
1949 {
1950 (void) laddr; // Unused
1951 (void) raddr; // Unused
1952 (void) lport; // Unused
1953 (void) rport; // Unused
1954 (void) mti; // Unused
1955
1956 return mStatus_NoError;
1957 }
1958
1959 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNSAddr *raddr)
1960 {
1961 (void) raddr; // Unused
1962
1963 return mStatus_NoError;
1964 }
1965
1966 mDNSexport mStatus mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
1967 {
1968 (void) spsaddr; // Unused
1969 (void) ifname; // Unused
1970
1971 return mStatus_NoError;
1972 }
1973
1974 mDNSexport mStatus mDNSPlatformClearSPSData(void)
1975 {
1976 return mStatus_NoError;
1977 }
1978
1979 mDNSexport mStatus mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length)
1980 {
1981 (void) ifname; // Unused
1982 (void) msg; // Unused
1983 (void) length; // Unused
1984 return mStatus_UnsupportedErr;
1985 }
1986
1987 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
1988 {
1989 (void) sock; // unused
1990
1991 return (mDNSu16)-1;
1992 }
1993
1994 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
1995 {
1996 (void) InterfaceID; // unused
1997
1998 return mDNSfalse;
1999 }
2000
2001 mDNSexport void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q)
2002 {
2003 (void) sock;
2004 (void) transType;
2005 (void) addrType;
2006 (void) q;
2007 }
2008
2009 mDNSexport mDNSs32 mDNSPlatformGetPID()
2010 {
2011 return 0;
2012 }
2013
2014 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
2015 {
2016 if (*nfds < s + 1) *nfds = s + 1;
2017 FD_SET(s, readfds);
2018 }
2019
2020 mDNSexport void mDNSPosixGetFDSetForSelect(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds)
2021 {
2022 int numFDs = *nfds;
2023 PosixEventSource *iSource;
2024
2025 // 2. Build our list of active file descriptors
2026 PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
2027 if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket4);
2028 #if HAVE_IPV6
2029 if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket6);
2030 #endif
2031 while (info)
2032 {
2033 if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket4);
2034 #if HAVE_IPV6
2035 if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket6);
2036 #endif
2037 info = (PosixNetworkInterface *)(info->coreIntf.next);
2038 }
2039
2040 // Copy over the event fds. We have to do it this way because client-provided event loops expect
2041 // to initialize their FD sets first and then call mDNSPosixGetFDSet()
2042 for (iSource = gEventSources; iSource; iSource = iSource->next)
2043 {
2044 if (iSource->readCallback != NULL)
2045 FD_SET(iSource->fd, readfds);
2046 if (iSource->writeCallback != NULL)
2047 FD_SET(iSource->fd, writefds);
2048 if (numFDs <= iSource->fd)
2049 numFDs = iSource->fd + 1;
2050 }
2051 *nfds = numFDs;
2052 }
2053
2054 mDNSexport void mDNSPosixGetNextDNSEventTime(mDNS *m, struct timeval *timeout)
2055 {
2056 mDNSs32 ticks;
2057 struct timeval interval;
2058
2059 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
2060 mDNSs32 nextevent = mDNS_Execute(m);
2061
2062 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
2063 ticks = nextevent - mDNS_TimeNow(m);
2064 if (ticks < 1) ticks = 1;
2065 interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
2066 interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
2067
2068 // 4. If client's proposed timeout is more than what we want, then reduce it
2069 if (timeout->tv_sec > interval.tv_sec ||
2070 (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
2071 *timeout = interval;
2072 }
2073
2074 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds, struct timeval *timeout)
2075 {
2076 mDNSPosixGetNextDNSEventTime(m, timeout);
2077 mDNSPosixGetFDSetForSelect(m, nfds, readfds, writefds);
2078 }
2079
2080 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds, fd_set *writefds)
2081 {
2082 PosixNetworkInterface *info;
2083 PosixEventSource *iSource;
2084 assert(m != NULL);
2085 assert(readfds != NULL);
2086 info = (PosixNetworkInterface *)(m->HostInterfaces);
2087
2088 if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
2089 {
2090 FD_CLR(m->p->unicastSocket4, readfds);
2091 SocketDataReady(m, NULL, m->p->unicastSocket4);
2092 }
2093 #if HAVE_IPV6
2094 if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
2095 {
2096 FD_CLR(m->p->unicastSocket6, readfds);
2097 SocketDataReady(m, NULL, m->p->unicastSocket6);
2098 }
2099 #endif
2100
2101 while (info)
2102 {
2103 if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
2104 {
2105 FD_CLR(info->multicastSocket4, readfds);
2106 SocketDataReady(m, info, info->multicastSocket4);
2107 }
2108 #if HAVE_IPV6
2109 if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
2110 {
2111 FD_CLR(info->multicastSocket6, readfds);
2112 SocketDataReady(m, info, info->multicastSocket6);
2113 }
2114 #endif
2115 info = (PosixNetworkInterface *)(info->coreIntf.next);
2116 }
2117
2118 // Now process routing socket events, discovery relay events and anything else of that ilk.
2119 for (iSource = gEventSources; iSource; iSource = iSource->next)
2120 {
2121 if (iSource->readCallback != NULL && FD_ISSET(iSource->fd, readfds))
2122 {
2123 iSource->readCallback(iSource->fd, iSource->readContext);
2124 break; // in case callback removed elements from gEventSources
2125 }
2126 else if (iSource->writeCallback != NULL && FD_ISSET(iSource->fd, writefds))
2127 {
2128 mDNSPosixEventCallback writeCallback = iSource->writeCallback;
2129 // Write events are one-shot: to get another event, the consumer has to put in a new request.
2130 // We reset this before calling the callback just in case the callback requests another write
2131 // callback, or deletes the event context from the list.
2132 iSource->writeCallback = NULL;
2133 writeCallback(iSource->fd, iSource->writeContext);
2134 break; // in case callback removed elements from gEventSources
2135 }
2136 }
2137 }
2138
2139 mDNSu32 mDNSPlatformEventContextSize = sizeof (PosixEventSource);
2140
2141 mDNSlocal void requestIOEvents(PosixEventSource *newSource, const char *taskName,
2142 mDNSPosixEventCallback callback, void *context, int flag)
2143 {
2144 PosixEventSource **epp = &gEventSources;
2145
2146 if (newSource->fd >= (int) FD_SETSIZE || newSource->fd < 0)
2147 {
2148 LogMsg("requestIOEvents called with fd %d > FD_SETSIZE %d.", newSource->fd, FD_SETSIZE);
2149 assert(0);
2150 }
2151 if (callback == NULL)
2152 {
2153 LogMsg("requestIOEvents called no callback.", newSource->fd, FD_SETSIZE);
2154 assert(0);
2155 }
2156
2157 // See if this event context is already on the list; if it is, no need to scan the list.
2158 if (!(newSource->flags & PosixEventFlag_OnList))
2159 {
2160 while (*epp)
2161 {
2162 // This should never happen.
2163 if (newSource == *epp)
2164 {
2165 LogMsg("Event context marked not on list but is on list.");
2166 assert(0);
2167 }
2168 epp = &(*epp)->next;
2169 }
2170 if (*epp == NULL)
2171 {
2172 *epp = newSource;
2173 newSource->next = NULL;
2174 newSource->flags = PosixEventFlag_OnList;
2175 }
2176 }
2177
2178 if (flag & PosixEventFlag_Read)
2179 {
2180 newSource->readCallback = callback;
2181 newSource->readContext = context;
2182 newSource->flags |= PosixEventFlag_Read;
2183 newSource->readTaskName = taskName;
2184 }
2185 if (flag & PosixEventFlag_Write)
2186 {
2187 newSource->writeCallback = callback;
2188 newSource->writeContext = context;
2189 newSource->flags |= PosixEventFlag_Write;
2190 newSource->writeTaskName = taskName;
2191 }
2192 }
2193
2194 mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
2195 const char *taskName, mDNSPosixEventCallback callback, void *context)
2196 {
2197 requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Read);
2198 }
2199
2200 mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
2201 const char *taskName, mDNSPosixEventCallback callback, void *context)
2202 {
2203 requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Write);
2204 }
2205
2206 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
2207 mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeContext, mDNSBool removeContext, int flags)
2208 {
2209 PosixEventSource *iSource, **epp = &gEventSources;
2210
2211 while (*epp)
2212 {
2213 iSource = *epp;
2214 if (fd == iSource->fd)
2215 {
2216 if (flags & PosixEventFlag_Read)
2217 {
2218 iSource->readCallback = NULL;
2219 iSource->readContext = NULL;
2220 }
2221 if (flags & PosixEventFlag_Write)
2222 {
2223 iSource->writeCallback = NULL;
2224 iSource->writeContext = NULL;
2225 }
2226 if (iSource->writeCallback == NULL && iSource->readCallback == NULL)
2227 {
2228 if (removeContext || freeContext)
2229 *epp = iSource->next;
2230 if (freeContext)
2231 free(iSource);
2232 }
2233 return mStatus_NoError;
2234 }
2235 epp = &(*epp)->next;
2236 }
2237 return mStatus_NoSuchNameErr;
2238 }
2239
2240 // Some of the mDNSPosix client code relies on being able to add FDs to the event loop without
2241 // providing storage for the event-related info. mDNSPosixAddFDToEventLoop and
2242 // mDNSPosixRemoveFDFromEventLoop handle the event structure storage automatically.
2243 mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
2244 {
2245 PosixEventSource *newSource;
2246
2247 newSource = (PosixEventSource*) malloc(sizeof *newSource);
2248 if (NULL == newSource)
2249 return mStatus_NoMemoryErr;
2250 memset(newSource, 0, sizeof *newSource);
2251 newSource->fd = fd;
2252
2253 requestReadEvents(newSource, "mDNSPosixAddFDToEventLoop", callback, context);
2254 return mStatus_NoError;
2255 }
2256
2257 mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
2258 {
2259 return stopReadOrWriteEvents(fd, mDNStrue, mDNStrue, PosixEventFlag_Read | PosixEventFlag_Write);
2260 }
2261
2262 // Simply note the received signal in gEventSignals.
2263 mDNSlocal void NoteSignal(int signum)
2264 {
2265 sigaddset(&gEventSignals, signum);
2266 }
2267
2268 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
2269 mStatus mDNSPosixListenForSignalInEventLoop(int signum)
2270 {
2271 struct sigaction action;
2272 mStatus err;
2273
2274 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
2275 action.sa_handler = NoteSignal;
2276 err = sigaction(signum, &action, (struct sigaction*) NULL);
2277
2278 sigaddset(&gEventSignalSet, signum);
2279
2280 return err;
2281 }
2282
2283 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
2284 mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
2285 {
2286 struct sigaction action;
2287 mStatus err;
2288
2289 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
2290 action.sa_handler = SIG_DFL;
2291 err = sigaction(signum, &action, (struct sigaction*) NULL);
2292
2293 sigdelset(&gEventSignalSet, signum);
2294
2295 return err;
2296 }
2297
2298 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
2299 // Return as soon as internal timeout expires, or a signal we're listening for is received.
2300 mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
2301 sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
2302 {
2303 fd_set listenFDs;
2304 fd_set writeFDs;
2305 int numFDs = 0, numReady;
2306 struct timeval timeout = *pTimeout;
2307
2308 // 1. Set up the fd_set as usual here.
2309 // This example client has no file descriptors of its own,
2310 // but a real application would call FD_SET to add them to the set here
2311 FD_ZERO(&listenFDs);
2312 FD_ZERO(&writeFDs);
2313
2314 // 2. Set up the timeout.
2315 mDNSPosixGetNextDNSEventTime(m, &timeout);
2316
2317 // Include the sockets that are listening to the wire in our select() set
2318 mDNSPosixGetFDSetForSelect(m, &numFDs, &listenFDs, &writeFDs);
2319 numReady = select(numFDs, &listenFDs, &writeFDs, (fd_set*) NULL, &timeout);
2320
2321 if (numReady > 0)
2322 {
2323 mDNSPosixProcessFDSet(m, &listenFDs, &writeFDs);
2324 *pDataDispatched = mDNStrue;
2325 }
2326 else if (numReady < 0)
2327 {
2328 if (errno != EINTR) {
2329 // This should never happen, represents a coding error, and is not recoverable, since
2330 // we'll just sit here spinning and never receive another event. The usual reason for
2331 // it to happen is that an FD was closed but not removed from the event list.
2332 LogMsg("select failed: %s", strerror(errno));
2333 abort();
2334 }
2335 }
2336 else
2337 *pDataDispatched = mDNSfalse;
2338
2339 (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
2340 *pSignalsReceived = gEventSignals;
2341 sigemptyset(&gEventSignals);
2342 (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
2343
2344 return mStatus_NoError;
2345 }