7139 Sync mDNS with mDNSResponder-625.41.2
[unleashed.git] / usr / src / cmd / cmd-inet / usr.lib / mdnsd / mDNSPosix.c
blobf16e82044a9745c5d2acc1f60ded7fa07adc2756
1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
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 "dns_sd.h"
23 #include "dnssec.h"
24 #include "nsec.h"
26 #include <assert.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <syslog.h>
33 #include <stdarg.h>
34 #include <fcntl.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <sys/socket.h>
38 #include <sys/uio.h>
39 #include <sys/select.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <time.h> // platform support for UTC time
44 #if USES_NETLINK
45 #include <asm/types.h>
46 #include <linux/netlink.h>
47 #include <linux/rtnetlink.h>
48 #else // USES_NETLINK
49 #include <net/route.h>
50 #include <net/if.h>
51 #endif // USES_NETLINK
53 #include "mDNSUNP.h"
54 #include "GenLinkedList.h"
56 // ***************************************************************************
57 // Structures
59 // We keep a list of client-supplied event sources in PosixEventSource records
60 struct PosixEventSource
62 mDNSPosixEventCallback Callback;
63 void *Context;
64 int fd;
65 struct PosixEventSource *Next;
67 typedef struct PosixEventSource PosixEventSource;
69 // Context record for interface change callback
70 struct IfChangeRec
72 int NotifySD;
73 mDNS *mDNS;
75 typedef struct IfChangeRec IfChangeRec;
77 // Note that static data is initialized to zero in (modern) C.
78 static fd_set gEventFDs;
79 static int gMaxFD; // largest fd in gEventFDs
80 static GenLinkedList gEventSources; // linked list of PosixEventSource's
81 static sigset_t gEventSignalSet; // Signals which event loop listens for
82 static sigset_t gEventSignals; // Signals which were received while inside loop
84 static PosixNetworkInterface *gRecentInterfaces;
86 // ***************************************************************************
87 // Globals (for debugging)
89 static int num_registered_interfaces = 0;
90 static int num_pkts_accepted = 0;
91 static int num_pkts_rejected = 0;
93 // ***************************************************************************
94 // Functions
96 int gMDNSPlatformPosixVerboseLevel = 0;
98 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
100 mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
102 switch (sa->sa_family)
104 case AF_INET:
106 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
107 ipAddr->type = mDNSAddrType_IPv4;
108 ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
109 if (ipPort) ipPort->NotAnInteger = sin->sin_port;
110 break;
113 #if HAVE_IPV6
114 case AF_INET6:
116 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
117 #ifndef NOT_HAVE_SA_LEN
118 assert(sin6->sin6_len == sizeof(*sin6));
119 #endif
120 ipAddr->type = mDNSAddrType_IPv6;
121 ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
122 if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
123 break;
125 #endif
127 default:
128 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
129 ipAddr->type = mDNSAddrType_None;
130 if (ipPort) ipPort->NotAnInteger = 0;
131 break;
135 #if COMPILER_LIKES_PRAGMA_MARK
136 #pragma mark ***** Send and Receive
137 #endif
139 // mDNS core calls this routine when it needs to send a packet.
140 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
141 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
142 mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
144 int err = 0;
145 struct sockaddr_storage to;
146 PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
147 int sendingsocket = -1;
149 (void)src; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
150 (void) useBackgroundTrafficClass;
152 assert(m != NULL);
153 assert(msg != NULL);
154 assert(end != NULL);
155 assert((((char *) end) - ((char *) msg)) > 0);
157 if (dstPort.NotAnInteger == 0)
159 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
160 return PosixErrorToStatus(EINVAL);
162 if (dst->type == mDNSAddrType_IPv4)
164 struct sockaddr_in *sin = (struct sockaddr_in*)&to;
165 #ifndef NOT_HAVE_SA_LEN
166 sin->sin_len = sizeof(*sin);
167 #endif
168 sin->sin_family = AF_INET;
169 sin->sin_port = dstPort.NotAnInteger;
170 sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
171 sendingsocket = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
174 #if HAVE_IPV6
175 else if (dst->type == mDNSAddrType_IPv6)
177 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
178 mDNSPlatformMemZero(sin6, sizeof(*sin6));
179 #ifndef NOT_HAVE_SA_LEN
180 sin6->sin6_len = sizeof(*sin6);
181 #endif
182 sin6->sin6_family = AF_INET6;
183 sin6->sin6_port = dstPort.NotAnInteger;
184 sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
185 sendingsocket = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
187 #endif
189 if (sendingsocket >= 0)
190 err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
192 if (err > 0) err = 0;
193 else if (err < 0)
195 static int MessageCount = 0;
196 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
197 if (!mDNSAddressIsAllDNSLinkGroup(dst))
198 if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
200 /* dont report ENETUNREACH */
201 if (errno == ENETUNREACH) return(mStatus_TransientErr);
203 if (MessageCount < 1000)
205 MessageCount++;
206 if (thisIntf)
207 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
208 errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
209 else
210 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
214 return PosixErrorToStatus(err);
217 // This routine is called when the main loop detects that data is available on a socket.
218 mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
220 mDNSAddr senderAddr, destAddr;
221 mDNSIPPort senderPort;
222 ssize_t packetLen;
223 DNSMessage packet;
224 struct my_in_pktinfo packetInfo;
225 struct sockaddr_storage from;
226 socklen_t fromLen;
227 int flags;
228 mDNSu8 ttl;
229 mDNSBool reject;
230 const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
232 assert(m != NULL);
233 assert(skt >= 0);
235 fromLen = sizeof(from);
236 flags = 0;
237 packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
239 if (packetLen >= 0)
241 SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
242 SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
244 // If we have broken IP_RECVDSTADDR functionality (so far
245 // I've only seen this on OpenBSD) then apply a hack to
246 // convince mDNS Core that this isn't a spoof packet.
247 // Basically what we do is check to see whether the
248 // packet arrived as a multicast and, if so, set its
249 // destAddr to the mDNS address.
251 // I must admit that I could just be doing something
252 // wrong on OpenBSD and hence triggering this problem
253 // but I'm at a loss as to how.
255 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
256 // no way to tell the destination address or interface this packet arrived on,
257 // so all we can do is just assume it's a multicast
259 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
260 if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
262 destAddr.type = senderAddr.type;
263 if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
264 else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
266 #endif
268 // We only accept the packet if the interface on which it came
269 // in matches the interface associated with this socket.
270 // We do this match by name or by index, depending on which
271 // information is available. recvfrom_flags sets the name
272 // to "" if the name isn't available, or the index to -1
273 // if the index is available. This accomodates the various
274 // different capabilities of our target platforms.
276 reject = mDNSfalse;
277 if (!intf)
279 // Ignore multicasts accidentally delivered to our unicast receiving socket
280 if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
282 else
284 if (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
285 else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
287 if (reject)
289 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
290 &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
291 &intf->coreIntf.ip, intf->intfName, intf->index, skt);
292 packetLen = -1;
293 num_pkts_rejected++;
294 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
296 fprintf(stderr,
297 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
298 num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
299 num_pkts_accepted = 0;
300 num_pkts_rejected = 0;
303 else
305 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
306 &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
307 num_pkts_accepted++;
312 if (packetLen >= 0)
313 mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
314 &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
317 mDNSexport mDNSBool mDNSPlatformPeekUDP(mDNS *const m, UDPSocket *src)
319 (void)m; // unused
320 (void)src; // unused
321 return mDNSfalse;
324 mDNSexport TCPSocket *mDNSPlatformTCPSocket(mDNS * const m, TCPSocketFlags flags, mDNSIPPort * port, mDNSBool useBackgroundTrafficClass)
326 (void)m; // Unused
327 (void)flags; // Unused
328 (void)port; // Unused
329 (void)useBackgroundTrafficClass; // Unused
330 return NULL;
333 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd)
335 (void)flags; // Unused
336 (void)sd; // Unused
337 return NULL;
340 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
342 (void)sock; // Unused
343 return -1;
346 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname, mDNSInterfaceID InterfaceID,
347 TCPConnectionCallback callback, void *context)
349 (void)sock; // Unused
350 (void)dst; // Unused
351 (void)dstport; // Unused
352 (void)hostname; // Unused
353 (void)InterfaceID; // Unused
354 (void)callback; // Unused
355 (void)context; // Unused
356 return(mStatus_UnsupportedErr);
359 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
361 (void)sock; // Unused
364 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
366 (void)sock; // Unused
367 (void)buf; // Unused
368 (void)buflen; // Unused
369 (void)closed; // Unused
370 return 0;
373 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
375 (void)sock; // Unused
376 (void)msg; // Unused
377 (void)len; // Unused
378 return 0;
381 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNS * const m, mDNSIPPort port)
383 (void)m; // Unused
384 (void)port; // Unused
385 return NULL;
388 mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
390 (void)sock; // Unused
393 mDNSexport void mDNSPlatformUpdateProxyList(mDNS *const m, const mDNSInterfaceID InterfaceID)
395 (void)m; // Unused
396 (void)InterfaceID; // Unused
399 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
401 (void)msg; // Unused
402 (void)end; // Unused
403 (void)InterfaceID; // Unused
406 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
408 (void)m; // Unused
409 (void)tpa; // Unused
410 (void)tha; // Unused
411 (void)InterfaceID; // Unused
414 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
416 return(mStatus_UnsupportedErr);
419 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
423 mDNSexport void mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason)
425 (void) m;
426 (void) allowSleep;
427 (void) reason;
430 #if COMPILER_LIKES_PRAGMA_MARK
431 #pragma mark -
432 #pragma mark - /etc/hosts support
433 #endif
435 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
437 (void)m; // unused
438 (void)rr;
439 (void)result;
443 #if COMPILER_LIKES_PRAGMA_MARK
444 #pragma mark ***** DDNS Config Platform Functions
445 #endif
448 * Stub to set or get DNS config. Even if it actually does not do anything, it has to
449 * make sure the data is zeroed properly.
451 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
452 DNameListElem **BrowseDomains, mDNSBool ackConfig)
454 (void) m;
455 (void) setservers;
456 if (fqdn) fqdn->c[0] = 0;
457 (void) setsearch;
458 if (RegDomains) *RegDomains = NULL;
459 if (BrowseDomains) *BrowseDomains = NULL;
460 (void) ackConfig;
462 return mDNStrue;
465 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNS * const m, mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
467 (void) m;
468 (void) v4;
469 (void) v6;
470 (void) router;
472 return mStatus_UnsupportedErr;
475 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
477 (void) dname;
478 (void) status;
481 #if COMPILER_LIKES_PRAGMA_MARK
482 #pragma mark ***** Init and Term
483 #endif
485 // This gets the current hostname, truncating it at the first dot if necessary
486 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
488 int len = 0;
489 gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
490 while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
491 namelabel->c[0] = len;
494 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
495 // Other platforms can either get the information from the appropriate place,
496 // or they can alternatively just require all registering services to provide an explicit name
497 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
499 // On Unix we have no better name than the host name, so we just use that.
500 GetUserSpecifiedRFC1034ComputerName(namelabel);
503 mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
505 char line[256];
506 char nameserver[16];
507 char keyword[11];
508 int numOfServers = 0;
509 FILE *fp = fopen(filePath, "r");
510 if (fp == NULL) return -1;
511 while (fgets(line,sizeof(line),fp))
513 struct in_addr ina;
514 line[255]='\0'; // just to be safe
515 if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue; // it will skip whitespaces
516 if (strncasecmp(keyword,"nameserver",10)) continue;
517 if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
519 mDNSAddr DNSAddr;
520 DNSAddr.type = mDNSAddrType_IPv4;
521 DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
522 mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
523 numOfServers++;
526 fclose(fp);
527 return (numOfServers > 0) ? 0 : -1;
530 // Searches the interface list looking for the named interface.
531 // Returns a pointer to if it found, or NULL otherwise.
532 mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
534 PosixNetworkInterface *intf;
536 assert(m != NULL);
537 assert(intfName != NULL);
539 intf = (PosixNetworkInterface*)(m->HostInterfaces);
540 while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
541 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
543 return intf;
546 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
548 PosixNetworkInterface *intf;
550 assert(m != NULL);
552 if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
553 if (index == kDNSServiceInterfaceIndexP2P ) return(mDNSInterface_P2P);
554 if (index == kDNSServiceInterfaceIndexAny ) return(mDNSInterface_Any);
556 intf = (PosixNetworkInterface*)(m->HostInterfaces);
557 while ((intf != NULL) && (mDNSu32) intf->index != index)
558 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
560 return (mDNSInterfaceID) intf;
563 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
565 PosixNetworkInterface *intf;
566 (void) suppressNetworkChange; // Unused
568 assert(m != NULL);
570 if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
571 if (id == mDNSInterface_P2P ) return(kDNSServiceInterfaceIndexP2P);
572 if (id == mDNSInterface_Any ) return(kDNSServiceInterfaceIndexAny);
574 intf = (PosixNetworkInterface*)(m->HostInterfaces);
575 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
576 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
578 if (intf) return intf->index;
580 // If we didn't find the interface, check the RecentInterfaces list as well
581 intf = gRecentInterfaces;
582 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
583 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
585 return intf ? intf->index : 0;
588 // Frees the specified PosixNetworkInterface structure. The underlying
589 // interface must have already been deregistered with the mDNS core.
590 mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
592 assert(intf != NULL);
593 if (intf->intfName != NULL) free((void *)intf->intfName);
594 if (intf->multicastSocket4 != -1) assert(close(intf->multicastSocket4) == 0);
595 #if HAVE_IPV6
596 if (intf->multicastSocket6 != -1) assert(close(intf->multicastSocket6) == 0);
597 #endif
599 // Move interface to the RecentInterfaces list for a minute
600 intf->LastSeen = mDNSPlatformUTC();
601 intf->coreIntf.next = &gRecentInterfaces->coreIntf;
602 gRecentInterfaces = intf;
605 // Grab the first interface, deregister it, free it, and repeat until done.
606 mDNSlocal void ClearInterfaceList(mDNS *const m)
608 assert(m != NULL);
610 while (m->HostInterfaces)
612 PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
613 mDNS_DeregisterInterface(m, &intf->coreIntf, mDNSfalse);
614 if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
615 FreePosixNetworkInterface(intf);
617 num_registered_interfaces = 0;
618 num_pkts_accepted = 0;
619 num_pkts_rejected = 0;
622 // Sets up a send/receive socket.
623 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
624 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
625 mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
627 int err = 0;
628 static const int kOn = 1;
629 static const int kIntTwoFiveFive = 255;
630 static const unsigned char kByteTwoFiveFive = 255;
631 const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
633 (void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
634 assert(intfAddr != NULL);
635 assert(sktPtr != NULL);
636 assert(*sktPtr == -1);
638 // Open the socket...
639 if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
640 #if HAVE_IPV6
641 else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
642 #endif
643 else return EINVAL;
645 if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
647 // ... with a shared UDP port, if it's for multicast receiving
648 if (err == 0 && port.NotAnInteger)
650 // <rdar://problem/20946253>
651 // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
652 // Linux kernel versions 3.9 introduces support for socket option
653 // SO_REUSEPORT, however this is not implemented the same as on *BSD
654 // systems. Linux version implements a "port hijacking" prevention
655 // mechanism, limiting processes wanting to bind to an already existing
656 // addr:port to have the same effective UID as the first who bound it. What
657 // this meant for us was that the daemon ran as one user and when for
658 // instance mDNSClientPosix was executed by another user, it wasn't allowed
659 // to bind to the socket. Our suggestion was to switch the order in which
660 // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
661 // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
662 #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
663 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
664 #elif defined(SO_REUSEPORT)
665 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
666 #else
667 #error This platform has no way to avoid address busy errors on multicast.
668 #endif
669 if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
671 // Enable inbound packets on IFEF_AWDL interface.
672 // Only done for multicast sockets, since we don't expect unicast socket operations
673 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
674 #ifdef SO_RECV_ANYIF
675 if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
676 #endif
679 // We want to receive destination addresses and interface identifiers.
680 if (intfAddr->sa_family == AF_INET)
682 struct ip_mreq imr;
683 struct sockaddr_in bindAddr;
684 if (err == 0)
686 #if defined(IP_PKTINFO) // Linux
687 err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
688 if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
689 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
690 #if defined(IP_RECVDSTADDR)
691 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
692 if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
693 #endif
694 #if defined(IP_RECVIF)
695 if (err == 0)
697 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
698 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
700 #endif
701 #else
702 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
703 #endif
705 #if defined(IP_RECVTTL) // Linux
706 if (err == 0)
708 setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
709 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
711 #endif
713 // Add multicast group membership on this interface
714 if (err == 0 && JoinMulticastGroup)
716 imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
717 imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
718 err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
719 if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
722 // Specify outgoing interface too
723 if (err == 0 && JoinMulticastGroup)
725 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
726 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
729 // Per the mDNS spec, send unicast packets with TTL 255
730 if (err == 0)
732 err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
733 if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
736 // and multicast packets with TTL 255 too
737 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
738 if (err == 0)
740 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
741 if (err < 0 && errno == EINVAL)
742 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
743 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
746 // And start listening for packets
747 if (err == 0)
749 bindAddr.sin_family = AF_INET;
750 bindAddr.sin_port = port.NotAnInteger;
751 bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
752 err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
753 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
755 } // endif (intfAddr->sa_family == AF_INET)
757 #if HAVE_IPV6
758 else if (intfAddr->sa_family == AF_INET6)
760 struct ipv6_mreq imr6;
761 struct sockaddr_in6 bindAddr6;
762 #if defined(IPV6_RECVPKTINFO) // Solaris
763 if (err == 0)
765 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVPKTINFO, &kOn, sizeof(kOn));
766 if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVPKTINFO"); }
768 #elif defined(IPV6_PKTINFO)
769 if (err == 0)
771 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
772 if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
774 #else
775 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
776 #endif
777 #if defined(IPV6_RECVHOPLIMIT)
778 if (err == 0)
780 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &kOn, sizeof(kOn));
781 if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVHOPLIMIT"); }
783 #elif defined(IPV6_HOPLIMIT)
784 if (err == 0)
786 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
787 if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
789 #endif
791 // Add multicast group membership on this interface
792 if (err == 0 && JoinMulticastGroup)
794 imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
795 imr6.ipv6mr_interface = interfaceIndex;
796 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
797 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
798 if (err < 0)
800 err = errno;
801 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
802 perror("setsockopt - IPV6_JOIN_GROUP");
806 // Specify outgoing interface too
807 if (err == 0 && JoinMulticastGroup)
809 u_int multicast_if = interfaceIndex;
810 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
811 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
814 // We want to receive only IPv6 packets on this socket.
815 // Without this option, we may get IPv4 addresses as mapped addresses.
816 if (err == 0)
818 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
819 if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
822 // Per the mDNS spec, send unicast packets with TTL 255
823 if (err == 0)
825 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
826 if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
829 // and multicast packets with TTL 255 too
830 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
831 if (err == 0)
833 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
834 if (err < 0 && errno == EINVAL)
835 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
836 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
839 // And start listening for packets
840 if (err == 0)
842 mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
843 #ifndef NOT_HAVE_SA_LEN
844 bindAddr6.sin6_len = sizeof(bindAddr6);
845 #endif
846 bindAddr6.sin6_family = AF_INET6;
847 bindAddr6.sin6_port = port.NotAnInteger;
848 bindAddr6.sin6_flowinfo = 0;
849 bindAddr6.sin6_addr = in6addr_any; // Want to receive multicasts AND unicasts on this socket
850 bindAddr6.sin6_scope_id = 0;
851 err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
852 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
854 } // endif (intfAddr->sa_family == AF_INET6)
855 #endif
857 // Set the socket to non-blocking.
858 if (err == 0)
860 err = fcntl(*sktPtr, F_GETFL, 0);
861 if (err < 0) err = errno;
862 else
864 err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
865 if (err < 0) err = errno;
869 // Clean up
870 if (err != 0 && *sktPtr != -1) { assert(close(*sktPtr) == 0); *sktPtr = -1; }
871 assert((err == 0) == (*sktPtr != -1));
872 return err;
875 // Creates a PosixNetworkInterface for the interface whose IP address is
876 // intfAddr and whose name is intfName and registers it with mDNS core.
877 mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
879 int err = 0;
880 PosixNetworkInterface *intf;
881 PosixNetworkInterface *alias = NULL;
883 assert(m != NULL);
884 assert(intfAddr != NULL);
885 assert(intfName != NULL);
886 assert(intfMask != NULL);
888 // Allocate the interface structure itself.
889 intf = (PosixNetworkInterface*)calloc(1, sizeof(*intf));
890 if (intf == NULL) { assert(0); err = ENOMEM; }
892 // And make a copy of the intfName.
893 if (err == 0)
895 intf->intfName = strdup(intfName);
896 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
899 if (err == 0)
901 // Set up the fields required by the mDNS core.
902 SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
903 SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
905 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
906 strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
907 intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
908 intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
909 intf->coreIntf.McastTxRx = mDNStrue;
911 // Set up the extra fields in PosixNetworkInterface.
912 assert(intf->intfName != NULL); // intf->intfName already set up above
913 intf->index = intfIndex;
914 intf->multicastSocket4 = -1;
915 #if HAVE_IPV6
916 intf->multicastSocket6 = -1;
917 #endif
918 alias = SearchForInterfaceByName(m, intf->intfName);
919 if (alias == NULL) alias = intf;
920 intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
922 if (alias != intf)
923 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
926 // Set up the multicast socket
927 if (err == 0)
929 if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
930 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
931 #if HAVE_IPV6
932 else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
933 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
934 #endif
937 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
938 // and skip the probe phase of the probe/announce packet sequence.
939 intf->coreIntf.DirectLink = mDNSfalse;
940 #ifdef DIRECTLINK_INTERFACE_NAME
941 if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
942 intf->coreIntf.DirectLink = mDNStrue;
943 #endif
944 intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;
946 // The interface is all ready to go, let's register it with the mDNS core.
947 if (err == 0)
948 err = mDNS_RegisterInterface(m, &intf->coreIntf, mDNSfalse);
950 // Clean up.
951 if (err == 0)
953 num_registered_interfaces++;
954 debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
955 if (gMDNSPlatformPosixVerboseLevel > 0)
956 fprintf(stderr, "Registered interface %s\n", intf->intfName);
958 else
960 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
961 debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
962 if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
965 assert((err == 0) == (intf != NULL));
967 return err;
970 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
971 mDNSlocal int SetupInterfaceList(mDNS *const m)
973 mDNSBool foundav4 = mDNSfalse;
974 int err = 0;
975 struct ifi_info *intfList = get_ifi_info(AF_INET, mDNStrue);
976 struct ifi_info *firstLoopback = NULL;
978 assert(m != NULL);
979 debugf("SetupInterfaceList");
981 if (intfList == NULL) err = ENOENT;
983 #if HAVE_IPV6
984 if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
986 struct ifi_info **p = &intfList;
987 while (*p) p = &(*p)->ifi_next;
988 *p = get_ifi_info(AF_INET6, mDNStrue);
990 #endif
992 if (err == 0)
994 struct ifi_info *i = intfList;
995 while (i)
997 if ( ((i->ifi_addr->sa_family == AF_INET)
998 #if HAVE_IPV6
999 || (i->ifi_addr->sa_family == AF_INET6)
1000 #endif
1001 ) && (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT))
1003 if (i->ifi_flags & IFF_LOOPBACK)
1005 if (firstLoopback == NULL)
1006 firstLoopback = i;
1008 else
1010 if (SetupOneInterface(m, i->ifi_addr, i->ifi_netmask, i->ifi_name, i->ifi_index) == 0)
1011 if (i->ifi_addr->sa_family == AF_INET)
1012 foundav4 = mDNStrue;
1015 i = i->ifi_next;
1018 // If we found no normal interfaces but we did find a loopback interface, register the
1019 // loopback interface. This allows self-discovery if no interfaces are configured.
1020 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
1021 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
1022 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
1023 if (!foundav4 && firstLoopback)
1024 (void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_netmask, firstLoopback->ifi_name, firstLoopback->ifi_index);
1027 // Clean up.
1028 if (intfList != NULL) free_ifi_info(intfList);
1030 // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
1031 PosixNetworkInterface **ri = &gRecentInterfaces;
1032 const mDNSs32 utc = mDNSPlatformUTC();
1033 while (*ri)
1035 PosixNetworkInterface *pi = *ri;
1036 if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
1037 else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
1040 return err;
1043 #if USES_NETLINK
1045 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1047 // Open a socket that will receive interface change notifications
1048 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1050 mStatus err = mStatus_NoError;
1051 struct sockaddr_nl snl;
1052 int sock;
1053 int ret;
1055 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1056 if (sock < 0)
1057 return errno;
1059 // Configure read to be non-blocking because inbound msg size is not known in advance
1060 (void) fcntl(sock, F_SETFL, O_NONBLOCK);
1062 /* Subscribe the socket to Link & IP addr notifications. */
1063 mDNSPlatformMemZero(&snl, sizeof snl);
1064 snl.nl_family = AF_NETLINK;
1065 snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
1066 ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
1067 if (0 == ret)
1068 *pFD = sock;
1069 else
1070 err = errno;
1072 return err;
1075 #if MDNS_DEBUGMSGS
1076 mDNSlocal void PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
1078 const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1079 const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1081 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
1082 pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
1083 pNLMsg->nlmsg_flags);
1085 if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
1087 struct ifinfomsg *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
1088 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
1089 pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
1092 else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
1094 struct ifaddrmsg *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
1095 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
1096 pIfAddr->ifa_index, pIfAddr->ifa_flags);
1098 printf("\n");
1100 #endif
1102 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1103 // Read through the messages on sd and if any indicate that any interface records should
1104 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1106 ssize_t readCount;
1107 char buff[4096];
1108 struct nlmsghdr *pNLMsg = (struct nlmsghdr*) buff;
1109 mDNSu32 result = 0;
1111 // The structure here is more complex than it really ought to be because,
1112 // unfortunately, there's no good way to size a buffer in advance large
1113 // enough to hold all pending data and so avoid message fragmentation.
1114 // (Note that FIONREAD is not supported on AF_NETLINK.)
1116 readCount = read(sd, buff, sizeof buff);
1117 while (1)
1119 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1120 // If not, discard already-processed messages in buffer and read more data.
1121 if (((char*) &pNLMsg[1] > (buff + readCount)) || // i.e. *pNLMsg extends off end of buffer
1122 ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
1124 if (buff < (char*) pNLMsg) // we have space to shuffle
1126 // discard processed data
1127 readCount -= ((char*) pNLMsg - buff);
1128 memmove(buff, pNLMsg, readCount);
1129 pNLMsg = (struct nlmsghdr*) buff;
1131 // read more data
1132 readCount += read(sd, buff + readCount, sizeof buff - readCount);
1133 continue; // spin around and revalidate with new readCount
1135 else
1136 break; // Otherwise message does not fit in buffer
1139 #if MDNS_DEBUGMSGS
1140 PrintNetLinkMsg(pNLMsg);
1141 #endif
1143 // Process the NetLink message
1144 if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
1145 result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
1146 else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
1147 result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
1149 // Advance pNLMsg to the next message in the buffer
1150 if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
1152 ssize_t len = readCount - ((char*)pNLMsg - buff);
1153 pNLMsg = NLMSG_NEXT(pNLMsg, len);
1155 else
1156 break; // all done!
1159 return result;
1162 #else // USES_NETLINK
1164 // Open a socket that will receive interface change notifications
1165 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1167 *pFD = socket(AF_ROUTE, SOCK_RAW, 0);
1169 if (*pFD < 0)
1170 return mStatus_UnknownErr;
1172 // Configure read to be non-blocking because inbound msg size is not known in advance
1173 (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
1175 return mStatus_NoError;
1178 #if MDNS_DEBUGMSGS
1179 mDNSlocal void PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
1181 const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1182 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1183 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1185 int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
1187 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
1189 #endif
1191 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1192 // Read through the messages on sd and if any indicate that any interface records should
1193 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1195 ssize_t readCount;
1196 char buff[4096];
1197 struct ifa_msghdr *pRSMsg = (struct ifa_msghdr*) buff;
1198 mDNSu32 result = 0;
1200 readCount = read(sd, buff, sizeof buff);
1201 if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
1202 return mStatus_UnsupportedErr; // cannot decipher message
1204 #if MDNS_DEBUGMSGS
1205 PrintRoutingSocketMsg(pRSMsg);
1206 #endif
1208 // Process the message
1209 switch (pRSMsg->ifam_type)
1211 case RTM_NEWADDR:
1212 case RTM_DELADDR:
1213 case RTM_IFINFO:
1215 * ADD & DELETE are happening when IPv6 announces are changing,
1216 * and for some reason it will stop mdnsd to announce IPv6
1217 * addresses. So we force mdnsd to check interfaces.
1219 case RTM_ADD:
1220 case RTM_DELETE:
1221 if (pRSMsg->ifam_type == RTM_IFINFO)
1222 result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
1223 else
1224 result |= 1 << pRSMsg->ifam_index;
1225 break;
1228 return result;
1231 #endif // USES_NETLINK
1233 // Called when data appears on interface change notification socket
1234 mDNSlocal void InterfaceChangeCallback(int fd, short filter, void *context)
1236 IfChangeRec *pChgRec = (IfChangeRec*) context;
1237 fd_set readFDs;
1238 mDNSu32 changedInterfaces = 0;
1239 struct timeval zeroTimeout = { 0, 0 };
1241 (void)fd; // Unused
1242 (void)filter; // Unused
1244 FD_ZERO(&readFDs);
1245 FD_SET(pChgRec->NotifySD, &readFDs);
1249 changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
1251 while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
1253 // Currently we rebuild the entire interface list whenever any interface change is
1254 // detected. If this ever proves to be a performance issue in a multi-homed
1255 // configuration, more care should be paid to changedInterfaces.
1256 if (changedInterfaces)
1257 mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
1260 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1261 mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
1263 mStatus err;
1264 IfChangeRec *pChgRec;
1266 pChgRec = (IfChangeRec*) mDNSPlatformMemAllocate(sizeof *pChgRec);
1267 if (pChgRec == NULL)
1268 return mStatus_NoMemoryErr;
1270 pChgRec->mDNS = m;
1271 err = OpenIfNotifySocket(&pChgRec->NotifySD);
1272 if (err == 0)
1273 err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
1275 return err;
1278 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1279 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1280 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1281 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
1283 int err;
1284 int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1285 struct sockaddr_in s5353;
1286 s5353.sin_family = AF_INET;
1287 s5353.sin_port = MulticastDNSPort.NotAnInteger;
1288 s5353.sin_addr.s_addr = 0;
1289 err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
1290 close(s);
1291 if (err) debugf("No unicast UDP responses");
1292 else debugf("Unicast UDP responses okay");
1293 return(err == 0);
1296 // mDNS core calls this routine to initialise the platform-specific data.
1297 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
1299 int err = 0;
1300 struct sockaddr sa;
1301 assert(m != NULL);
1303 if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
1305 // Tell mDNS core the names of this machine.
1307 // Set up the nice label
1308 m->nicelabel.c[0] = 0;
1309 GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
1310 if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
1312 // Set up the RFC 1034-compliant label
1313 m->hostlabel.c[0] = 0;
1314 GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
1315 if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
1317 mDNS_SetFQDN(m);
1319 sa.sa_family = AF_INET;
1320 m->p->unicastSocket4 = -1;
1321 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
1322 #if HAVE_IPV6
1323 sa.sa_family = AF_INET6;
1324 m->p->unicastSocket6 = -1;
1325 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
1326 #endif
1328 // Tell mDNS core about the network interfaces on this machine.
1329 if (err == mStatus_NoError) err = SetupInterfaceList(m);
1331 // Tell mDNS core about DNS Servers
1332 mDNS_Lock(m);
1333 if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
1334 mDNS_Unlock(m);
1336 if (err == mStatus_NoError)
1338 err = WatchForInterfaceChange(m);
1339 // Failure to observe interface changes is non-fatal.
1340 if (err != mStatus_NoError)
1342 fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n",
1343 (int)getpid(), err);
1344 err = mStatus_NoError;
1348 // We don't do asynchronous initialization on the Posix platform, so by the time
1349 // we get here the setup will already have succeeded or failed. If it succeeded,
1350 // we should just call mDNSCoreInitComplete() immediately.
1351 if (err == mStatus_NoError)
1352 mDNSCoreInitComplete(m, mStatus_NoError);
1354 return PosixErrorToStatus(err);
1357 // mDNS core calls this routine to clean up the platform-specific data.
1358 // In our case all we need to do is to tear down every network interface.
1359 mDNSexport void mDNSPlatformClose(mDNS *const m)
1361 assert(m != NULL);
1362 ClearInterfaceList(m);
1363 if (m->p->unicastSocket4 != -1) assert(close(m->p->unicastSocket4) == 0);
1364 #if HAVE_IPV6
1365 if (m->p->unicastSocket6 != -1) assert(close(m->p->unicastSocket6) == 0);
1366 #endif
1369 // This is used internally by InterfaceChangeCallback.
1370 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1371 // can call it in response to a SIGHUP (mainly for debugging purposes).
1372 mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
1374 int err;
1375 // This is a pretty heavyweight way to process interface changes --
1376 // destroying the entire interface list and then making fresh one from scratch.
1377 // We should make it like the OS X version, which leaves unchanged interfaces alone.
1378 ClearInterfaceList(m);
1379 err = SetupInterfaceList(m);
1380 return PosixErrorToStatus(err);
1383 #if COMPILER_LIKES_PRAGMA_MARK
1384 #pragma mark ***** Locking
1385 #endif
1387 // On the Posix platform, locking is a no-op because we only ever enter
1388 // mDNS core on the main thread.
1390 // mDNS core calls this routine when it wants to prevent
1391 // the platform from reentering mDNS core code.
1392 mDNSexport void mDNSPlatformLock (const mDNS *const m)
1394 (void) m; // Unused
1397 // mDNS core calls this routine when it release the lock taken by
1398 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1399 mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
1401 (void) m; // Unused
1404 #if COMPILER_LIKES_PRAGMA_MARK
1405 #pragma mark ***** Strings
1406 #endif
1408 // mDNS core calls this routine to copy C strings.
1409 // On the Posix platform this maps directly to the ANSI C strcpy.
1410 mDNSexport void mDNSPlatformStrCopy(void *dst, const void *src)
1412 strcpy((char *)dst, (char *)src);
1415 // mDNS core calls this routine to get the length of a C string.
1416 // On the Posix platform this maps directly to the ANSI C strlen.
1417 mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
1419 return strlen((char*)src);
1422 // mDNS core calls this routine to copy memory.
1423 // On the Posix platform this maps directly to the ANSI C memcpy.
1424 mDNSexport void mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
1426 memcpy(dst, src, len);
1429 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1430 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1431 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
1433 return memcmp(dst, src, len) == 0;
1436 // If the caller wants to know the exact return of memcmp, then use this instead
1437 // of mDNSPlatformMemSame
1438 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
1440 return (memcmp(dst, src, len));
1443 mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
1445 (void)qsort(base, nel, width, compar);
1448 // DNSSEC stub functions
1449 mDNSexport void VerifySignature(mDNS *const m, DNSSECVerifier *dv, DNSQuestion *q)
1451 (void)m;
1452 (void)dv;
1453 (void)q;
1456 mDNSexport mDNSBool AddNSECSForCacheRecord(mDNS *const m, CacheRecord *crlist, CacheRecord *negcr, mDNSu8 rcode)
1458 (void)m;
1459 (void)crlist;
1460 (void)negcr;
1461 (void)rcode;
1462 return mDNSfalse;
1465 mDNSexport void BumpDNSSECStats(mDNS *const m, DNSSECStatsAction action, DNSSECStatsType type, mDNSu32 value)
1467 (void)m;
1468 (void)action;
1469 (void)type;
1470 (void)value;
1473 // Proxy stub functions
1474 mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
1476 (void) q;
1477 (void) h;
1478 (void) msg;
1479 (void) ptr;
1480 (void) limit;
1482 return ptr;
1485 mDNSexport void DNSProxyInit(mDNS *const m, mDNSu32 IpIfArr[], mDNSu32 OpIf)
1487 (void) m;
1488 (void) IpIfArr;
1489 (void) OpIf;
1492 mDNSexport void DNSProxyTerminate(mDNS *const m)
1494 (void) m;
1497 // mDNS core calls this routine to clear blocks of memory.
1498 // On the Posix platform this is a simple wrapper around ANSI C memset.
1499 mDNSexport void mDNSPlatformMemZero(void *dst, mDNSu32 len)
1501 memset(dst, 0, len);
1504 mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
1505 mDNSexport void mDNSPlatformMemFree (void *mem) { free(mem); }
1507 mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
1509 struct timeval tv;
1510 gettimeofday(&tv, NULL);
1511 return(tv.tv_usec);
1514 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
1516 mDNSexport mStatus mDNSPlatformTimeInit(void)
1518 // No special setup is required on Posix -- we just use gettimeofday();
1519 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1520 // We should find a better way to do this
1521 return(mStatus_NoError);
1524 mDNSexport mDNSs32 mDNSPlatformRawTime()
1526 struct timeval tv;
1527 gettimeofday(&tv, NULL);
1528 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1529 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1530 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1531 // and we multiply tv.tv_usec by 16 / 15625 to get a value in the range 0-1023 to go in the bottom 10 bits.
1532 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1533 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1534 return((tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625));
1537 mDNSexport mDNSs32 mDNSPlatformUTC(void)
1539 return time(NULL);
1542 mDNSexport void mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
1544 (void) m;
1545 (void) InterfaceID;
1546 (void) EthAddr;
1547 (void) IPAddr;
1548 (void) iteration;
1551 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(AuthRecord *rr, const NetworkInterfaceInfo *intf)
1553 (void) rr;
1554 (void) intf;
1556 return 1;
1559 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
1561 (void) q;
1562 (void) intf;
1564 return 1;
1567 // Used for debugging purposes. For now, just set the buffer to zero
1568 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
1570 (void) te;
1571 if (bufsize) buf[0] = 0;
1574 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
1576 (void) sadd; // Unused
1577 (void) dadd; // Unused
1578 (void) lport; // Unused
1579 (void) rport; // Unused
1580 (void) seq; // Unused
1581 (void) ack; // Unused
1582 (void) win; // Unused
1585 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNS *const m, mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
1587 (void) m; // Unused
1588 (void) laddr; // Unused
1589 (void) raddr; // Unused
1590 (void) lport; // Unused
1591 (void) rport; // Unused
1592 (void) mti; // Unused
1594 return mStatus_NoError;
1597 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNS *const m, mDNSAddr *raddr)
1599 (void) raddr; // Unused
1600 (void) m; // Unused
1602 return mStatus_NoError;
1605 mDNSexport mStatus mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
1607 (void) spsaddr; // Unused
1608 (void) ifname; // Unused
1610 return mStatus_NoError;
1613 mDNSexport mStatus mDNSPlatformClearSPSMACAddr(void)
1615 return mStatus_NoError;
1618 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
1620 (void) sock; // unused
1622 return (mDNSu16)-1;
1625 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
1627 (void) InterfaceID; // unused
1629 return mDNSfalse;
1632 mDNSexport void mDNSPlatformGetDNSRoutePolicy(mDNS *const m, DNSQuestion *q, mDNSBool *isCellBlocked)
1634 (void) m;
1636 q->ServiceID = -1;
1637 *isCellBlocked = mDNSfalse;
1640 mDNSexport void mDNSPlatformSetuDNSSocktOpt(UDPSocket *src, const mDNSAddr *dst, DNSQuestion *q)
1642 (void) src;
1643 (void) dst;
1644 (void) q;
1647 mDNSexport mDNSs32 mDNSPlatformGetPID()
1649 return 0;
1652 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
1654 if (*nfds < s + 1) *nfds = s + 1;
1655 FD_SET(s, readfds);
1658 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, struct timeval *timeout)
1660 mDNSs32 ticks;
1661 struct timeval interval;
1663 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1664 mDNSs32 nextevent = mDNS_Execute(m);
1666 // 2. Build our list of active file descriptors
1667 PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
1668 if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket4);
1669 #if HAVE_IPV6
1670 if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket6);
1671 #endif
1672 while (info)
1674 if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket4);
1675 #if HAVE_IPV6
1676 if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket6);
1677 #endif
1678 info = (PosixNetworkInterface *)(info->coreIntf.next);
1681 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1682 ticks = nextevent - mDNS_TimeNow(m);
1683 if (ticks < 1) ticks = 1;
1684 interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
1685 interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1687 // 4. If client's proposed timeout is more than what we want, then reduce it
1688 if (timeout->tv_sec > interval.tv_sec ||
1689 (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
1690 *timeout = interval;
1693 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
1695 PosixNetworkInterface *info;
1696 assert(m != NULL);
1697 assert(readfds != NULL);
1698 info = (PosixNetworkInterface *)(m->HostInterfaces);
1700 if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
1702 FD_CLR(m->p->unicastSocket4, readfds);
1703 SocketDataReady(m, NULL, m->p->unicastSocket4);
1705 #if HAVE_IPV6
1706 if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
1708 FD_CLR(m->p->unicastSocket6, readfds);
1709 SocketDataReady(m, NULL, m->p->unicastSocket6);
1711 #endif
1713 while (info)
1715 if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
1717 FD_CLR(info->multicastSocket4, readfds);
1718 SocketDataReady(m, info, info->multicastSocket4);
1720 #if HAVE_IPV6
1721 if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
1723 FD_CLR(info->multicastSocket6, readfds);
1724 SocketDataReady(m, info, info->multicastSocket6);
1726 #endif
1727 info = (PosixNetworkInterface *)(info->coreIntf.next);
1731 // update gMaxFD
1732 mDNSlocal void DetermineMaxEventFD(void)
1734 PosixEventSource *iSource;
1736 gMaxFD = 0;
1737 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1738 if (gMaxFD < iSource->fd)
1739 gMaxFD = iSource->fd;
1742 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1743 mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
1745 PosixEventSource *newSource;
1747 if (gEventSources.LinkOffset == 0)
1748 InitLinkedList(&gEventSources, offsetof(PosixEventSource, Next));
1750 if (fd >= (int) FD_SETSIZE || fd < 0)
1751 return mStatus_UnsupportedErr;
1752 if (callback == NULL)
1753 return mStatus_BadParamErr;
1755 newSource = (PosixEventSource*) malloc(sizeof *newSource);
1756 if (NULL == newSource)
1757 return mStatus_NoMemoryErr;
1759 newSource->Callback = callback;
1760 newSource->Context = context;
1761 newSource->fd = fd;
1763 AddToTail(&gEventSources, newSource);
1764 FD_SET(fd, &gEventFDs);
1766 DetermineMaxEventFD();
1768 return mStatus_NoError;
1771 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1772 mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
1774 PosixEventSource *iSource;
1776 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1778 if (fd == iSource->fd)
1780 FD_CLR(fd, &gEventFDs);
1781 RemoveFromList(&gEventSources, iSource);
1782 free(iSource);
1783 DetermineMaxEventFD();
1784 return mStatus_NoError;
1787 return mStatus_NoSuchNameErr;
1790 // Simply note the received signal in gEventSignals.
1791 mDNSlocal void NoteSignal(int signum)
1793 sigaddset(&gEventSignals, signum);
1796 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1797 mStatus mDNSPosixListenForSignalInEventLoop(int signum)
1799 struct sigaction action;
1800 mStatus err;
1802 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
1803 action.sa_handler = NoteSignal;
1804 err = sigaction(signum, &action, (struct sigaction*) NULL);
1806 sigaddset(&gEventSignalSet, signum);
1808 return err;
1811 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1812 mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
1814 struct sigaction action;
1815 mStatus err;
1817 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
1818 action.sa_handler = SIG_DFL;
1819 err = sigaction(signum, &action, (struct sigaction*) NULL);
1821 sigdelset(&gEventSignalSet, signum);
1823 return err;
1826 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1827 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1828 mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
1829 sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
1831 fd_set listenFDs = gEventFDs;
1832 int fdMax = 0, numReady;
1833 struct timeval timeout = *pTimeout;
1835 // Include the sockets that are listening to the wire in our select() set
1836 mDNSPosixGetFDSet(m, &fdMax, &listenFDs, &timeout); // timeout may get modified
1837 if (fdMax < gMaxFD)
1838 fdMax = gMaxFD;
1840 numReady = select(fdMax + 1, &listenFDs, (fd_set*) NULL, (fd_set*) NULL, &timeout);
1842 // If any data appeared, invoke its callback
1843 if (numReady > 0)
1845 PosixEventSource *iSource;
1847 (void) mDNSPosixProcessFDSet(m, &listenFDs); // call this first to process wire data for clients
1849 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1851 if (FD_ISSET(iSource->fd, &listenFDs))
1853 iSource->Callback(iSource->fd, 0, iSource->Context);
1854 break; // in case callback removed elements from gEventSources
1857 *pDataDispatched = mDNStrue;
1859 else
1860 *pDataDispatched = mDNSfalse;
1862 (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
1863 *pSignalsReceived = gEventSignals;
1864 sigemptyset(&gEventSignals);
1865 (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
1867 return mStatus_NoError;