2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
26 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
27 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
28 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
29 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
30 * therefore common sense dictates that if they are part of a compound statement then they
31 * should be indented to the same level as everything else in that compound statement.
32 * Indenting curly braces at the same level as the "if" implies that curly braces are
33 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
34 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
35 * understand why variable y is not of type "char*" just proves the point that poor code
36 * layout leads people to unfortunate misunderstandings about how the C language really works.)
38 Change History (most recent first):
41 Revision 1.46 2004/05/13 04:54:20 ksekar
42 Unified list copy/free code. Added symetric list for
44 Revision 1.45 2004/05/12 22:03:09 ksekar
45 Made GetSearchDomainList a true platform-layer call (declaration moved
46 from mDNSMacOSX.h to mDNSClientAPI.h), impelemted to return "local"
47 only on non-OSX platforms. Changed call to return a copy of the list
48 to avoid shared memory issues. Added a routine to free the list.
50 Revision 1.44 2004/04/21 02:49:11 cheshire
51 To reduce future confusion, renamed 'TxAndRx' to 'McastTxRx'
53 Revision 1.43 2004/04/14 23:09:29 ksekar
54 Support for TSIG signed dynamic updates.
56 Revision 1.42 2004/04/09 17:43:04 cheshire
57 Make sure to set the McastTxRx field so that duplicate suppression works correctly
59 Revision 1.41 2004/02/06 01:19:51 cheshire
60 Conditionally exclude IPv6 code unless HAVE_IPV6 is set
62 Revision 1.40 2004/02/05 01:00:01 rpantos
63 Fix some issues that turned up when building for FreeBSD.
65 Revision 1.39 2004/01/28 21:12:15 cheshire
66 Reconcile mDNSIPv6Support & HAVE_IPV6 into a single flag (HAVE_IPV6)
68 Revision 1.38 2004/01/27 20:15:23 cheshire
69 <rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
71 Revision 1.37 2004/01/24 05:12:03 cheshire
72 <rdar://problem/3534352>: Need separate socket for issuing unicast queries
74 Revision 1.36 2004/01/24 04:59:16 cheshire
75 Fixes so that Posix/Linux, OS9, Windows, and VxWorks targets build again
77 Revision 1.35 2004/01/23 21:37:08 cheshire
78 For consistency, rename multicastSocket to multicastSocket4, and multicastSocketv6 to multicastSocket6
80 Revision 1.34 2004/01/22 03:43:09 cheshire
81 Export constants like mDNSInterface_LocalOnly so that the client layers can use them
83 Revision 1.33 2004/01/21 21:54:20 cheshire
84 <rdar://problem/3448144>: Don't try to receive unicast responses if we're not the first to bind to the UDP port
86 Revision 1.32 2004/01/20 01:49:28 rpantos
87 Tweak error handling of last checkin a bit.
89 Revision 1.31 2004/01/20 01:39:27 rpantos
90 Respond to If changes by rebuilding interface list.
92 Revision 1.30 2003/12/11 19:40:36 cheshire
93 Fix 'destAddr.type == senderAddr.type;' that should have said 'destAddr.type = senderAddr.type;'
95 Revision 1.29 2003/12/11 18:53:22 cheshire
96 Fix compiler warning reported by Paul Guyot
98 Revision 1.28 2003/12/11 03:03:51 rpantos
99 Clean up mDNSPosix so that it builds on OS X again.
101 Revision 1.27 2003/12/08 20:47:02 rpantos
102 Add support for mDNSResponder on Linux.
104 Revision 1.26 2003/11/14 20:59:09 cheshire
105 Clients can't use AssignDomainName macro because mDNSPlatformMemCopy is defined in mDNSPlatformFunctions.h.
106 Best solution is just to combine mDNSClientAPI.h and mDNSPlatformFunctions.h into a single file.
108 Revision 1.25 2003/10/30 19:25:49 cheshire
109 Fix signed/unsigned warning on certain compilers
111 Revision 1.24 2003/08/18 23:12:23 cheshire
112 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
114 Revision 1.23 2003/08/12 19:56:26 cheshire
117 Revision 1.22 2003/08/06 18:46:15 cheshire
118 LogMsg() errors are serious -- always report them to stderr, regardless of debugging level
120 Revision 1.21 2003/08/06 18:20:51 cheshire
123 Revision 1.20 2003/08/05 23:56:26 cheshire
124 Update code to compile with the new mDNSCoreReceive() function that requires a TTL
125 (Right now mDNSPosix.c just reports 255 -- we should fix this)
127 Revision 1.19 2003/07/19 03:15:16 cheshire
128 Add generic MemAllocate/MemFree prototypes to mDNSPlatformFunctions.h,
129 and add the obvious trivial implementations to each platform support layer
131 Revision 1.18 2003/07/14 18:11:54 cheshire
132 Fix stricter compiler warnings
134 Revision 1.17 2003/07/13 01:08:38 cheshire
135 There's not much point running mDNS over a point-to-point link; exclude those
137 Revision 1.16 2003/07/02 21:19:59 cheshire
138 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
140 Revision 1.15 2003/06/18 05:48:41 cheshire
143 Revision 1.14 2003/05/26 03:21:30 cheshire
144 Tidy up address structure naming:
145 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
146 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
147 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
149 Revision 1.13 2003/05/26 03:01:28 cheshire
150 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
152 Revision 1.12 2003/05/21 03:49:18 cheshire
155 Revision 1.11 2003/05/06 00:00:50 cheshire
156 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
158 Revision 1.10 2003/04/25 01:45:57 cheshire
159 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
161 Revision 1.9 2003/03/20 21:10:31 cheshire
162 Fixes done at IETF 56 to make mDNSProxyResponderPosix run on Solaris
164 Revision 1.8 2003/03/15 04:40:38 cheshire
165 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
167 Revision 1.7 2003/03/13 03:46:21 cheshire
168 Fixes to make the code build on Linux
170 Revision 1.6 2003/03/08 00:35:56 cheshire
171 Switched to using new "mDNS_Execute" model (see "mDNSCore/Implementer Notes.txt")
173 Revision 1.5 2002/12/23 22:13:31 jgraessl
174 Reviewed by: Stuart Cheshire
175 Initial IPv6 support for mDNSResponder.
177 Revision 1.4 2002/09/27 01:47:45 cheshire
178 Workaround for Linux 2.0 systems that don't have IP_PKTINFO
180 Revision 1.3 2002/09/21 20:44:53 zarzycki
183 Revision 1.2 2002/09/19 21:25:36 cheshire
184 mDNS_snprintf() doesn't need to be in a separate file
186 Revision 1.1 2002/09/17 06:24:34 cheshire
190 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
191 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
202 #include <sys/types.h>
203 #include <sys/time.h>
204 #include <sys/socket.h>
206 #include <sys/select.h>
207 #include <netinet/in.h>
208 #include <time.h> // platform support for UTC time
211 #include <asm/types.h>
212 #include <linux/netlink.h>
213 #include <linux/rtnetlink.h>
214 #else // USES_NETLINK
215 #include <net/route.h>
217 #endif // USES_NETLINK
220 #include "GenLinkedList.h"
222 // ***************************************************************************
225 // We keep a list of client-supplied event sources in PosixEventSource records
226 struct PosixEventSource
228 mDNSPosixEventCallback Callback
;
231 struct PosixEventSource
*Next
;
233 typedef struct PosixEventSource PosixEventSource
;
235 // Context record for interface change callback
241 typedef struct IfChangeRec IfChangeRec
;
243 // Note that static data is initialized to zero in (modern) C.
244 static fd_set gEventFDs
;
245 static int gMaxFD
; // largest fd in gEventFDs
246 static GenLinkedList gEventSources
; // linked list of PosixEventSource's
247 static sigset_t gEventSignalSet
; // Signals which event loop listens for
248 static sigset_t gEventSignals
; // Signals which were received while inside loop
250 // ***************************************************************************
251 // Globals (for debugging)
253 static int num_registered_interfaces
= 0;
254 static int num_pkts_accepted
= 0;
255 static int num_pkts_rejected
= 0;
257 // ***************************************************************************
260 int gMDNSPlatformPosixVerboseLevel
= 0;
262 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
264 static void SockAddrTomDNSAddr(const struct sockaddr
*const sa
, mDNSAddr
*ipAddr
, mDNSIPPort
*ipPort
)
266 switch (sa
->sa_family
)
270 struct sockaddr_in
* sin
= (struct sockaddr_in
*)sa
;
271 ipAddr
->type
= mDNSAddrType_IPv4
;
272 ipAddr
->ip
.v4
.NotAnInteger
= sin
->sin_addr
.s_addr
;
273 if (ipPort
) ipPort
->NotAnInteger
= sin
->sin_port
;
280 struct sockaddr_in6
* sin6
= (struct sockaddr_in6
*)sa
;
281 assert(sin6
->sin6_len
== sizeof(*sin6
));
282 ipAddr
->type
= mDNSAddrType_IPv6
;
283 ipAddr
->ip
.v6
= *(mDNSv6Addr
*)&sin6
->sin6_addr
;
284 if (ipPort
) ipPort
->NotAnInteger
= sin6
->sin6_port
;
290 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa
->sa_family
);
291 ipAddr
->type
= mDNSAddrType_None
;
292 if (ipPort
) ipPort
->NotAnInteger
= 0;
297 #if COMPILER_LIKES_PRAGMA_MARK
298 #pragma mark ***** Send and Receive
301 // mDNS core calls this routine when it needs to send a packet.
302 mDNSexport mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const DNSMessage
*const msg
, const mDNSu8
*const end
,
303 mDNSInterfaceID InterfaceID
, const mDNSAddr
*dst
, mDNSIPPort dstPort
)
306 struct sockaddr_storage to
;
307 PosixNetworkInterface
* thisIntf
= (PosixNetworkInterface
*)(InterfaceID
);
308 int sendingsocket
= -1;
313 assert( (((char *) end
) - ((char *) msg
)) > 0 );
314 assert(dstPort
.NotAnInteger
!= 0);
316 if (dst
->type
== mDNSAddrType_IPv4
)
318 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&to
;
319 #ifndef NOT_HAVE_SA_LEN
320 sin
->sin_len
= sizeof(*sin
);
322 sin
->sin_family
= AF_INET
;
323 sin
->sin_port
= dstPort
.NotAnInteger
;
324 sin
->sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
325 sendingsocket
= thisIntf
? thisIntf
->multicastSocket4
: m
->p
->unicastSocket4
;
329 else if (dst
->type
== mDNSAddrType_IPv6
)
331 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&to
;
332 mDNSPlatformMemZero(sin6
, sizeof(*sin6
));
333 sin6
->sin6_len
= sizeof(*sin6
);
334 sin6
->sin6_family
= AF_INET6
;
335 sin6
->sin6_port
= dstPort
.NotAnInteger
;
336 sin6
->sin6_addr
= *(struct in6_addr
*)&dst
->ip
.v6
;
337 sendingsocket
= thisIntf
? thisIntf
->multicastSocket6
: m
->p
->unicastSocket6
;
341 if (sendingsocket
>= 0)
342 err
= sendto(sendingsocket
, msg
, (char*)end
- (char*)msg
, 0, (struct sockaddr
*)&to
, GET_SA_LEN(to
));
344 if (err
> 0) err
= 0;
348 verbosedebugf("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
349 errno
, strerror(errno
), dst
, &thisIntf
->coreIntf
.ip
, thisIntf
->intfName
, thisIntf
->index
);
351 verbosedebugf("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno
, strerror(errno
), dst
);
354 return PosixErrorToStatus(err
);
357 // This routine is called when the main loop detects that data is available on a socket.
358 static void SocketDataReady(mDNS
*const m
, PosixNetworkInterface
*intf
, int skt
)
360 mDNSAddr senderAddr
, destAddr
;
361 mDNSIPPort senderPort
;
364 struct my_in_pktinfo packetInfo
;
365 struct sockaddr_storage from
;
370 const mDNSInterfaceID InterfaceID
= intf
? intf
->coreIntf
.InterfaceID
: NULL
;
375 fromLen
= sizeof(from
);
377 packetLen
= recvfrom_flags(skt
, &packet
, sizeof(packet
), &flags
, (struct sockaddr
*) &from
, &fromLen
, &packetInfo
, &ttl
);
381 SockAddrTomDNSAddr((struct sockaddr
*)&from
, &senderAddr
, &senderPort
);
382 SockAddrTomDNSAddr((struct sockaddr
*)&packetInfo
.ipi_addr
, &destAddr
, NULL
);
384 // If we have broken IP_RECVDSTADDR functionality (so far
385 // I've only seen this on OpenBSD) then apply a hack to
386 // convince mDNS Core that this isn't a spoof packet.
387 // Basically what we do is check to see whether the
388 // packet arrived as a multicast and, if so, set its
389 // destAddr to the mDNS address.
391 // I must admit that I could just be doing something
392 // wrong on OpenBSD and hence triggering this problem
393 // but I'm at a loss as to how.
395 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
396 // no way to tell the destination address or interface this packet arrived on,
397 // so all we can do is just assume it's a multicast
399 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
400 if ( (destAddr
.NotAnInteger
== 0) && (flags
& MSG_MCAST
) )
402 destAddr
.type
= senderAddr
.type
;
403 if (senderAddr
.type
== mDNSAddrType_IPv4
) destAddr
.ip
.v4
= AllDNSLinkGroup
;
404 else if (senderAddr
.type
== mDNSAddrType_IPv6
) destAddr
.ip
.v6
= AllDNSLinkGroupv6
;
408 // We only accept the packet if the interface on which it came
409 // in matches the interface associated with this socket.
410 // We do this match by name or by index, depending on which
411 // information is available. recvfrom_flags sets the name
412 // to "" if the name isn't available, or the index to -1
413 // if the index is available. This accomodates the various
414 // different capabilities of our target platforms.
419 if ( packetInfo
.ipi_ifname
[0] != 0 ) reject
= (strcmp(packetInfo
.ipi_ifname
, intf
->intfName
) != 0);
420 else if ( packetInfo
.ipi_ifindex
!= -1 ) reject
= (packetInfo
.ipi_ifindex
!= intf
->index
);
424 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d",
425 &senderAddr
, &destAddr
, packetInfo
.ipi_ifname
, packetInfo
.ipi_ifindex
,
426 &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
);
429 if (num_pkts_rejected
> (num_pkts_accepted
+ 1) * (num_registered_interfaces
+ 1) * 2)
432 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
433 num_pkts_accepted
+ num_pkts_rejected
, num_pkts_accepted
, num_pkts_rejected
);
434 num_pkts_accepted
= 0;
435 num_pkts_rejected
= 0;
440 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d",
441 &senderAddr
, &destAddr
, &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
);
447 if (packetLen
>= 0 && packetLen
< (ssize_t
)sizeof(DNSMessageHeader
))
449 debugf("SocketDataReady packet length (%d) too short", packetLen
);
454 mDNSCoreReceive(m
, &packet
, (mDNSu8
*)&packet
+ packetLen
,
455 &senderAddr
, senderPort
, &destAddr
, MulticastDNSPort
, InterfaceID
, ttl
);
458 mDNSexport mStatus
mDNSPlatformTCPConnect(const mDNSAddr
*dst
, mDNSOpaque16 dstport
, mDNSInterfaceID InterfaceID
,
459 TCPConnectionCallback callback
, void *context
, int *descriptor
)
462 (void)dstport
; // Unused
463 (void)InterfaceID
; // Unused
464 (void)callback
; // Unused
465 (void)context
; // Unused
466 (void)descriptor
; // Unused
467 return(mStatus_UnsupportedErr
);
470 mDNSexport
void mDNSPlatformTCPCloseConnection(int sd
)
475 mDNSexport
int mDNSPlatformReadTCP(int sd
, void *buf
, int buflen
)
479 (void)buflen
; // Unused
483 mDNSexport
int mDNSPlatformWriteTCP(int sd
, const char *msg
, int len
)
491 #if COMPILER_LIKES_PRAGMA_MARK
492 #pragma mark ***** Get/Free Search Domain List
495 mDNSexport DNameListElem
*mDNSPlatformGetSearchDomainList(void)
497 static DNameListElem tmp
;
498 static mDNSBool init
= mDNSfalse
;
502 MakeDomainNameFromDNSNameString(&tmp
.name
, "local.");
506 return mDNS_CopyDNameList(&tmp
);
509 #if COMPILER_LIKES_PRAGMA_MARK
510 #pragma mark ***** Init and Term
513 // This gets the current hostname, truncating it at the first dot if necessary
514 mDNSlocal
void GetUserSpecifiedRFC1034ComputerName(domainlabel
*const namelabel
)
517 gethostname((char *)(&namelabel
->c
[1]), MAX_DOMAIN_LABEL
);
518 while (len
< MAX_DOMAIN_LABEL
&& namelabel
->c
[len
+1] && namelabel
->c
[len
+1] != '.') len
++;
519 namelabel
->c
[0] = len
;
522 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
523 // Other platforms can either get the information from the appropriate place,
524 // or they can alternatively just require all registering services to provide an explicit name
525 mDNSlocal
void GetUserSpecifiedFriendlyComputerName(domainlabel
*const namelabel
)
527 // On Unix we have no better name than the host name, so we just use that.
528 GetUserSpecifiedRFC1034ComputerName( namelabel
);
531 // Searches the interface list looking for the named interface.
532 // Returns a pointer to if it found, or NULL otherwise.
533 static PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
535 PosixNetworkInterface
*intf
;
538 assert(intfName
!= NULL
);
540 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
541 while ( (intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0) )
542 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
547 extern mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(const mDNS
*const m
, mDNSu32 index
)
549 PosixNetworkInterface
*intf
;
553 if (index
== (uint32_t)~0) return(mDNSInterface_LocalOnly
);
555 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
556 while ( (intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
557 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
559 return (mDNSInterfaceID
) intf
;
562 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(const mDNS
*const m
, mDNSInterfaceID id
)
564 PosixNetworkInterface
*intf
;
568 if (id
== mDNSInterface_LocalOnly
) return((mDNSu32
)~0);
570 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
571 while ( (intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
572 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
574 return intf
? intf
->index
: 0;
577 // Frees the specified PosixNetworkInterface structure. The underlying
578 // interface must have already been deregistered with the mDNS core.
579 static void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
581 assert(intf
!= NULL
);
582 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
583 if (intf
->multicastSocket4
!= -1) assert(close(intf
->multicastSocket4
) == 0);
585 if (intf
->multicastSocket6
!= -1) assert(close(intf
->multicastSocket6
) == 0);
590 // Grab the first interface, deregister it, free it, and repeat until done.
591 static void ClearInterfaceList(mDNS
*const m
)
595 while (m
->HostInterfaces
)
597 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
598 mDNS_DeregisterInterface(m
, &intf
->coreIntf
);
599 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
600 FreePosixNetworkInterface(intf
);
602 num_registered_interfaces
= 0;
603 num_pkts_accepted
= 0;
604 num_pkts_rejected
= 0;
607 // Sets up a send/receive socket.
608 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
609 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
610 static int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
613 static const int kOn
= 1;
614 static const int kIntTwoFiveFive
= 255;
615 static const unsigned char kByteTwoFiveFive
= 255;
617 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
618 assert(intfAddr
!= NULL
);
619 assert(sktPtr
!= NULL
);
620 assert(*sktPtr
== -1);
622 // Open the socket...
623 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
625 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
629 if (*sktPtr
< 0) { err
= errno
; perror("socket"); }
631 // ... with a shared UDP port, if it's for multicast receiving
632 if (err
== 0 && port
.NotAnInteger
)
634 #if defined(SO_REUSEPORT)
635 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
636 #elif defined(SO_REUSEADDR)
637 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
639 #error This platform has no way to avoid address busy errors on multicast.
641 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
644 // We want to receive destination addresses and interface identifiers.
645 if (intfAddr
->sa_family
== AF_INET
)
648 struct sockaddr_in bindAddr
;
651 #if defined(IP_PKTINFO) // Linux
652 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
653 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
654 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
655 #if defined(IP_RECVDSTADDR)
656 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
657 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
659 #if defined(IP_RECVIF)
662 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
663 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
667 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
670 #if defined(IP_RECVTTL) // Linux
673 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
674 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVTTL"); }
678 // Add multicast group membership on this interface
679 if (err
== 0 && port
.NotAnInteger
)
681 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup
.NotAnInteger
;
682 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
683 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
684 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
687 // Specify outgoing interface too
688 if (err
== 0 && port
.NotAnInteger
)
690 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
691 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
694 // Per the mDNS spec, send unicast packets with TTL 255
697 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
698 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
701 // and multicast packets with TTL 255 too
702 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
705 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
706 if (err
< 0 && errno
== EINVAL
)
707 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
708 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
711 // And start listening for packets
714 bindAddr
.sin_family
= AF_INET
;
715 bindAddr
.sin_port
= port
.NotAnInteger
;
716 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
717 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
718 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
720 } // endif (intfAddr->sa_family == AF_INET)
723 else if (intfAddr
->sa_family
== AF_INET6
)
725 struct ipv6_mreq imr6
;
726 struct sockaddr_in6 bindAddr6
;
727 #if defined(IPV6_PKTINFO)
730 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_PKTINFO
, &kOn
, sizeof(kOn
));
731 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
734 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
736 #if defined(IPV6_HOPLIMIT)
739 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_HOPLIMIT
, &kOn
, sizeof(kOn
));
740 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
744 // Add multicast group membership on this interface
745 if (err
== 0 && port
.NotAnInteger
)
747 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroupv6
;
748 imr6
.ipv6mr_interface
= interfaceIndex
;
749 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
753 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
754 perror("setsockopt - IPV6_JOIN_GROUP");
758 // Specify outgoing interface too
759 if (err
== 0 && port
.NotAnInteger
)
761 u_int multicast_if
= interfaceIndex
;
762 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
763 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
766 // We want to receive only IPv6 packets on this socket.
767 // Without this option, we may get IPv4 addresses as mapped addresses.
770 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
771 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
774 // Per the mDNS spec, send unicast packets with TTL 255
777 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
778 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
781 // and multicast packets with TTL 255 too
782 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
785 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
786 if (err
< 0 && errno
== EINVAL
)
787 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
788 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
791 // And start listening for packets
794 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
795 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
796 bindAddr6
.sin6_family
= AF_INET6
;
797 bindAddr6
.sin6_port
= port
.NotAnInteger
;
798 bindAddr6
.sin6_flowinfo
= 0;
799 // bindAddr6.sin6_addr.s_addr = IN6ADDR_ANY_INIT; // Want to receive multicasts AND unicasts on this socket
800 bindAddr6
.sin6_scope_id
= 0;
801 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
802 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
804 } // endif (intfAddr->sa_family == AF_INET6)
807 // Set the socket to non-blocking.
810 err
= fcntl(*sktPtr
, F_GETFL
, 0);
811 if (err
< 0) err
= errno
;
814 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
815 if (err
< 0) err
= errno
;
820 if (err
!= 0 && *sktPtr
!= -1) { assert(close(*sktPtr
) == 0); *sktPtr
= -1; }
821 assert( (err
== 0) == (*sktPtr
!= -1) );
825 // Creates a PosixNetworkInterface for the interface whose IP address is
826 // intfAddr and whose name is intfName and registers it with mDNS core.
827 static int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, const char *intfName
)
830 PosixNetworkInterface
*intf
;
831 PosixNetworkInterface
*alias
= NULL
;
834 assert(intfAddr
!= NULL
);
835 assert(intfName
!= NULL
);
837 // Allocate the interface structure itself.
838 intf
= (PosixNetworkInterface
*)malloc(sizeof(*intf
));
839 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
841 // And make a copy of the intfName.
844 intf
->intfName
= strdup(intfName
);
845 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
850 // Set up the fields required by the mDNS core.
851 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
852 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
853 intf
->coreIntf
.McastTxRx
= mDNStrue
;
855 // Set up the extra fields in PosixNetworkInterface.
856 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
857 intf
->index
= if_nametoindex(intf
->intfName
);
858 intf
->multicastSocket4
= -1;
860 intf
->multicastSocket6
= -1;
862 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
863 if (alias
== NULL
) alias
= intf
;
864 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
867 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
870 // Set up the multicast socket
873 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
874 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
876 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
877 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
881 // The interface is all ready to go, let's register it with the mDNS core.
883 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
);
888 num_registered_interfaces
++;
889 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
890 if (gMDNSPlatformPosixVerboseLevel
> 0)
891 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
895 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
896 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
897 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
900 assert( (err
== 0) == (intf
!= NULL
) );
905 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
906 static int SetupInterfaceList(mDNS
*const m
)
908 mDNSBool foundav4
= mDNSfalse
;
910 struct ifi_info
*intfList
= get_ifi_info(AF_INET
, mDNStrue
);
911 struct ifi_info
*firstLoopback
= NULL
;
914 debugf("SetupInterfaceList");
916 if (intfList
== NULL
) err
= ENOENT
;
919 if (err
== 0) /* Link the IPv6 list to the end of the IPv4 list */
921 struct ifi_info
**p
= &intfList
;
922 while (*p
) p
= &(*p
)->ifi_next
;
923 *p
= get_ifi_info(AF_INET6
, mDNStrue
);
929 struct ifi_info
*i
= intfList
;
932 if ( ((i
->ifi_addr
->sa_family
== AF_INET
)
934 || (i
->ifi_addr
->sa_family
== AF_INET6
)
936 ) && (i
->ifi_flags
& IFF_UP
) && !(i
->ifi_flags
& IFF_POINTOPOINT
) )
938 if (i
->ifi_flags
& IFF_LOOPBACK
)
940 if (firstLoopback
== NULL
)
945 if (SetupOneInterface(m
, i
->ifi_addr
, i
->ifi_name
) == 0)
946 if (i
->ifi_addr
->sa_family
== AF_INET
)
953 // If we found no normal interfaces but we did find a loopback interface, register the
954 // loopback interface. This allows self-discovery if no interfaces are configured.
955 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
956 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
957 // if ( (m->HostInterfaces == NULL) && (firstLoopback != NULL) )
958 if ( !foundav4
&& firstLoopback
)
959 (void) SetupOneInterface(m
, firstLoopback
->ifi_addr
, firstLoopback
->ifi_name
);
963 if (intfList
!= NULL
) free_ifi_info(intfList
);
969 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
971 // Open a socket that will receive interface change notifications
972 mStatus
OpenIfNotifySocket( int *pFD
)
974 mStatus err
= mStatus_NoError
;
975 struct sockaddr_nl snl
;
979 sock
= socket( AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
983 // Configure read to be non-blocking because inbound msg size is not known in advance
984 (void) fcntl( sock
, F_SETFL
, O_NONBLOCK
);
986 /* Subscribe the socket to Link & IP addr notifications. */
987 bzero( &snl
, sizeof snl
);
988 snl
.nl_family
= AF_NETLINK
;
989 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
990 ret
= bind( sock
, (struct sockaddr
*) &snl
, sizeof snl
);
1000 static void PrintNetLinkMsg( const struct nlmsghdr
*pNLMsg
)
1002 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1003 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1005 printf( "nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
1006 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[ pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[ pNLMsg
->nlmsg_type
- RTM_BASE
],
1007 pNLMsg
->nlmsg_flags
);
1009 if ( RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
1011 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA( pNLMsg
);
1012 printf( "ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
1013 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
1016 else if ( RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
1018 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA( pNLMsg
);
1019 printf( "ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
1020 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1026 static uint32_t ProcessRoutingNotification( int sd
)
1027 // Read through the messages on sd and if any indicate that any interface records should
1028 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1032 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1033 uint32_t result
= 0;
1035 // The structure here is more complex than it really ought to be because,
1036 // unfortunately, there's no good way to size a buffer in advance large
1037 // enough to hold all pending data and so avoid message fragmentation.
1038 // (Note that FIONREAD is not supported on AF_NETLINK.)
1040 readCount
= read( sd
, buff
, sizeof buff
);
1043 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1044 // If not, discard already-processed messages in buffer and read more data.
1045 if ( ( (char*) &pNLMsg
[1] > ( buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1046 ( (char*) pNLMsg
+ pNLMsg
->nlmsg_len
> ( buff
+ readCount
)))
1048 if ( buff
< (char*) pNLMsg
) // we have space to shuffle
1050 // discard processed data
1051 readCount
-= ( (char*) pNLMsg
- buff
);
1052 memmove( buff
, pNLMsg
, readCount
);
1053 pNLMsg
= (struct nlmsghdr
*) buff
;
1056 readCount
+= read( sd
, buff
+ readCount
, sizeof buff
- readCount
);
1057 continue; // spin around and revalidate with new readCount
1060 break; // Otherwise message does not fit in buffer
1064 PrintNetLinkMsg( pNLMsg
);
1067 // Process the NetLink message
1068 if ( pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1069 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA( pNLMsg
))->ifi_index
;
1070 else if ( pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1071 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA( pNLMsg
))->ifa_index
;
1073 // Advance pNLMsg to the next message in the buffer
1074 if ( ( pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1076 ssize_t len
= readCount
- ( (char*)pNLMsg
- buff
);
1077 pNLMsg
= NLMSG_NEXT( pNLMsg
, len
);
1086 #else // USES_NETLINK
1088 // Open a socket that will receive interface change notifications
1089 mStatus
OpenIfNotifySocket( int *pFD
)
1091 *pFD
= socket( AF_ROUTE
, SOCK_RAW
, 0);
1094 return mStatus_UnknownErr
;
1096 // Configure read to be non-blocking because inbound msg size is not known in advance
1097 (void) fcntl( *pFD
, F_SETFL
, O_NONBLOCK
);
1099 return mStatus_NoError
;
1103 static void PrintRoutingSocketMsg( const struct ifa_msghdr
*pRSMsg
)
1105 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1106 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1107 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1109 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1111 printf( "ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[ pRSMsg
->ifam_type
], index
);
1115 static uint32_t ProcessRoutingNotification( int sd
)
1116 // Read through the messages on sd and if any indicate that any interface records should
1117 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1121 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1122 uint32_t result
= 0;
1124 readCount
= read( sd
, buff
, sizeof buff
);
1125 if ( readCount
< (ssize_t
) sizeof( struct ifa_msghdr
))
1126 return mStatus_UnsupportedErr
; // cannot decipher message
1129 PrintRoutingSocketMsg( pRSMsg
);
1132 // Process the message
1133 if ( pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1134 pRSMsg
->ifam_type
== RTM_IFINFO
)
1136 if ( pRSMsg
->ifam_type
== RTM_IFINFO
)
1137 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1139 result
|= 1 << pRSMsg
->ifam_index
;
1145 #endif // USES_NETLINK
1147 // Called when data appears on interface change notification socket
1148 static void InterfaceChangeCallback( void *context
)
1150 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1152 uint32_t changedInterfaces
= 0;
1153 struct timeval zeroTimeout
= { 0, 0 };
1156 FD_SET( pChgRec
->NotifySD
, &readFDs
);
1160 changedInterfaces
|= ProcessRoutingNotification( pChgRec
->NotifySD
);
1162 while ( 0 < select( pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1164 // Currently we rebuild the entire interface list whenever any interface change is
1165 // detected. If this ever proves to be a performance issue in a multi-homed
1166 // configuration, more care should be paid to changedInterfaces.
1167 if ( changedInterfaces
)
1168 mDNSPlatformPosixRefreshInterfaceList( pChgRec
->mDNS
);
1171 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1172 static mStatus
WatchForInterfaceChange(mDNS
*const m
)
1175 IfChangeRec
*pChgRec
;
1177 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocate( sizeof *pChgRec
);
1178 if ( pChgRec
== NULL
)
1179 return mStatus_NoMemoryErr
;
1182 err
= OpenIfNotifySocket( &pChgRec
->NotifySD
);
1184 err
= mDNSPosixAddFDToEventLoop( pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1189 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1190 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1191 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1192 mDNSlocal mDNSBool
mDNSPlatformInit_ReceiveUnicast(void)
1195 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1196 struct sockaddr_in s5353
;
1197 s5353
.sin_family
= AF_INET
;
1198 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1199 s5353
.sin_addr
.s_addr
= 0;
1200 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1202 if (err
) debugf("No unicast UDP responses");
1203 else debugf("Unicast UDP responses okay");
1207 // mDNS core calls this routine to initialise the platform-specific data.
1208 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1214 if (mDNSPlatformInit_ReceiveUnicast()) m
->CanReceiveUnicast
= mDNStrue
;
1216 // Tell mDNS core the names of this machine.
1218 // Set up the nice label
1219 m
->nicelabel
.c
[0] = 0;
1220 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1221 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Macintosh");
1223 // Set up the RFC 1034-compliant label
1224 m
->hostlabel
.c
[0] = 0;
1225 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1226 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Macintosh");
1228 mDNS_GenerateFQDN(m
);
1230 sa
.sa_family
= AF_INET
;
1231 m
->p
->unicastSocket4
= -1;
1232 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1234 sa
.sa_family
= AF_INET6
;
1235 m
->p
->unicastSocket6
= -1;
1236 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1239 // Tell mDNS core about the network interfaces on this machine.
1240 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1242 if (err
== mStatus_NoError
)
1244 err
= WatchForInterfaceChange(m
);
1245 // Failure to observe interface changes is non-fatal.
1246 if ( err
!= mStatus_NoError
)
1248 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1249 err
= mStatus_NoError
;
1253 // We don't do asynchronous initialization on the Posix platform, so by the time
1254 // we get here the setup will already have succeeded or failed. If it succeeded,
1255 // we should just call mDNSCoreInitComplete() immediately.
1256 if (err
== mStatus_NoError
)
1257 mDNSCoreInitComplete(m
, mStatus_NoError
);
1259 return PosixErrorToStatus(err
);
1262 // mDNS core calls this routine to clean up the platform-specific data.
1263 // In our case all we need to do is to tear down every network interface.
1264 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1267 ClearInterfaceList(m
);
1268 if (m
->p
->unicastSocket4
!= -1) assert(close(m
->p
->unicastSocket4
) == 0);
1270 if (m
->p
->unicastSocket6
!= -1) assert(close(m
->p
->unicastSocket6
) == 0);
1274 extern mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1277 ClearInterfaceList(m
);
1278 err
= SetupInterfaceList(m
);
1279 return PosixErrorToStatus(err
);
1282 #if COMPILER_LIKES_PRAGMA_MARK
1283 #pragma mark ***** Locking
1286 // On the Posix platform, locking is a no-op because we only ever enter
1287 // mDNS core on the main thread.
1289 // mDNS core calls this routine when it wants to prevent
1290 // the platform from reentering mDNS core code.
1291 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1296 // mDNS core calls this routine when it release the lock taken by
1297 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1298 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1303 #if COMPILER_LIKES_PRAGMA_MARK
1304 #pragma mark ***** Strings
1307 // mDNS core calls this routine to copy C strings.
1308 // On the Posix platform this maps directly to the ANSI C strcpy.
1309 mDNSexport
void mDNSPlatformStrCopy(const void *src
, void *dst
)
1311 strcpy((char *)dst
, (char *)src
);
1314 // mDNS core calls this routine to get the length of a C string.
1315 // On the Posix platform this maps directly to the ANSI C strlen.
1316 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1318 return strlen((char*)src
);
1321 // mDNS core calls this routine to copy memory.
1322 // On the Posix platform this maps directly to the ANSI C memcpy.
1323 mDNSexport
void mDNSPlatformMemCopy(const void *src
, void *dst
, mDNSu32 len
)
1325 memcpy(dst
, src
, len
);
1328 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1329 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1330 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *src
, const void *dst
, mDNSu32 len
)
1332 return memcmp(dst
, src
, len
) == 0;
1335 // mDNS core calls this routine to clear blocks of memory.
1336 // On the Posix platform this is a simple wrapper around ANSI C memset.
1337 mDNSexport
void mDNSPlatformMemZero( void *dst
, mDNSu32 len
)
1339 memset(dst
, 0, len
);
1342 mDNSexport
void * mDNSPlatformMemAllocate(mDNSu32 len
) { return(malloc(len
)); }
1343 mDNSexport
void mDNSPlatformMemFree (void *mem
) { free(mem
); }
1345 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1347 mDNSexport mStatus
mDNSPlatformTimeInit(mDNSs32
*timenow
)
1349 // No special setup is required on Posix -- we just use gettimeofday();
1350 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1351 // We should find a better way to do this
1352 *timenow
= mDNSPlatformTimeNow();
1353 return(mStatus_NoError
);
1356 mDNSexport mDNSs32
mDNSPlatformTimeNow()
1359 gettimeofday(&tv
, NULL
);
1360 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1361 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1362 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1363 // 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.
1364 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1365 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1366 return( (tv
.tv_sec
<< 10) | (tv
.tv_usec
* 16 / 15625) );
1369 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1374 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
1376 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
1380 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, struct timeval
*timeout
)
1383 struct timeval interval
;
1385 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1386 mDNSs32 nextevent
= mDNS_Execute(m
);
1388 // 2. Build our list of active file descriptors
1389 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1390 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket4
);
1392 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket6
);
1396 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket4
);
1398 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket6
);
1400 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1403 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1404 ticks
= nextevent
- mDNSPlatformTimeNow();
1405 if (ticks
< 1) ticks
= 1;
1406 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
1407 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1409 // 4. If client's proposed timeout is more than what we want, then reduce it
1410 if (timeout
->tv_sec
> interval
.tv_sec
||
1411 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
1412 *timeout
= interval
;
1415 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
)
1417 PosixNetworkInterface
*info
;
1419 assert(readfds
!= NULL
);
1420 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1422 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
1424 FD_CLR(m
->p
->unicastSocket4
, readfds
);
1425 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
1428 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
1430 FD_CLR(m
->p
->unicastSocket6
, readfds
);
1431 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
1437 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
1439 FD_CLR(info
->multicastSocket4
, readfds
);
1440 SocketDataReady(m
, info
, info
->multicastSocket4
);
1443 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
1445 FD_CLR(info
->multicastSocket6
, readfds
);
1446 SocketDataReady(m
, info
, info
->multicastSocket6
);
1449 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1454 static void DetermineMaxEventFD( void )
1456 PosixEventSource
*iSource
;
1459 for ( iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1460 if ( gMaxFD
< iSource
->fd
)
1461 gMaxFD
= iSource
->fd
;
1464 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1465 mStatus
mDNSPosixAddFDToEventLoop( int fd
, mDNSPosixEventCallback callback
, void *context
)
1467 PosixEventSource
*newSource
;
1469 if ( gEventSources
.LinkOffset
== 0)
1470 InitLinkedList( &gEventSources
, offsetof( PosixEventSource
, Next
));
1472 if ( fd
>= (int) FD_SETSIZE
|| fd
< 0)
1473 return mStatus_UnsupportedErr
;
1474 if ( callback
== NULL
)
1475 return mStatus_BadParamErr
;
1477 newSource
= (PosixEventSource
*) malloc( sizeof *newSource
);
1478 if ( NULL
== newSource
)
1479 return mStatus_NoMemoryErr
;
1481 newSource
->Callback
= callback
;
1482 newSource
->Context
= context
;
1485 AddToTail( &gEventSources
, newSource
);
1486 FD_SET( fd
, &gEventFDs
);
1488 DetermineMaxEventFD();
1490 return mStatus_NoError
;
1493 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1494 mStatus
mDNSPosixRemoveFDFromEventLoop( int fd
)
1496 PosixEventSource
*iSource
;
1498 for ( iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1500 if ( fd
== iSource
->fd
)
1502 FD_CLR( fd
, &gEventFDs
);
1503 RemoveFromList( &gEventSources
, iSource
);
1505 DetermineMaxEventFD();
1506 return mStatus_NoError
;
1509 return mStatus_NoSuchNameErr
;
1512 // Simply note the received signal in gEventSignals.
1513 static void NoteSignal( int signum
)
1515 sigaddset( &gEventSignals
, signum
);
1518 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1519 mStatus
mDNSPosixListenForSignalInEventLoop( int signum
)
1521 struct sigaction action
;
1524 bzero( &action
, sizeof action
); // more portable than member-wise assignment
1525 action
.sa_handler
= NoteSignal
;
1526 err
= sigaction( signum
, &action
, (struct sigaction
*) NULL
);
1528 sigaddset( &gEventSignalSet
, signum
);
1533 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1534 mStatus
mDNSPosixIgnoreSignalInEventLoop( int signum
)
1536 struct sigaction action
;
1539 bzero( &action
, sizeof action
); // more portable than member-wise assignment
1540 action
.sa_handler
= SIG_DFL
;
1541 err
= sigaction( signum
, &action
, (struct sigaction
*) NULL
);
1543 sigdelset( &gEventSignalSet
, signum
);
1548 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1549 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1550 mStatus
mDNSPosixRunEventLoopOnce( mDNS
*m
, const struct timeval
*pTimeout
,
1551 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
1553 fd_set listenFDs
= gEventFDs
;
1554 int fdMax
= 0, numReady
;
1555 struct timeval timeout
= *pTimeout
;
1557 // Include the sockets that are listening to the wire in our select() set
1558 mDNSPosixGetFDSet( m
, &fdMax
, &listenFDs
, &timeout
); // timeout may get modified
1559 if ( fdMax
< gMaxFD
)
1562 numReady
= select( fdMax
+ 1, &listenFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &timeout
);
1564 // If any data appeared, invoke its callback
1567 PosixEventSource
*iSource
;
1569 (void) mDNSPosixProcessFDSet( m
, &listenFDs
); // call this first to process wire data for clients
1571 for ( iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1573 if ( FD_ISSET( iSource
->fd
, &listenFDs
))
1575 iSource
->Callback( iSource
->Context
);
1576 break; // in case callback removed elements from gEventSources
1579 *pDataDispatched
= mDNStrue
;
1582 *pDataDispatched
= mDNSfalse
;
1584 (void) sigprocmask( SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1585 *pSignalsReceived
= gEventSignals
;
1586 sigemptyset( &gEventSignals
);
1587 (void) sigprocmask( SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1589 return mStatus_NoError
;