1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2004 Apple Computer, 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
35 #include <sys/types.h>
37 #include <sys/socket.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
45 #include <asm/types.h>
46 #include <linux/netlink.h>
47 #include <linux/rtnetlink.h>
49 #include <net/route.h>
51 #endif // USES_NETLINK
54 #include "GenLinkedList.h"
56 // ***************************************************************************
59 // We keep a list of client-supplied event sources in PosixEventSource records
60 struct PosixEventSource
62 mDNSPosixEventCallback Callback
;
65 struct PosixEventSource
*Next
;
67 typedef struct PosixEventSource PosixEventSource
;
69 // Context record for interface change callback
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 // ***************************************************************************
85 // Globals (for debugging)
87 static int num_registered_interfaces
= 0;
88 static int num_pkts_accepted
= 0;
89 static int num_pkts_rejected
= 0;
91 // ***************************************************************************
94 int gMDNSPlatformPosixVerboseLevel
= 0;
96 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
98 mDNSlocal
void SockAddrTomDNSAddr(const struct sockaddr
*const sa
, mDNSAddr
*ipAddr
, mDNSIPPort
*ipPort
)
100 switch (sa
->sa_family
)
104 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
105 ipAddr
->type
= mDNSAddrType_IPv4
;
106 ipAddr
->ip
.v4
.NotAnInteger
= sin
->sin_addr
.s_addr
;
107 if (ipPort
) ipPort
->NotAnInteger
= sin
->sin_port
;
114 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
115 #ifndef NOT_HAVE_SA_LEN
116 assert(sin6
->sin6_len
== sizeof(*sin6
));
118 ipAddr
->type
= mDNSAddrType_IPv6
;
119 ipAddr
->ip
.v6
= *(mDNSv6Addr
*)&sin6
->sin6_addr
;
120 if (ipPort
) ipPort
->NotAnInteger
= sin6
->sin6_port
;
126 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa
->sa_family
);
127 ipAddr
->type
= mDNSAddrType_None
;
128 if (ipPort
) ipPort
->NotAnInteger
= 0;
133 #if COMPILER_LIKES_PRAGMA_MARK
134 #pragma mark ***** Send and Receive
137 // mDNS core calls this routine when it needs to send a packet.
138 mDNSexport mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
139 mDNSInterfaceID InterfaceID
, UDPSocket
*src
, const mDNSAddr
*dst
,
140 mDNSIPPort dstPort
, mDNSBool useBackgroundTrafficClass
)
143 struct sockaddr_storage to
;
144 PosixNetworkInterface
* thisIntf
= (PosixNetworkInterface
*)(InterfaceID
);
145 int sendingsocket
= -1;
147 (void)src
; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
148 (void) useBackgroundTrafficClass
;
153 assert((((char *) end
) - ((char *) msg
)) > 0);
155 if (dstPort
.NotAnInteger
== 0)
157 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
158 return PosixErrorToStatus(EINVAL
);
160 if (dst
->type
== mDNSAddrType_IPv4
)
162 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&to
;
163 #ifndef NOT_HAVE_SA_LEN
164 sin
->sin_len
= sizeof(*sin
);
166 sin
->sin_family
= AF_INET
;
167 sin
->sin_port
= dstPort
.NotAnInteger
;
168 sin
->sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
169 sendingsocket
= thisIntf
? thisIntf
->multicastSocket4
: m
->p
->unicastSocket4
;
173 else if (dst
->type
== mDNSAddrType_IPv6
)
175 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&to
;
176 mDNSPlatformMemZero(sin6
, sizeof(*sin6
));
177 #ifndef NOT_HAVE_SA_LEN
178 sin6
->sin6_len
= sizeof(*sin6
);
180 sin6
->sin6_family
= AF_INET6
;
181 sin6
->sin6_port
= dstPort
.NotAnInteger
;
182 sin6
->sin6_addr
= *(struct in6_addr
*)&dst
->ip
.v6
;
183 sendingsocket
= thisIntf
? thisIntf
->multicastSocket6
: m
->p
->unicastSocket6
;
187 if (sendingsocket
>= 0)
188 err
= sendto(sendingsocket
, msg
, (char*)end
- (char*)msg
, 0, (struct sockaddr
*)&to
, GET_SA_LEN(to
));
190 if (err
> 0) err
= 0;
193 static int MessageCount
= 0;
194 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
195 if (!mDNSAddressIsAllDNSLinkGroup(dst
))
196 if (errno
== EHOSTDOWN
|| errno
== ENETDOWN
|| errno
== EHOSTUNREACH
|| errno
== ENETUNREACH
) return(mStatus_TransientErr
);
198 if (MessageCount
< 1000)
202 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
203 errno
, strerror(errno
), dst
, &thisIntf
->coreIntf
.ip
, thisIntf
->intfName
, thisIntf
->index
);
205 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno
, strerror(errno
), dst
);
209 return PosixErrorToStatus(err
);
212 // This routine is called when the main loop detects that data is available on a socket.
213 mDNSlocal
void SocketDataReady(mDNS
*const m
, PosixNetworkInterface
*intf
, int skt
)
215 mDNSAddr senderAddr
, destAddr
;
216 mDNSIPPort senderPort
;
219 struct my_in_pktinfo packetInfo
;
220 struct sockaddr_storage from
;
225 const mDNSInterfaceID InterfaceID
= intf
? intf
->coreIntf
.InterfaceID
: NULL
;
230 fromLen
= sizeof(from
);
232 packetLen
= recvfrom_flags(skt
, &packet
, sizeof(packet
), &flags
, (struct sockaddr
*) &from
, &fromLen
, &packetInfo
, &ttl
);
236 SockAddrTomDNSAddr((struct sockaddr
*)&from
, &senderAddr
, &senderPort
);
237 SockAddrTomDNSAddr((struct sockaddr
*)&packetInfo
.ipi_addr
, &destAddr
, NULL
);
239 // If we have broken IP_RECVDSTADDR functionality (so far
240 // I've only seen this on OpenBSD) then apply a hack to
241 // convince mDNS Core that this isn't a spoof packet.
242 // Basically what we do is check to see whether the
243 // packet arrived as a multicast and, if so, set its
244 // destAddr to the mDNS address.
246 // I must admit that I could just be doing something
247 // wrong on OpenBSD and hence triggering this problem
248 // but I'm at a loss as to how.
250 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
251 // no way to tell the destination address or interface this packet arrived on,
252 // so all we can do is just assume it's a multicast
254 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
255 if ((destAddr
.NotAnInteger
== 0) && (flags
& MSG_MCAST
))
257 destAddr
.type
= senderAddr
.type
;
258 if (senderAddr
.type
== mDNSAddrType_IPv4
) destAddr
.ip
.v4
= AllDNSLinkGroup_v4
.ip
.v4
;
259 else if (senderAddr
.type
== mDNSAddrType_IPv6
) destAddr
.ip
.v6
= AllDNSLinkGroup_v6
.ip
.v6
;
263 // We only accept the packet if the interface on which it came
264 // in matches the interface associated with this socket.
265 // We do this match by name or by index, depending on which
266 // information is available. recvfrom_flags sets the name
267 // to "" if the name isn't available, or the index to -1
268 // if the index is available. This accomodates the various
269 // different capabilities of our target platforms.
274 // Ignore multicasts accidentally delivered to our unicast receiving socket
275 if (mDNSAddrIsDNSMulticast(&destAddr
)) packetLen
= -1;
279 if (packetInfo
.ipi_ifname
[0] != 0) reject
= (strcmp(packetInfo
.ipi_ifname
, intf
->intfName
) != 0);
280 else if (packetInfo
.ipi_ifindex
!= -1) reject
= (packetInfo
.ipi_ifindex
!= intf
->index
);
284 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
285 &senderAddr
, &destAddr
, packetInfo
.ipi_ifname
, packetInfo
.ipi_ifindex
,
286 &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
289 if (num_pkts_rejected
> (num_pkts_accepted
+ 1) * (num_registered_interfaces
+ 1) * 2)
292 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
293 num_pkts_accepted
+ num_pkts_rejected
, num_pkts_accepted
, num_pkts_rejected
);
294 num_pkts_accepted
= 0;
295 num_pkts_rejected
= 0;
300 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
301 &senderAddr
, &destAddr
, &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
308 mDNSCoreReceive(m
, &packet
, (mDNSu8
*)&packet
+ packetLen
,
309 &senderAddr
, senderPort
, &destAddr
, MulticastDNSPort
, InterfaceID
);
312 mDNSexport TCPSocket
*mDNSPlatformTCPSocket(mDNS
* const m
, TCPSocketFlags flags
, mDNSIPPort
* port
, mDNSBool useBackgroundTrafficClass
)
315 (void)flags
; // Unused
316 (void)port
; // Unused
317 (void)useBackgroundTrafficClass
; // Unused
321 mDNSexport TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int sd
)
323 (void)flags
; // Unused
328 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
330 (void)sock
; // Unused
334 mDNSexport mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
, domainname
*hostname
, mDNSInterfaceID InterfaceID
,
335 TCPConnectionCallback callback
, void *context
)
337 (void)sock
; // Unused
339 (void)dstport
; // Unused
340 (void)hostname
; // Unused
341 (void)InterfaceID
; // Unused
342 (void)callback
; // Unused
343 (void)context
; // Unused
344 return(mStatus_UnsupportedErr
);
347 mDNSexport
void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
)
349 (void)sock
; // Unused
352 mDNSexport
long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
* closed
)
354 (void)sock
; // Unused
356 (void)buflen
; // Unused
357 (void)closed
; // Unused
361 mDNSexport
long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
)
363 (void)sock
; // Unused
369 mDNSexport UDPSocket
*mDNSPlatformUDPSocket(mDNS
* const m
, mDNSIPPort port
)
372 (void)port
; // Unused
376 mDNSexport
void mDNSPlatformUDPClose(UDPSocket
*sock
)
378 (void)sock
; // Unused
381 mDNSexport
void mDNSPlatformUpdateProxyList(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
384 (void)InterfaceID
; // Unused
387 mDNSexport
void mDNSPlatformSendRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
)
391 (void)InterfaceID
; // Unused
394 mDNSexport
void mDNSPlatformSetLocalAddressCacheEntry(mDNS
*const m
, const mDNSAddr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
)
399 (void)InterfaceID
; // Unused
402 mDNSexport mStatus
mDNSPlatformTLSSetupCerts(void)
404 return(mStatus_UnsupportedErr
);
407 mDNSexport
void mDNSPlatformTLSTearDownCerts(void)
411 mDNSexport
void mDNSPlatformSetAllowSleep(mDNS
*const m
, mDNSBool allowSleep
, const char *reason
)
418 #if COMPILER_LIKES_PRAGMA_MARK
420 #pragma mark - /etc/hosts support
423 mDNSexport
void FreeEtcHosts(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
431 #if COMPILER_LIKES_PRAGMA_MARK
432 #pragma mark ***** DDNS Config Platform Functions
435 mDNSexport
void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**BrowseDomains
)
442 (void) BrowseDomains
;
445 mDNSexport mStatus
mDNSPlatformGetPrimaryInterface(mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
452 return mStatus_UnsupportedErr
;
455 mDNSexport
void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
)
461 #if COMPILER_LIKES_PRAGMA_MARK
462 #pragma mark ***** Init and Term
465 // This gets the current hostname, truncating it at the first dot if necessary
466 mDNSlocal
void GetUserSpecifiedRFC1034ComputerName(domainlabel
*const namelabel
)
469 gethostname((char *)(&namelabel
->c
[1]), MAX_DOMAIN_LABEL
);
470 while (len
< MAX_DOMAIN_LABEL
&& namelabel
->c
[len
+1] && namelabel
->c
[len
+1] != '.') len
++;
471 namelabel
->c
[0] = len
;
474 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
475 // Other platforms can either get the information from the appropriate place,
476 // or they can alternatively just require all registering services to provide an explicit name
477 mDNSlocal
void GetUserSpecifiedFriendlyComputerName(domainlabel
*const namelabel
)
479 // On Unix we have no better name than the host name, so we just use that.
480 GetUserSpecifiedRFC1034ComputerName(namelabel
);
483 mDNSexport
int ParseDNSServers(mDNS
*m
, const char *filePath
)
488 int numOfServers
= 0;
489 FILE *fp
= fopen(filePath
, "r");
490 if (fp
== NULL
) return -1;
491 while (fgets(line
,sizeof(line
),fp
))
494 line
[255]='\0'; // just to be safe
495 if (sscanf(line
,"%10s %15s", keyword
, nameserver
) != 2) continue; // it will skip whitespaces
496 if (strncasecmp(keyword
,"nameserver",10)) continue;
497 if (inet_aton(nameserver
, (struct in_addr
*)&ina
) != 0)
500 DNSAddr
.type
= mDNSAddrType_IPv4
;
501 DNSAddr
.ip
.v4
.NotAnInteger
= ina
.s_addr
;
502 mDNS_AddDNSServer(m
, NULL
, mDNSInterface_Any
, &DNSAddr
, UnicastDNSPort
, mDNSfalse
, 0, mDNSfalse
, 0);
506 return (numOfServers
> 0) ? 0 : -1;
509 // Searches the interface list looking for the named interface.
510 // Returns a pointer to if it found, or NULL otherwise.
511 mDNSlocal PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
513 PosixNetworkInterface
*intf
;
516 assert(intfName
!= NULL
);
518 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
519 while ((intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0))
520 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
525 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 index
)
527 PosixNetworkInterface
*intf
;
531 if (index
== kDNSServiceInterfaceIndexLocalOnly
) return(mDNSInterface_LocalOnly
);
532 if (index
== kDNSServiceInterfaceIndexP2P
) return(mDNSInterface_P2P
);
533 if (index
== kDNSServiceInterfaceIndexAny
) return(mDNSInterface_Any
);
535 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
536 while ((intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
537 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
539 return (mDNSInterfaceID
) intf
;
542 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
, mDNSBool suppressNetworkChange
)
544 PosixNetworkInterface
*intf
;
545 (void) suppressNetworkChange
; // Unused
549 if (id
== mDNSInterface_LocalOnly
) return(kDNSServiceInterfaceIndexLocalOnly
);
550 if (id
== mDNSInterface_P2P
) return(kDNSServiceInterfaceIndexP2P
);
551 if (id
== mDNSInterface_Any
) return(kDNSServiceInterfaceIndexAny
);
553 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
554 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
555 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
557 return intf
? intf
->index
: 0;
560 // Frees the specified PosixNetworkInterface structure. The underlying
561 // interface must have already been deregistered with the mDNS core.
562 mDNSlocal
void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
564 assert(intf
!= NULL
);
565 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
566 if (intf
->multicastSocket4
!= -1) assert(close(intf
->multicastSocket4
) == 0);
568 if (intf
->multicastSocket6
!= -1) assert(close(intf
->multicastSocket6
) == 0);
573 // Grab the first interface, deregister it, free it, and repeat until done.
574 mDNSlocal
void ClearInterfaceList(mDNS
*const m
)
578 while (m
->HostInterfaces
)
580 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
581 mDNS_DeregisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
582 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
583 FreePosixNetworkInterface(intf
);
585 num_registered_interfaces
= 0;
586 num_pkts_accepted
= 0;
587 num_pkts_rejected
= 0;
590 // Sets up a send/receive socket.
591 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
592 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
593 mDNSlocal
int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
596 static const int kOn
= 1;
597 static const int kIntTwoFiveFive
= 255;
598 static const unsigned char kByteTwoFiveFive
= 255;
599 const mDNSBool JoinMulticastGroup
= (port
.NotAnInteger
!= 0);
601 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
602 assert(intfAddr
!= NULL
);
603 assert(sktPtr
!= NULL
);
604 assert(*sktPtr
== -1);
606 // Open the socket...
607 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
609 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
613 if (*sktPtr
< 0) { err
= errno
; perror((intfAddr
->sa_family
== AF_INET
) ? "socket AF_INET" : "socket AF_INET6"); }
615 // ... with a shared UDP port, if it's for multicast receiving
616 if (err
== 0 && port
.NotAnInteger
)
618 #if defined(SO_REUSEPORT)
619 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
620 #elif defined(SO_REUSEADDR)
621 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
623 #error This platform has no way to avoid address busy errors on multicast.
625 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
628 // We want to receive destination addresses and interface identifiers.
629 if (intfAddr
->sa_family
== AF_INET
)
632 struct sockaddr_in bindAddr
;
635 #if defined(IP_PKTINFO) // Linux
636 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
637 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
638 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
639 #if defined(IP_RECVDSTADDR)
640 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
641 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
643 #if defined(IP_RECVIF)
646 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
647 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
651 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
654 #if defined(IP_RECVTTL) // Linux
657 setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
658 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
662 // Add multicast group membership on this interface
663 if (err
== 0 && JoinMulticastGroup
)
665 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
666 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
667 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
668 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
671 // Specify outgoing interface too
672 if (err
== 0 && JoinMulticastGroup
)
674 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
675 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
678 // Per the mDNS spec, send unicast packets with TTL 255
681 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
682 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
685 // and multicast packets with TTL 255 too
686 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
689 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
690 if (err
< 0 && errno
== EINVAL
)
691 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
692 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
695 // And start listening for packets
698 bindAddr
.sin_family
= AF_INET
;
699 bindAddr
.sin_port
= port
.NotAnInteger
;
700 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
701 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
702 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
704 } // endif (intfAddr->sa_family == AF_INET)
707 else if (intfAddr
->sa_family
== AF_INET6
)
709 struct ipv6_mreq imr6
;
710 struct sockaddr_in6 bindAddr6
;
711 #if defined(IPV6_PKTINFO)
714 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_PKTINFO
, &kOn
, sizeof(kOn
));
715 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
718 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
720 #if defined(IPV6_HOPLIMIT)
723 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_HOPLIMIT
, &kOn
, sizeof(kOn
));
724 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
728 // Add multicast group membership on this interface
729 if (err
== 0 && JoinMulticastGroup
)
731 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroup_v6
.ip
.v6
;
732 imr6
.ipv6mr_interface
= interfaceIndex
;
733 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
734 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
738 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
739 perror("setsockopt - IPV6_JOIN_GROUP");
743 // Specify outgoing interface too
744 if (err
== 0 && JoinMulticastGroup
)
746 u_int multicast_if
= interfaceIndex
;
747 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
748 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
751 // We want to receive only IPv6 packets on this socket.
752 // Without this option, we may get IPv4 addresses as mapped addresses.
755 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
756 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
759 // Per the mDNS spec, send unicast packets with TTL 255
762 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
763 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
766 // and multicast packets with TTL 255 too
767 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
770 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
771 if (err
< 0 && errno
== EINVAL
)
772 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
773 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
776 // And start listening for packets
779 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
780 #ifndef NOT_HAVE_SA_LEN
781 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
783 bindAddr6
.sin6_family
= AF_INET6
;
784 bindAddr6
.sin6_port
= port
.NotAnInteger
;
785 bindAddr6
.sin6_flowinfo
= 0;
786 bindAddr6
.sin6_addr
= in6addr_any
; // Want to receive multicasts AND unicasts on this socket
787 bindAddr6
.sin6_scope_id
= 0;
788 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
789 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
791 } // endif (intfAddr->sa_family == AF_INET6)
794 // Set the socket to non-blocking.
797 err
= fcntl(*sktPtr
, F_GETFL
, 0);
798 if (err
< 0) err
= errno
;
801 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
802 if (err
< 0) err
= errno
;
807 if (err
!= 0 && *sktPtr
!= -1) { assert(close(*sktPtr
) == 0); *sktPtr
= -1; }
808 assert((err
== 0) == (*sktPtr
!= -1));
812 // Creates a PosixNetworkInterface for the interface whose IP address is
813 // intfAddr and whose name is intfName and registers it with mDNS core.
814 mDNSlocal
int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, struct sockaddr
*intfMask
, const char *intfName
, int intfIndex
)
817 PosixNetworkInterface
*intf
;
818 PosixNetworkInterface
*alias
= NULL
;
821 assert(intfAddr
!= NULL
);
822 assert(intfName
!= NULL
);
823 assert(intfMask
!= NULL
);
825 // Allocate the interface structure itself.
826 intf
= (PosixNetworkInterface
*)malloc(sizeof(*intf
));
827 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
829 // And make a copy of the intfName.
832 intf
->intfName
= strdup(intfName
);
833 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
838 // Set up the fields required by the mDNS core.
839 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
840 SockAddrTomDNSAddr(intfMask
, &intf
->coreIntf
.mask
, NULL
);
842 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
843 strncpy(intf
->coreIntf
.ifname
, intfName
, sizeof(intf
->coreIntf
.ifname
));
844 intf
->coreIntf
.ifname
[sizeof(intf
->coreIntf
.ifname
)-1] = 0;
845 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
846 intf
->coreIntf
.McastTxRx
= mDNStrue
;
848 // Set up the extra fields in PosixNetworkInterface.
849 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
850 intf
->index
= intfIndex
;
851 intf
->multicastSocket4
= -1;
853 intf
->multicastSocket6
= -1;
855 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
856 if (alias
== NULL
) alias
= intf
;
857 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
860 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
863 // Set up the multicast socket
866 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
867 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
869 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
870 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
874 // The interface is all ready to go, let's register it with the mDNS core.
876 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
881 num_registered_interfaces
++;
882 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
883 if (gMDNSPlatformPosixVerboseLevel
> 0)
884 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
888 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
889 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
890 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
893 assert((err
== 0) == (intf
!= NULL
));
898 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
899 mDNSlocal
int SetupInterfaceList(mDNS
*const m
)
901 mDNSBool foundav4
= mDNSfalse
;
903 struct ifi_info
*intfList
= get_ifi_info(AF_INET
, mDNStrue
);
904 struct ifi_info
*firstLoopback
= NULL
;
907 debugf("SetupInterfaceList");
909 if (intfList
== NULL
) err
= ENOENT
;
912 if (err
== 0) /* Link the IPv6 list to the end of the IPv4 list */
914 struct ifi_info
**p
= &intfList
;
915 while (*p
) p
= &(*p
)->ifi_next
;
916 *p
= get_ifi_info(AF_INET6
, mDNStrue
);
922 struct ifi_info
*i
= intfList
;
925 if ( ((i
->ifi_addr
->sa_family
== AF_INET
)
927 || (i
->ifi_addr
->sa_family
== AF_INET6
)
929 ) && (i
->ifi_flags
& IFF_UP
) && !(i
->ifi_flags
& IFF_POINTOPOINT
))
931 if (i
->ifi_flags
& IFF_LOOPBACK
)
933 if (firstLoopback
== NULL
)
938 if (SetupOneInterface(m
, i
->ifi_addr
, i
->ifi_netmask
, i
->ifi_name
, i
->ifi_index
) == 0)
939 if (i
->ifi_addr
->sa_family
== AF_INET
)
946 // If we found no normal interfaces but we did find a loopback interface, register the
947 // loopback interface. This allows self-discovery if no interfaces are configured.
948 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
949 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
950 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
951 if (!foundav4
&& firstLoopback
)
952 (void) SetupOneInterface(m
, firstLoopback
->ifi_addr
, firstLoopback
->ifi_netmask
, firstLoopback
->ifi_name
, firstLoopback
->ifi_index
);
956 if (intfList
!= NULL
) free_ifi_info(intfList
);
962 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
964 // Open a socket that will receive interface change notifications
965 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
967 mStatus err
= mStatus_NoError
;
968 struct sockaddr_nl snl
;
972 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
976 // Configure read to be non-blocking because inbound msg size is not known in advance
977 (void) fcntl(sock
, F_SETFL
, O_NONBLOCK
);
979 /* Subscribe the socket to Link & IP addr notifications. */
980 mDNSPlatformMemZero(&snl
, sizeof snl
);
981 snl
.nl_family
= AF_NETLINK
;
982 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
983 ret
= bind(sock
, (struct sockaddr
*) &snl
, sizeof snl
);
993 mDNSlocal
void PrintNetLinkMsg(const struct nlmsghdr
*pNLMsg
)
995 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
996 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
998 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
999 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[pNLMsg
->nlmsg_type
- RTM_BASE
],
1000 pNLMsg
->nlmsg_flags
);
1002 if (RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
1004 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA(pNLMsg
);
1005 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
1006 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
1009 else if (RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
1011 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
);
1012 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
1013 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1019 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1020 // Read through the messages on sd and if any indicate that any interface records should
1021 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1025 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1028 // The structure here is more complex than it really ought to be because,
1029 // unfortunately, there's no good way to size a buffer in advance large
1030 // enough to hold all pending data and so avoid message fragmentation.
1031 // (Note that FIONREAD is not supported on AF_NETLINK.)
1033 readCount
= read(sd
, buff
, sizeof buff
);
1036 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1037 // If not, discard already-processed messages in buffer and read more data.
1038 if (((char*) &pNLMsg
[1] > (buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1039 ((char*) pNLMsg
+ pNLMsg
->nlmsg_len
> (buff
+ readCount
)))
1041 if (buff
< (char*) pNLMsg
) // we have space to shuffle
1043 // discard processed data
1044 readCount
-= ((char*) pNLMsg
- buff
);
1045 memmove(buff
, pNLMsg
, readCount
);
1046 pNLMsg
= (struct nlmsghdr
*) buff
;
1049 readCount
+= read(sd
, buff
+ readCount
, sizeof buff
- readCount
);
1050 continue; // spin around and revalidate with new readCount
1053 break; // Otherwise message does not fit in buffer
1057 PrintNetLinkMsg(pNLMsg
);
1060 // Process the NetLink message
1061 if (pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1062 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA(pNLMsg
))->ifi_index
;
1063 else if (pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1064 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
))->ifa_index
;
1066 // Advance pNLMsg to the next message in the buffer
1067 if ((pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1069 ssize_t len
= readCount
- ((char*)pNLMsg
- buff
);
1070 pNLMsg
= NLMSG_NEXT(pNLMsg
, len
);
1079 #else // USES_NETLINK
1081 // Open a socket that will receive interface change notifications
1082 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1084 *pFD
= socket(AF_ROUTE
, SOCK_RAW
, 0);
1087 return mStatus_UnknownErr
;
1089 // Configure read to be non-blocking because inbound msg size is not known in advance
1090 (void) fcntl(*pFD
, F_SETFL
, O_NONBLOCK
);
1092 return mStatus_NoError
;
1096 mDNSlocal
void PrintRoutingSocketMsg(const struct ifa_msghdr
*pRSMsg
)
1098 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1099 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1100 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1102 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1104 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[pRSMsg
->ifam_type
], index
);
1108 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1109 // Read through the messages on sd and if any indicate that any interface records should
1110 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1114 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1117 readCount
= read(sd
, buff
, sizeof buff
);
1118 if (readCount
< (ssize_t
) sizeof(struct ifa_msghdr
))
1119 return mStatus_UnsupportedErr
; // cannot decipher message
1122 PrintRoutingSocketMsg(pRSMsg
);
1125 // Process the message
1126 if (pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1127 pRSMsg
->ifam_type
== RTM_IFINFO
)
1129 if (pRSMsg
->ifam_type
== RTM_IFINFO
)
1130 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1132 result
|= 1 << pRSMsg
->ifam_index
;
1138 #endif // USES_NETLINK
1140 // Called when data appears on interface change notification socket
1141 mDNSlocal
void InterfaceChangeCallback(int fd
, short filter
, void *context
)
1143 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1145 mDNSu32 changedInterfaces
= 0;
1146 struct timeval zeroTimeout
= { 0, 0 };
1149 (void)filter
; // Unused
1152 FD_SET(pChgRec
->NotifySD
, &readFDs
);
1156 changedInterfaces
|= ProcessRoutingNotification(pChgRec
->NotifySD
);
1158 while (0 < select(pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1160 // Currently we rebuild the entire interface list whenever any interface change is
1161 // detected. If this ever proves to be a performance issue in a multi-homed
1162 // configuration, more care should be paid to changedInterfaces.
1163 if (changedInterfaces
)
1164 mDNSPlatformPosixRefreshInterfaceList(pChgRec
->mDNS
);
1167 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1168 mDNSlocal mStatus
WatchForInterfaceChange(mDNS
*const m
)
1171 IfChangeRec
*pChgRec
;
1173 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocate(sizeof *pChgRec
);
1174 if (pChgRec
== NULL
)
1175 return mStatus_NoMemoryErr
;
1178 err
= OpenIfNotifySocket(&pChgRec
->NotifySD
);
1180 err
= mDNSPosixAddFDToEventLoop(pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1185 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1186 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1187 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1188 mDNSlocal mDNSBool
mDNSPlatformInit_CanReceiveUnicast(void)
1191 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1192 struct sockaddr_in s5353
;
1193 s5353
.sin_family
= AF_INET
;
1194 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1195 s5353
.sin_addr
.s_addr
= 0;
1196 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1198 if (err
) debugf("No unicast UDP responses");
1199 else debugf("Unicast UDP responses okay");
1203 // mDNS core calls this routine to initialise the platform-specific data.
1204 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1210 if (mDNSPlatformInit_CanReceiveUnicast()) m
->CanReceiveUnicastOn5353
= mDNStrue
;
1212 // Tell mDNS core the names of this machine.
1214 // Set up the nice label
1215 m
->nicelabel
.c
[0] = 0;
1216 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1217 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Computer");
1219 // Set up the RFC 1034-compliant label
1220 m
->hostlabel
.c
[0] = 0;
1221 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1222 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Computer");
1226 sa
.sa_family
= AF_INET
;
1227 m
->p
->unicastSocket4
= -1;
1228 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1230 sa
.sa_family
= AF_INET6
;
1231 m
->p
->unicastSocket6
= -1;
1232 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1235 // Tell mDNS core about the network interfaces on this machine.
1236 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1238 // Tell mDNS core about DNS Servers
1240 if (err
== mStatus_NoError
) ParseDNSServers(m
, uDNS_SERVERS_FILE
);
1243 if (err
== mStatus_NoError
)
1245 err
= WatchForInterfaceChange(m
);
1246 // Failure to observe interface changes is non-fatal.
1247 if (err
!= mStatus_NoError
)
1249 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1250 err
= mStatus_NoError
;
1254 // We don't do asynchronous initialization on the Posix platform, so by the time
1255 // we get here the setup will already have succeeded or failed. If it succeeded,
1256 // we should just call mDNSCoreInitComplete() immediately.
1257 if (err
== mStatus_NoError
)
1258 mDNSCoreInitComplete(m
, mStatus_NoError
);
1260 return PosixErrorToStatus(err
);
1263 // mDNS core calls this routine to clean up the platform-specific data.
1264 // In our case all we need to do is to tear down every network interface.
1265 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1268 ClearInterfaceList(m
);
1269 if (m
->p
->unicastSocket4
!= -1) assert(close(m
->p
->unicastSocket4
) == 0);
1271 if (m
->p
->unicastSocket6
!= -1) assert(close(m
->p
->unicastSocket6
) == 0);
1275 mDNSexport mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1278 ClearInterfaceList(m
);
1279 err
= SetupInterfaceList(m
);
1280 return PosixErrorToStatus(err
);
1283 #if COMPILER_LIKES_PRAGMA_MARK
1284 #pragma mark ***** Locking
1287 // On the Posix platform, locking is a no-op because we only ever enter
1288 // mDNS core on the main thread.
1290 // mDNS core calls this routine when it wants to prevent
1291 // the platform from reentering mDNS core code.
1292 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1297 // mDNS core calls this routine when it release the lock taken by
1298 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1299 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1304 #if COMPILER_LIKES_PRAGMA_MARK
1305 #pragma mark ***** Strings
1308 // mDNS core calls this routine to copy C strings.
1309 // On the Posix platform this maps directly to the ANSI C strcpy.
1310 mDNSexport
void mDNSPlatformStrCopy(void *dst
, const void *src
)
1312 strcpy((char *)dst
, (char *)src
);
1315 // mDNS core calls this routine to get the length of a C string.
1316 // On the Posix platform this maps directly to the ANSI C strlen.
1317 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1319 return strlen((char*)src
);
1322 // mDNS core calls this routine to copy memory.
1323 // On the Posix platform this maps directly to the ANSI C memcpy.
1324 mDNSexport
void mDNSPlatformMemCopy(void *dst
, const void *src
, mDNSu32 len
)
1326 memcpy(dst
, src
, len
);
1329 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1330 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1331 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *dst
, const void *src
, mDNSu32 len
)
1333 return memcmp(dst
, src
, len
) == 0;
1336 // If the caller wants to know the exact return of memcmp, then use this instead
1337 // of mDNSPlatformMemSame
1338 mDNSexport
int mDNSPlatformMemCmp(const void *dst
, const void *src
, mDNSu32 len
)
1340 return (memcmp(dst
, src
, len
));
1343 mDNSexport
void mDNSPlatformQsort(void *base
, int nel
, int width
, int (*compar
)(const void *, const void *))
1345 return (qsort(base
, nel
, width
, compar
));
1348 // DNSSEC stub functions
1349 mDNSexport
void VerifySignature(mDNS
*const m
, DNSSECVerifier
*dv
, DNSQuestion
*q
)
1356 mDNSexport mDNSBool
AddNSECSForCacheRecord(mDNS
*const m
, CacheRecord
*crlist
, CacheRecord
*negcr
, mDNSu8 rcode
)
1365 // mDNS core calls this routine to clear blocks of memory.
1366 // On the Posix platform this is a simple wrapper around ANSI C memset.
1367 mDNSexport
void mDNSPlatformMemZero(void *dst
, mDNSu32 len
)
1369 memset(dst
, 0, len
);
1372 mDNSexport
void * mDNSPlatformMemAllocate(mDNSu32 len
) { return(malloc(len
)); }
1373 mDNSexport
void mDNSPlatformMemFree (void *mem
) { free(mem
); }
1375 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
1378 gettimeofday(&tv
, NULL
);
1382 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1384 mDNSexport mStatus
mDNSPlatformTimeInit(void)
1386 // No special setup is required on Posix -- we just use gettimeofday();
1387 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1388 // We should find a better way to do this
1389 return(mStatus_NoError
);
1392 mDNSexport mDNSs32
mDNSPlatformRawTime()
1395 gettimeofday(&tv
, NULL
);
1396 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1397 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1398 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1399 // 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.
1400 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1401 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1402 return((tv
.tv_sec
<< 10) | (tv
.tv_usec
* 16 / 15625));
1405 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1410 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNS
*const m
, mDNSInterfaceID InterfaceID
, char *EthAddr
, char *IPAddr
, int iteration
)
1419 mDNSexport mDNSBool
mDNSPlatformValidRecordForInterface(AuthRecord
*rr
, const NetworkInterfaceInfo
*intf
)
1427 mDNSexport mDNSBool
mDNSPlatformValidQuestionForInterface(DNSQuestion
*q
, const NetworkInterfaceInfo
*intf
)
1435 // Used for debugging purposes. For now, just set the buffer to zero
1436 mDNSexport
void mDNSPlatformFormatTime(unsigned long te
, mDNSu8
*buf
, int bufsize
)
1439 if (bufsize
) buf
[0] = 0;
1442 mDNSexport
void mDNSPlatformSendKeepalive(mDNSAddr
*sadd
, mDNSAddr
*dadd
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu32 seq
, mDNSu32 ack
, mDNSu16 win
)
1444 (void) sadd
; // Unused
1445 (void) dadd
; // Unused
1446 (void) lport
; // Unused
1447 (void) rport
; // Unused
1448 (void) seq
; // Unused
1449 (void) ack
; // Unused
1450 (void) win
; // Unused
1453 mDNSexport mStatus
mDNSPlatformRetrieveTCPInfo(mDNS
*const m
, mDNSAddr
*laddr
, mDNSIPPort
*lport
, mDNSAddr
*raddr
, mDNSIPPort
*rport
, mDNSTCPInfo
*mti
)
1456 (void) laddr
; // Unused
1457 (void) raddr
; // Unused
1458 (void) lport
; // Unused
1459 (void) rport
; // Unused
1460 (void) mti
; // Unused
1462 return mStatus_NoError
;
1465 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
1467 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
1471 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, struct timeval
*timeout
)
1474 struct timeval interval
;
1476 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1477 mDNSs32 nextevent
= mDNS_Execute(m
);
1479 // 2. Build our list of active file descriptors
1480 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1481 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket4
);
1483 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket6
);
1487 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket4
);
1489 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket6
);
1491 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1494 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1495 ticks
= nextevent
- mDNS_TimeNow(m
);
1496 if (ticks
< 1) ticks
= 1;
1497 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
1498 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1500 // 4. If client's proposed timeout is more than what we want, then reduce it
1501 if (timeout
->tv_sec
> interval
.tv_sec
||
1502 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
1503 *timeout
= interval
;
1506 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
)
1508 PosixNetworkInterface
*info
;
1510 assert(readfds
!= NULL
);
1511 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1513 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
1515 FD_CLR(m
->p
->unicastSocket4
, readfds
);
1516 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
1519 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
1521 FD_CLR(m
->p
->unicastSocket6
, readfds
);
1522 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
1528 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
1530 FD_CLR(info
->multicastSocket4
, readfds
);
1531 SocketDataReady(m
, info
, info
->multicastSocket4
);
1534 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
1536 FD_CLR(info
->multicastSocket6
, readfds
);
1537 SocketDataReady(m
, info
, info
->multicastSocket6
);
1540 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1545 mDNSlocal
void DetermineMaxEventFD(void)
1547 PosixEventSource
*iSource
;
1550 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1551 if (gMaxFD
< iSource
->fd
)
1552 gMaxFD
= iSource
->fd
;
1555 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1556 mStatus
mDNSPosixAddFDToEventLoop(int fd
, mDNSPosixEventCallback callback
, void *context
)
1558 PosixEventSource
*newSource
;
1560 if (gEventSources
.LinkOffset
== 0)
1561 InitLinkedList(&gEventSources
, offsetof(PosixEventSource
, Next
));
1563 if (fd
>= (int) FD_SETSIZE
|| fd
< 0)
1564 return mStatus_UnsupportedErr
;
1565 if (callback
== NULL
)
1566 return mStatus_BadParamErr
;
1568 newSource
= (PosixEventSource
*) malloc(sizeof *newSource
);
1569 if (NULL
== newSource
)
1570 return mStatus_NoMemoryErr
;
1572 newSource
->Callback
= callback
;
1573 newSource
->Context
= context
;
1576 AddToTail(&gEventSources
, newSource
);
1577 FD_SET(fd
, &gEventFDs
);
1579 DetermineMaxEventFD();
1581 return mStatus_NoError
;
1584 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1585 mStatus
mDNSPosixRemoveFDFromEventLoop(int fd
)
1587 PosixEventSource
*iSource
;
1589 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1591 if (fd
== iSource
->fd
)
1593 FD_CLR(fd
, &gEventFDs
);
1594 RemoveFromList(&gEventSources
, iSource
);
1596 DetermineMaxEventFD();
1597 return mStatus_NoError
;
1600 return mStatus_NoSuchNameErr
;
1603 // Simply note the received signal in gEventSignals.
1604 mDNSlocal
void NoteSignal(int signum
)
1606 sigaddset(&gEventSignals
, signum
);
1609 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1610 mStatus
mDNSPosixListenForSignalInEventLoop(int signum
)
1612 struct sigaction action
;
1615 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1616 action
.sa_handler
= NoteSignal
;
1617 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1619 sigaddset(&gEventSignalSet
, signum
);
1624 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1625 mStatus
mDNSPosixIgnoreSignalInEventLoop(int signum
)
1627 struct sigaction action
;
1630 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1631 action
.sa_handler
= SIG_DFL
;
1632 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1634 sigdelset(&gEventSignalSet
, signum
);
1639 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1640 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1641 mStatus
mDNSPosixRunEventLoopOnce(mDNS
*m
, const struct timeval
*pTimeout
,
1642 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
1644 fd_set listenFDs
= gEventFDs
;
1645 int fdMax
= 0, numReady
;
1646 struct timeval timeout
= *pTimeout
;
1648 // Include the sockets that are listening to the wire in our select() set
1649 mDNSPosixGetFDSet(m
, &fdMax
, &listenFDs
, &timeout
); // timeout may get modified
1653 numReady
= select(fdMax
+ 1, &listenFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &timeout
);
1655 // If any data appeared, invoke its callback
1658 PosixEventSource
*iSource
;
1660 (void) mDNSPosixProcessFDSet(m
, &listenFDs
); // call this first to process wire data for clients
1662 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1664 if (FD_ISSET(iSource
->fd
, &listenFDs
))
1666 iSource
->Callback(iSource
->fd
, 0, iSource
->Context
);
1667 break; // in case callback removed elements from gEventSources
1670 *pDataDispatched
= mDNStrue
;
1673 *pDataDispatched
= mDNSfalse
;
1675 (void) sigprocmask(SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1676 *pSignalsReceived
= gEventSignals
;
1677 sigemptyset(&gEventSignals
);
1678 (void) sigprocmask(SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1680 return mStatus_NoError
;