1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
3 * Copyright (c) 2002-2019 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
20 #include "DNSCommon.h"
21 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
22 #include "PlatformCommon.h"
36 #include <sys/types.h>
38 #include <sys/socket.h>
40 #include <sys/select.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <time.h> // platform support for UTC time
47 #include <asm/types.h>
48 #include <linux/netlink.h>
49 #include <linux/rtnetlink.h>
51 #include <net/route.h>
53 #endif // USES_NETLINK
56 #include "GenLinkedList.h"
59 // ***************************************************************************
62 // Context record for interface change callback
68 typedef struct IfChangeRec IfChangeRec
;
70 // Note that static data is initialized to zero in (modern) C.
71 static PosixEventSource
*gEventSources
; // linked list of PosixEventSource's
72 static sigset_t gEventSignalSet
; // Signals which event loop listens for
73 static sigset_t gEventSignals
; // Signals which were received while inside loop
75 static PosixNetworkInterface
*gRecentInterfaces
;
77 // ***************************************************************************
78 // Globals (for debugging)
80 static int num_registered_interfaces
= 0;
81 static int num_pkts_accepted
= 0;
82 static int num_pkts_rejected
= 0;
84 // ***************************************************************************
86 mDNSlocal
void requestReadEvents(PosixEventSource
*eventSource
,
87 const char *taskName
, mDNSPosixEventCallback callback
, void *context
);
88 mDNSlocal mStatus
stopReadOrWriteEvents(int fd
, mDNSBool freeSource
, mDNSBool removeSource
, int flags
);
89 mDNSlocal
void requestWriteEvents(PosixEventSource
*eventSource
,
90 const char *taskName
, mDNSPosixEventCallback callback
, void *context
);
91 // ***************************************************************************
94 #if MDNS_MALLOC_DEBUGGING
95 mDNSexport
void mDNSPlatformValidateLists(void)
97 // This should validate gEventSources and any other Posix-specific stuff that gets allocated.
101 int gMDNSPlatformPosixVerboseLevel
= 0;
103 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
105 mDNSlocal
void SockAddrTomDNSAddr(const struct sockaddr
*const sa
, mDNSAddr
*ipAddr
, mDNSIPPort
*ipPort
)
107 switch (sa
->sa_family
)
111 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
112 ipAddr
->type
= mDNSAddrType_IPv4
;
113 ipAddr
->ip
.v4
.NotAnInteger
= sin
->sin_addr
.s_addr
;
114 if (ipPort
) ipPort
->NotAnInteger
= sin
->sin_port
;
121 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
122 #ifndef NOT_HAVE_SA_LEN
123 assert(sin6
->sin6_len
== sizeof(*sin6
));
125 ipAddr
->type
= mDNSAddrType_IPv6
;
126 ipAddr
->ip
.v6
= *(mDNSv6Addr
*)&sin6
->sin6_addr
;
127 if (ipPort
) ipPort
->NotAnInteger
= sin6
->sin6_port
;
133 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa
->sa_family
);
134 ipAddr
->type
= mDNSAddrType_None
;
135 if (ipPort
) ipPort
->NotAnInteger
= 0;
140 #if COMPILER_LIKES_PRAGMA_MARK
141 #pragma mark ***** Send and Receive
144 // mDNS core calls this routine when it needs to send a packet.
145 mDNSexport mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
146 mDNSInterfaceID InterfaceID
, UDPSocket
*src
, const mDNSAddr
*dst
,
147 mDNSIPPort dstPort
, mDNSBool useBackgroundTrafficClass
)
150 struct sockaddr_storage to
;
151 PosixNetworkInterface
* thisIntf
= (PosixNetworkInterface
*)(InterfaceID
);
152 int sendingsocket
= -1;
154 (void)src
; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
155 (void) useBackgroundTrafficClass
;
160 assert((((char *) end
) - ((char *) msg
)) > 0);
162 if (dstPort
.NotAnInteger
== 0)
164 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
165 return PosixErrorToStatus(EINVAL
);
167 if (dst
->type
== mDNSAddrType_IPv4
)
169 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&to
;
170 #ifndef NOT_HAVE_SA_LEN
171 sin
->sin_len
= sizeof(*sin
);
173 sin
->sin_family
= AF_INET
;
174 sin
->sin_port
= dstPort
.NotAnInteger
;
175 sin
->sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
176 sendingsocket
= thisIntf
? thisIntf
->multicastSocket4
: m
->p
->unicastSocket4
;
180 else if (dst
->type
== mDNSAddrType_IPv6
)
182 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&to
;
183 mDNSPlatformMemZero(sin6
, sizeof(*sin6
));
184 #ifndef NOT_HAVE_SA_LEN
185 sin6
->sin6_len
= sizeof(*sin6
);
187 sin6
->sin6_family
= AF_INET6
;
188 sin6
->sin6_port
= dstPort
.NotAnInteger
;
189 sin6
->sin6_addr
= *(struct in6_addr
*)&dst
->ip
.v6
;
190 sendingsocket
= thisIntf
? thisIntf
->multicastSocket6
: m
->p
->unicastSocket6
;
194 if (sendingsocket
>= 0)
195 err
= sendto(sendingsocket
, msg
, (char*)end
- (char*)msg
, 0, (struct sockaddr
*)&to
, GET_SA_LEN(to
));
197 if (err
> 0) err
= 0;
200 static int MessageCount
= 0;
201 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
202 if (!mDNSAddressIsAllDNSLinkGroup(dst
))
203 if (errno
== EHOSTDOWN
|| errno
== ENETDOWN
|| errno
== EHOSTUNREACH
|| errno
== ENETUNREACH
) return(mStatus_TransientErr
);
205 if (MessageCount
< 1000)
209 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
210 errno
, strerror(errno
), dst
, &thisIntf
->coreIntf
.ip
, thisIntf
->intfName
, thisIntf
->index
);
212 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno
, strerror(errno
), dst
);
216 return PosixErrorToStatus(err
);
219 mDNSlocal
void TCPReadCallback(int fd
, void *context
)
221 TCPSocket
*sock
= context
;
224 if (sock
->flags
& kTCPSocketFlags_UseTLS
)
230 sock
->callback(sock
, sock
->context
, mDNSfalse
, sock
->err
);
234 mDNSlocal
void tcpConnectCallback(int fd
, void *context
)
236 TCPSocket
*sock
= context
;
237 mDNSBool c
= !sock
->connected
;
239 socklen_t len
= sizeof result
;
241 sock
->connected
= mDNStrue
;
243 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &result
, &len
) < 0)
245 LogInfo("ERROR: TCPConnectCallback - unable to get connect error: socket %d: Error %d (%s)",
246 sock
->events
.fd
, result
, strerror(result
));
247 sock
->err
= mStatus_ConnFailed
;
253 sock
->err
= mStatus_ConnFailed
;
254 if (result
== EHOSTUNREACH
|| result
== EADDRNOTAVAIL
|| result
== ENETDOWN
)
256 LogInfo("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
257 sock
->events
.fd
, result
, strerror(result
));
261 LogMsg("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
262 sock
->events
.fd
, result
, strerror(result
));
267 // The connection succeeded.
268 sock
->connected
= mDNStrue
;
269 // Select for read events.
270 sock
->events
.fd
= fd
;
271 requestReadEvents(&sock
->events
, "mDNSPosix::tcpConnectCallback", TCPReadCallback
, sock
);
277 sock
->callback(sock
, sock
->context
, c
, sock
->err
);
278 // Here sock must be assumed to be invalid, in case the callback freed it.
283 // This routine is called when the main loop detects that data is available on a socket.
284 mDNSlocal
void SocketDataReady(mDNS
*const m
, PosixNetworkInterface
*intf
, int skt
)
286 mDNSAddr senderAddr
, destAddr
;
287 mDNSIPPort senderPort
;
290 struct my_in_pktinfo packetInfo
;
291 struct sockaddr_storage from
;
296 const mDNSInterfaceID InterfaceID
= intf
? intf
->coreIntf
.InterfaceID
: NULL
;
301 fromLen
= sizeof(from
);
303 packetLen
= recvfrom_flags(skt
, &packet
, sizeof(packet
), &flags
, (struct sockaddr
*) &from
, &fromLen
, &packetInfo
, &ttl
);
307 SockAddrTomDNSAddr((struct sockaddr
*)&from
, &senderAddr
, &senderPort
);
308 SockAddrTomDNSAddr((struct sockaddr
*)&packetInfo
.ipi_addr
, &destAddr
, NULL
);
310 // If we have broken IP_RECVDSTADDR functionality (so far
311 // I've only seen this on OpenBSD) then apply a hack to
312 // convince mDNS Core that this isn't a spoof packet.
313 // Basically what we do is check to see whether the
314 // packet arrived as a multicast and, if so, set its
315 // destAddr to the mDNS address.
317 // I must admit that I could just be doing something
318 // wrong on OpenBSD and hence triggering this problem
319 // but I'm at a loss as to how.
321 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
322 // no way to tell the destination address or interface this packet arrived on,
323 // so all we can do is just assume it's a multicast
325 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
326 if ((destAddr
.NotAnInteger
== 0) && (flags
& MSG_MCAST
))
328 destAddr
.type
= senderAddr
.type
;
329 if (senderAddr
.type
== mDNSAddrType_IPv4
) destAddr
.ip
.v4
= AllDNSLinkGroup_v4
.ip
.v4
;
330 else if (senderAddr
.type
== mDNSAddrType_IPv6
) destAddr
.ip
.v6
= AllDNSLinkGroup_v6
.ip
.v6
;
334 // We only accept the packet if the interface on which it came
335 // in matches the interface associated with this socket.
336 // We do this match by name or by index, depending on which
337 // information is available. recvfrom_flags sets the name
338 // to "" if the name isn't available, or the index to -1
339 // if the index is available. This accomodates the various
340 // different capabilities of our target platforms.
345 // Ignore multicasts accidentally delivered to our unicast receiving socket
346 if (mDNSAddrIsDNSMulticast(&destAddr
)) packetLen
= -1;
350 if (packetInfo
.ipi_ifname
[0] != 0) reject
= (strcmp(packetInfo
.ipi_ifname
, intf
->intfName
) != 0);
351 else if (packetInfo
.ipi_ifindex
!= -1) reject
= (packetInfo
.ipi_ifindex
!= intf
->index
);
355 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
356 &senderAddr
, &destAddr
, packetInfo
.ipi_ifname
, packetInfo
.ipi_ifindex
,
357 &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
360 if (num_pkts_rejected
> (num_pkts_accepted
+ 1) * (num_registered_interfaces
+ 1) * 2)
363 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
364 num_pkts_accepted
+ num_pkts_rejected
, num_pkts_accepted
, num_pkts_rejected
);
365 num_pkts_accepted
= 0;
366 num_pkts_rejected
= 0;
371 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
372 &senderAddr
, &destAddr
, &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
379 mDNSCoreReceive(m
, &packet
, (mDNSu8
*)&packet
+ packetLen
,
380 &senderAddr
, senderPort
, &destAddr
, MulticastDNSPort
, InterfaceID
);
383 mDNSexport TCPSocket
*mDNSPlatformTCPSocket(TCPSocketFlags flags
, mDNSAddr_Type addrType
, mDNSIPPort
* port
,
384 domainname
*hostname
, mDNSBool useBackgroundTrafficClass
)
387 int len
= sizeof (TCPSocket
);
389 (void)useBackgroundTrafficClass
;
393 len
+= sizeof (domainname
);
399 LogMsg("mDNSPlatformTCPSocket: no memory for socket");
402 memset(sock
, 0, sizeof *sock
);
406 sock
->hostname
= (domainname
*)(sock
+ 1);
407 LogMsg("mDNSPlatformTCPSocket: hostname %##s", hostname
->c
);
408 AssignDomainName(sock
->hostname
, hostname
);
411 sock
->events
.fd
= -1;
412 if (!mDNSPosixTCPSocketSetup(&sock
->events
.fd
, addrType
, port
, &sock
->port
))
414 if (sock
->events
.fd
!= -1) close(sock
->events
.fd
);
419 // Set up the other fields in the structure.
421 sock
->err
= mStatus_NoError
;
422 sock
->setup
= mDNSfalse
;
423 sock
->connected
= mDNSfalse
;
427 mDNSexport mStatus
mDNSPlatformTCPSocketSetCallback(TCPSocket
*sock
, TCPConnectionCallback callback
, void *context
)
429 sock
->callback
= callback
;
430 sock
->context
= context
;
431 return mStatus_NoError
;
434 mDNSexport TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int fd
)
439 if (flags
& kTCPSocketFlags_UseTLS
)
441 return mDNSNULL
; // not supported yet.
444 sock
= (TCPSocket
*) mDNSPlatformMemAllocateClear(sizeof *sock
);
450 sock
->events
.fd
= fd
;
452 sock
->connected
= mDNStrue
;
457 mDNSlocal
void tcpListenCallback(int fd
, void *context
)
459 TCPListener
*listener
= context
;
462 sock
= mDNSPosixDoTCPListenCallback(fd
, listener
->addressType
, listener
->socketFlags
,
463 listener
->callback
, listener
->context
);
466 requestReadEvents(&sock
->events
, "mDNSPosix::tcpListenCallback", TCPReadCallback
, sock
);
470 mDNSexport TCPListener
*mDNSPlatformTCPListen(mDNSAddr_Type addrType
, mDNSIPPort
*port
, mDNSAddr
*addr
,
471 TCPSocketFlags socketFlags
, mDNSBool reuseAddr
, int queueLength
,
472 TCPAcceptedCallback callback
, void *context
)
477 if (!mDNSPosixTCPListen(&fd
, addrType
, port
, addr
, reuseAddr
, queueLength
))
486 // Allocate a listener structure
487 ret
= (TCPListener
*) mDNSPlatformMemAllocateClear(sizeof *ret
);
490 LogMsg("mDNSPlatformTCPListen: no memory for TCPListener struct.");
495 ret
->callback
= callback
;
496 ret
->context
= context
;
497 ret
->addressType
= addrType
;
498 ret
->socketFlags
= socketFlags
;
500 // When we get a connection, mDNSPosixListenCallback will be called, and it will invoke the
501 // callback we were passed.
502 requestReadEvents(&ret
->events
, "tcpListenCallback", tcpListenCallback
, ret
);
506 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
508 return sock
->events
.fd
;
511 mDNSexport mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
,
512 mDNSInterfaceID InterfaceID
, TCPConnectionCallback callback
, void *context
)
517 struct sockaddr_in sin
;
518 struct sockaddr_in6 sin6
;
522 sock
->callback
= callback
;
523 sock
->context
= context
;
524 sock
->setup
= mDNSfalse
;
525 sock
->connected
= mDNSfalse
;
526 sock
->err
= mStatus_NoError
;
528 result
= fcntl(sock
->events
.fd
, F_GETFL
, 0);
531 LogMsg("mDNSPlatformTCPConnect: F_GETFL failed: %s", strerror(errno
));
532 return mStatus_UnknownErr
;
535 result
= fcntl(sock
->events
.fd
, F_SETFL
, result
| O_NONBLOCK
);
538 LogMsg("mDNSPlatformTCPConnect: F_SETFL failed: %s", strerror(errno
));
539 return mStatus_UnknownErr
;
542 // If we've been asked to bind to a single interface, do it. See comment in mDNSMacOSX.c for more info.
545 PosixNetworkInterface
*iface
= (PosixNetworkInterface
*)InterfaceID
;
546 #if defined(SO_BINDTODEVICE)
547 result
= setsockopt(sock
->events
.fd
,
548 SOL_SOCKET
, SO_BINDTODEVICE
, iface
->intfName
, strlen(iface
->intfName
));
551 LogMsg("mDNSPlatformTCPConnect: SO_BINDTODEVICE failed on %s: %s", iface
->intfName
, strerror(errno
));
552 return mStatus_BadParamErr
;
555 if (dst
->type
== mDNSAddrType_IPv4
)
557 #if defined(IP_BOUND_IF)
558 result
= setsockopt(sock
->events
.fd
, IPPROTO_IP
, IP_BOUND_IF
, &iface
->index
, sizeof iface
->index
);
561 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
562 iface
->intfName
, iface
->index
, strerror(errno
));
563 return mStatus_BadParamErr
;
567 #endif // IP_BOUND_IF
571 #if defined(IPV6_BOUND_IF)
572 result
= setsockopt(sock
->events
.fd
, IPPROTO_IPV6
, IPV6_BOUND_IF
, &iface
->index
, sizeof iface
->index
);
575 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
576 iface
->intfName
, iface
->index
, strerror(errno
));
577 return mStatus_BadParamErr
;
581 #endif // IPV6_BOUND_IF
583 #endif // SO_BINDTODEVICE
586 memset(&addr
, 0, sizeof addr
);
587 if (dst
->type
== mDNSAddrType_IPv4
)
589 addr
.sa
.sa_family
= AF_INET
;
590 addr
.sin
.sin_port
= dstport
.NotAnInteger
;
591 len
= sizeof (struct sockaddr_in
);
592 addr
.sin
.sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
596 addr
.sa
.sa_family
= AF_INET6
;
597 len
= sizeof (struct sockaddr_in6
);
598 addr
.sin6
.sin6_port
= dstport
.NotAnInteger
;
599 memcpy(&addr
.sin6
.sin6_addr
.s6_addr
, &dst
->ip
.v6
, sizeof addr
.sin6
.sin6_addr
.s6_addr
);
601 #ifndef NOT_HAVE_SA_LEN
602 addr
.sa
.sa_len
= len
;
605 result
= connect(sock
->events
.fd
, (struct sockaddr
*)&addr
, len
);
608 if (errno
== EINPROGRESS
)
610 requestWriteEvents(&sock
->events
, "mDNSPlatformConnect", tcpConnectCallback
, sock
);
611 return mStatus_ConnPending
;
613 if (errno
== EHOSTUNREACH
|| errno
== EADDRNOTAVAIL
|| errno
== ENETDOWN
)
615 LogInfo("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s)",
616 sock
->events
.fd
, errno
, strerror(errno
));
620 LogMsg("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s) length %d",
621 sock
->events
.fd
, errno
, strerror(errno
), len
);
623 return mStatus_ConnFailed
;
626 LogMsg("NOTE: mDNSPlatformTCPConnect completed synchronously");
627 return mStatus_NoError
;
630 mDNSexport
void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
)
633 { // can sock really be NULL when this is called?
634 shutdown(sock
->events
.fd
, SHUT_RDWR
);
635 stopReadOrWriteEvents(sock
->events
.fd
, mDNSfalse
, mDNStrue
,
636 PosixEventFlag_Read
| PosixEventFlag_Write
);
637 close(sock
->events
.fd
);
642 mDNSexport
long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
* closed
)
647 if (sock
->flags
& kTCPSocketFlags_UseTLS
)
653 nread
= mDNSPosixReadTCP(sock
->events
.fd
, buf
, buflen
, closed
);
658 mDNSexport mDNSBool
mDNSPlatformTCPWritable(TCPSocket
*sock
)
661 int nfds
= sock
->events
.fd
+ 1;
665 if (nfds
> FD_SETSIZE
)
667 LogMsg("ERROR: mDNSPlatformTCPWritable called on an fd that won't fit in an fd_set.");
668 return mDNStrue
; // hope for the best?
670 FD_SET(sock
->events
.fd
, &w
);
671 tv
.tv_sec
= tv
.tv_usec
= 0;
672 count
= select(nfds
, NULL
, &w
, NULL
, &tv
);
680 mDNSexport
long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
)
682 if (sock
->flags
& kTCPSocketFlags_UseTLS
)
689 return mDNSPosixWriteTCP(sock
->events
.fd
, msg
, len
);
693 mDNSexport UDPSocket
*mDNSPlatformUDPSocket(mDNSIPPort port
)
695 (void)port
; // Unused
699 mDNSexport
void mDNSPlatformUDPClose(UDPSocket
*sock
)
701 (void)sock
; // Unused
704 mDNSexport
void mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID
)
706 (void)InterfaceID
; // Unused
709 mDNSexport
void mDNSPlatformSendRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
)
713 (void)InterfaceID
; // Unused
716 mDNSexport
void mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
)
720 (void)InterfaceID
; // Unused
723 mDNSexport mStatus
mDNSPlatformTLSSetupCerts(void)
725 return(mStatus_UnsupportedErr
);
728 mDNSexport
void mDNSPlatformTLSTearDownCerts(void)
732 mDNSexport
void mDNSPlatformSetAllowSleep(mDNSBool allowSleep
, const char *reason
)
738 #if COMPILER_LIKES_PRAGMA_MARK
740 #pragma mark - /etc/hosts support
743 mDNSexport
void FreeEtcHosts(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
751 #if COMPILER_LIKES_PRAGMA_MARK
752 #pragma mark ***** DDNS Config Platform Functions
755 mDNSexport mDNSBool
mDNSPlatformSetDNSConfig(mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
,
756 DNameListElem
**BrowseDomains
, mDNSBool ackConfig
)
762 if (fqdn
) fqdn
->c
[0] = 0;
763 if (RegDomains
) *RegDomains
= NULL
;
764 if (BrowseDomains
) *BrowseDomains
= NULL
;
769 mDNSexport mStatus
mDNSPlatformGetPrimaryInterface(mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
775 return mStatus_UnsupportedErr
;
778 mDNSexport
void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
)
784 #if COMPILER_LIKES_PRAGMA_MARK
785 #pragma mark ***** Init and Term
788 // This gets the current hostname, truncating it at the first dot if necessary
789 mDNSlocal
void GetUserSpecifiedRFC1034ComputerName(domainlabel
*const namelabel
)
792 gethostname((char *)(&namelabel
->c
[1]), MAX_DOMAIN_LABEL
);
793 while (len
< MAX_DOMAIN_LABEL
&& namelabel
->c
[len
+1] && namelabel
->c
[len
+1] != '.') len
++;
794 namelabel
->c
[0] = len
;
797 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
798 // Other platforms can either get the information from the appropriate place,
799 // or they can alternatively just require all registering services to provide an explicit name
800 mDNSlocal
void GetUserSpecifiedFriendlyComputerName(domainlabel
*const namelabel
)
802 // On Unix we have no better name than the host name, so we just use that.
803 GetUserSpecifiedRFC1034ComputerName(namelabel
);
806 mDNSexport
int ParseDNSServers(mDNS
*m
, const char *filePath
)
811 int numOfServers
= 0;
812 FILE *fp
= fopen(filePath
, "r");
813 if (fp
== NULL
) return -1;
814 while (fgets(line
,sizeof(line
),fp
))
817 line
[255]='\0'; // just to be safe
818 if (sscanf(line
,"%10s %15s", keyword
, nameserver
) != 2) continue; // it will skip whitespaces
819 if (strncasecmp(keyword
,"nameserver",10)) continue;
820 if (inet_aton(nameserver
, (struct in_addr
*)&ina
) != 0)
823 DNSAddr
.type
= mDNSAddrType_IPv4
;
824 DNSAddr
.ip
.v4
.NotAnInteger
= ina
.s_addr
;
825 mDNS_AddDNSServer(m
, NULL
, mDNSInterface_Any
, 0, &DNSAddr
, UnicastDNSPort
, kScopeNone
, 0, mDNSfalse
, mDNSfalse
, mDNSfalse
, mDNSfalse
, 0, mDNStrue
, mDNStrue
, mDNSfalse
);
830 return (numOfServers
> 0) ? 0 : -1;
833 // Searches the interface list looking for the named interface.
834 // Returns a pointer to if it found, or NULL otherwise.
835 mDNSlocal PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
837 PosixNetworkInterface
*intf
;
840 assert(intfName
!= NULL
);
842 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
843 while ((intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0))
844 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
849 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 index
)
851 PosixNetworkInterface
*intf
;
855 if (index
== kDNSServiceInterfaceIndexLocalOnly
) return(mDNSInterface_LocalOnly
);
856 if (index
== kDNSServiceInterfaceIndexP2P
) return(mDNSInterface_P2P
);
857 if (index
== kDNSServiceInterfaceIndexAny
) return(mDNSInterface_Any
);
859 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
860 while ((intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
861 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
863 return (mDNSInterfaceID
) intf
;
866 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
, mDNSBool suppressNetworkChange
)
868 PosixNetworkInterface
*intf
;
869 (void) suppressNetworkChange
; // Unused
873 if (id
== mDNSInterface_LocalOnly
) return(kDNSServiceInterfaceIndexLocalOnly
);
874 if (id
== mDNSInterface_P2P
) return(kDNSServiceInterfaceIndexP2P
);
875 if (id
== mDNSInterface_Any
) return(kDNSServiceInterfaceIndexAny
);
877 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
878 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
879 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
881 if (intf
) return intf
->index
;
883 // If we didn't find the interface, check the RecentInterfaces list as well
884 intf
= gRecentInterfaces
;
885 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
886 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
888 return intf
? intf
->index
: 0;
891 // Frees the specified PosixNetworkInterface structure. The underlying
892 // interface must have already been deregistered with the mDNS core.
893 mDNSlocal
void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
896 assert(intf
!= NULL
);
897 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
898 if (intf
->multicastSocket4
!= -1)
900 rv
= close(intf
->multicastSocket4
);
904 if (intf
->multicastSocket6
!= -1)
906 rv
= close(intf
->multicastSocket6
);
911 // Move interface to the RecentInterfaces list for a minute
912 intf
->LastSeen
= mDNSPlatformUTC();
913 intf
->coreIntf
.next
= &gRecentInterfaces
->coreIntf
;
914 gRecentInterfaces
= intf
;
917 // Grab the first interface, deregister it, free it, and repeat until done.
918 mDNSlocal
void ClearInterfaceList(mDNS
*const m
)
922 while (m
->HostInterfaces
)
924 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
925 mDNS_DeregisterInterface(m
, &intf
->coreIntf
, NormalActivation
);
926 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
927 FreePosixNetworkInterface(intf
);
929 num_registered_interfaces
= 0;
930 num_pkts_accepted
= 0;
931 num_pkts_rejected
= 0;
934 // Sets up a send/receive socket.
935 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
936 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
937 mDNSlocal
int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
940 static const int kOn
= 1;
941 static const int kIntTwoFiveFive
= 255;
942 static const unsigned char kByteTwoFiveFive
= 255;
943 const mDNSBool JoinMulticastGroup
= (port
.NotAnInteger
!= 0);
945 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
946 assert(intfAddr
!= NULL
);
947 assert(sktPtr
!= NULL
);
948 assert(*sktPtr
== -1);
950 // Open the socket...
951 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
953 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
957 if (*sktPtr
< 0) { err
= errno
; perror((intfAddr
->sa_family
== AF_INET
) ? "socket AF_INET" : "socket AF_INET6"); }
959 // ... with a shared UDP port, if it's for multicast receiving
960 if (err
== 0 && port
.NotAnInteger
)
962 // <rdar://problem/20946253> Suggestions from Jonny Törnbom at Axis Communications
963 // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
964 // Linux kernel versions 3.9 introduces support for socket option
965 // SO_REUSEPORT, however this is not implemented the same as on *BSD
966 // systems. Linux version implements a "port hijacking" prevention
967 // mechanism, limiting processes wanting to bind to an already existing
968 // addr:port to have the same effective UID as the first who bound it. What
969 // this meant for us was that the daemon ran as one user and when for
970 // instance mDNSClientPosix was executed by another user, it wasn't allowed
971 // to bind to the socket. Our suggestion was to switch the order in which
972 // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
973 // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
974 #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
975 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
976 #elif defined(SO_REUSEPORT)
977 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
979 #error This platform has no way to avoid address busy errors on multicast.
981 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
984 // Enable inbound packets on IFEF_AWDL interface.
985 // Only done for multicast sockets, since we don't expect unicast socket operations
986 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
987 #ifndef SO_RECV_ANYIF
988 #define SO_RECV_ANYIF 0x1104 /* unrestricted inbound processing */
990 if (setsockopt(*sktPtr
, SOL_SOCKET
, SO_RECV_ANYIF
, &kOn
, sizeof(kOn
)) < 0) perror("setsockopt - SO_RECV_ANYIF");
994 // We want to receive destination addresses and interface identifiers.
995 if (intfAddr
->sa_family
== AF_INET
)
998 struct sockaddr_in bindAddr
;
1001 #if defined(IP_PKTINFO) // Linux
1002 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
1003 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
1004 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
1005 #if defined(IP_RECVDSTADDR)
1006 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
1007 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
1009 #if defined(IP_RECVIF)
1012 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
1013 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
1017 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
1020 #if defined(IP_RECVTTL) // Linux
1023 setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
1024 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
1028 // Add multicast group membership on this interface
1029 if (err
== 0 && JoinMulticastGroup
)
1031 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
1032 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
1033 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
1034 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
1037 // Specify outgoing interface too
1038 if (err
== 0 && JoinMulticastGroup
)
1040 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
1041 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
1044 // Per the mDNS spec, send unicast packets with TTL 255
1047 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
1048 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
1051 // and multicast packets with TTL 255 too
1052 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
1055 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
1056 if (err
< 0 && errno
== EINVAL
)
1057 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
1058 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
1061 // And start listening for packets
1064 bindAddr
.sin_family
= AF_INET
;
1065 bindAddr
.sin_port
= port
.NotAnInteger
;
1066 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
1067 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
1068 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
1070 } // endif (intfAddr->sa_family == AF_INET)
1073 else if (intfAddr
->sa_family
== AF_INET6
)
1075 struct ipv6_mreq imr6
;
1076 struct sockaddr_in6 bindAddr6
;
1077 #if defined(IPV6_PKTINFO)
1080 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_PKTINFO
, &kOn
, sizeof(kOn
));
1081 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
1084 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
1086 #if defined(IPV6_HOPLIMIT)
1089 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_HOPLIMIT
, &kOn
, sizeof(kOn
));
1090 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
1094 // Add multicast group membership on this interface
1095 if (err
== 0 && JoinMulticastGroup
)
1097 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroup_v6
.ip
.v6
;
1098 imr6
.ipv6mr_interface
= interfaceIndex
;
1099 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
1100 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
1104 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
1105 perror("setsockopt - IPV6_JOIN_GROUP");
1109 // Specify outgoing interface too
1110 if (err
== 0 && JoinMulticastGroup
)
1112 u_int multicast_if
= interfaceIndex
;
1113 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
1114 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
1117 // We want to receive only IPv6 packets on this socket.
1118 // Without this option, we may get IPv4 addresses as mapped addresses.
1121 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
1122 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
1125 // Per the mDNS spec, send unicast packets with TTL 255
1128 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
1129 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
1132 // and multicast packets with TTL 255 too
1133 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
1136 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
1137 if (err
< 0 && errno
== EINVAL
)
1138 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
1139 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
1142 // And start listening for packets
1145 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
1146 #ifndef NOT_HAVE_SA_LEN
1147 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
1149 bindAddr6
.sin6_family
= AF_INET6
;
1150 bindAddr6
.sin6_port
= port
.NotAnInteger
;
1151 bindAddr6
.sin6_flowinfo
= 0;
1152 bindAddr6
.sin6_addr
= in6addr_any
; // Want to receive multicasts AND unicasts on this socket
1153 bindAddr6
.sin6_scope_id
= 0;
1154 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
1155 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
1157 } // endif (intfAddr->sa_family == AF_INET6)
1160 // Set the socket to non-blocking.
1163 err
= fcntl(*sktPtr
, F_GETFL
, 0);
1164 if (err
< 0) err
= errno
;
1167 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
1168 if (err
< 0) err
= errno
;
1173 if (err
!= 0 && *sktPtr
!= -1)
1176 rv
= close(*sktPtr
);
1180 assert((err
== 0) == (*sktPtr
!= -1));
1184 // Creates a PosixNetworkInterface for the interface whose IP address is
1185 // intfAddr and whose name is intfName and registers it with mDNS core.
1186 mDNSlocal
int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, struct sockaddr
*intfMask
, const char *intfName
, int intfIndex
)
1189 PosixNetworkInterface
*intf
;
1190 PosixNetworkInterface
*alias
= NULL
;
1193 assert(intfAddr
!= NULL
);
1194 assert(intfName
!= NULL
);
1195 assert(intfMask
!= NULL
);
1197 // Allocate the interface structure itself.
1198 intf
= (PosixNetworkInterface
*)calloc(1, sizeof(*intf
));
1199 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
1201 // And make a copy of the intfName.
1207 s
= strchr(intfName
, ':');
1210 len
= (s
- intfName
) + 1;
1214 len
= strlen(intfName
) + 1;
1216 intf
->intfName
= malloc(len
);
1217 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
1218 memcpy(intf
->intfName
, intfName
, len
- 1);
1219 intfName
[len
- 1] = 0;
1221 intf
->intfName
= strdup(intfName
);
1222 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
1228 // Set up the fields required by the mDNS core.
1229 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
1230 SockAddrTomDNSAddr(intfMask
, &intf
->coreIntf
.mask
, NULL
);
1232 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
1233 strncpy(intf
->coreIntf
.ifname
, intfName
, sizeof(intf
->coreIntf
.ifname
));
1234 intf
->coreIntf
.ifname
[sizeof(intf
->coreIntf
.ifname
)-1] = 0;
1236 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
1237 intf
->coreIntf
.McastTxRx
= mDNStrue
;
1239 // Set up the extra fields in PosixNetworkInterface.
1240 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
1241 intf
->index
= intfIndex
;
1242 intf
->multicastSocket4
= -1;
1244 intf
->multicastSocket6
= -1;
1246 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
1247 if (alias
== NULL
) alias
= intf
;
1248 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
1251 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
1254 // Set up the multicast socket
1257 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
1258 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
1260 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
1261 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
1265 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
1266 // and skip the probe phase of the probe/announce packet sequence.
1267 intf
->coreIntf
.DirectLink
= mDNSfalse
;
1268 #ifdef DIRECTLINK_INTERFACE_NAME
1269 if (strcmp(intfName
, STRINGIFY(DIRECTLINK_INTERFACE_NAME
)) == 0)
1270 intf
->coreIntf
.DirectLink
= mDNStrue
;
1272 intf
->coreIntf
.SupportsUnicastMDNSResponse
= mDNStrue
;
1274 // The interface is all ready to go, let's register it with the mDNS core.
1276 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
, NormalActivation
);
1281 num_registered_interfaces
++;
1282 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
1283 if (gMDNSPlatformPosixVerboseLevel
> 0)
1284 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
1288 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
1289 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
1290 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
1293 assert((err
== 0) == (intf
!= NULL
));
1298 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
1299 mDNSlocal
int SetupInterfaceList(mDNS
*const m
)
1301 mDNSBool foundav4
= mDNSfalse
;
1303 struct ifaddrs
*intfList
;
1304 struct ifaddrs
*firstLoopback
= NULL
;
1305 int firstLoopbackIndex
= 0;
1308 debugf("SetupInterfaceList");
1310 if (getifaddrs(&intfList
) < 0)
1314 if (intfList
== NULL
) err
= ENOENT
;
1318 struct ifaddrs
*i
= intfList
;
1321 if ( ((i
->ifa_addr
->sa_family
== AF_INET
)
1323 || (i
->ifa_addr
->sa_family
== AF_INET6
)
1325 ) && (i
->ifa_flags
& IFF_UP
) && !(i
->ifa_flags
& IFF_POINTOPOINT
))
1327 int ifIndex
= if_nametoindex(i
->ifa_name
);
1332 if (i
->ifa_flags
& IFF_LOOPBACK
)
1334 if (firstLoopback
== NULL
)
1337 firstLoopbackIndex
= ifIndex
;
1342 if (SetupOneInterface(m
, i
->ifa_addr
, i
->ifa_netmask
, i
->ifa_name
, ifIndex
) == 0)
1344 if (i
->ifa_addr
->sa_family
== AF_INET
)
1346 foundav4
= mDNStrue
;
1354 // If we found no normal interfaces but we did find a loopback interface, register the
1355 // loopback interface. This allows self-discovery if no interfaces are configured.
1356 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
1357 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
1358 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
1359 if (!foundav4
&& firstLoopback
)
1361 (void)SetupOneInterface(m
, firstLoopback
->ifa_addr
, firstLoopback
->ifa_netmask
, firstLoopback
->ifa_name
,
1362 firstLoopbackIndex
);
1367 if (intfList
!= NULL
) freeifaddrs(intfList
);
1369 // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
1370 PosixNetworkInterface
**ri
= &gRecentInterfaces
;
1371 const mDNSs32 utc
= mDNSPlatformUTC();
1374 PosixNetworkInterface
*pi
= *ri
;
1375 if (utc
- pi
->LastSeen
< 60) ri
= (PosixNetworkInterface
**)&pi
->coreIntf
.next
;
1376 else { *ri
= (PosixNetworkInterface
*)pi
->coreIntf
.next
; free(pi
); }
1384 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1386 // Open a socket that will receive interface change notifications
1387 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1389 mStatus err
= mStatus_NoError
;
1390 struct sockaddr_nl snl
;
1394 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
1398 // Configure read to be non-blocking because inbound msg size is not known in advance
1399 (void) fcntl(sock
, F_SETFL
, O_NONBLOCK
);
1401 /* Subscribe the socket to Link & IP addr notifications. */
1402 mDNSPlatformMemZero(&snl
, sizeof snl
);
1403 snl
.nl_family
= AF_NETLINK
;
1404 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
1405 ret
= bind(sock
, (struct sockaddr
*) &snl
, sizeof snl
);
1415 mDNSlocal
void PrintNetLinkMsg(const struct nlmsghdr
*pNLMsg
)
1417 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1418 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1420 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
1421 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[pNLMsg
->nlmsg_type
- RTM_BASE
],
1422 pNLMsg
->nlmsg_flags
);
1424 if (RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
1426 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA(pNLMsg
);
1427 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
1428 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
1431 else if (RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
1433 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
);
1434 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
1435 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1441 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1442 // Read through the messages on sd and if any indicate that any interface records should
1443 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1447 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1450 // The structure here is more complex than it really ought to be because,
1451 // unfortunately, there's no good way to size a buffer in advance large
1452 // enough to hold all pending data and so avoid message fragmentation.
1453 // (Note that FIONREAD is not supported on AF_NETLINK.)
1455 readCount
= read(sd
, buff
, sizeof buff
);
1458 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1459 // If not, discard already-processed messages in buffer and read more data.
1460 if (((char*) &pNLMsg
[1] > (buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1461 ((char*) pNLMsg
+ pNLMsg
->nlmsg_len
> (buff
+ readCount
)))
1463 if (buff
< (char*) pNLMsg
) // we have space to shuffle
1465 // discard processed data
1466 readCount
-= ((char*) pNLMsg
- buff
);
1467 memmove(buff
, pNLMsg
, readCount
);
1468 pNLMsg
= (struct nlmsghdr
*) buff
;
1471 readCount
+= read(sd
, buff
+ readCount
, sizeof buff
- readCount
);
1472 continue; // spin around and revalidate with new readCount
1475 break; // Otherwise message does not fit in buffer
1479 PrintNetLinkMsg(pNLMsg
);
1482 // Process the NetLink message
1483 if (pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1484 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA(pNLMsg
))->ifi_index
;
1485 else if (pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1486 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
))->ifa_index
;
1488 // Advance pNLMsg to the next message in the buffer
1489 if ((pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1491 ssize_t len
= readCount
- ((char*)pNLMsg
- buff
);
1492 pNLMsg
= NLMSG_NEXT(pNLMsg
, len
);
1501 #else // USES_NETLINK
1503 // Open a socket that will receive interface change notifications
1504 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1506 *pFD
= socket(AF_ROUTE
, SOCK_RAW
, 0);
1509 return mStatus_UnknownErr
;
1511 // Configure read to be non-blocking because inbound msg size is not known in advance
1512 (void) fcntl(*pFD
, F_SETFL
, O_NONBLOCK
);
1514 return mStatus_NoError
;
1518 mDNSlocal
void PrintRoutingSocketMsg(const struct ifa_msghdr
*pRSMsg
)
1520 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1521 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1522 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1524 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1526 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[pRSMsg
->ifam_type
], index
);
1530 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1531 // Read through the messages on sd and if any indicate that any interface records should
1532 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1536 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1539 readCount
= read(sd
, buff
, sizeof buff
);
1540 if (readCount
< (ssize_t
) sizeof(struct ifa_msghdr
))
1541 return mStatus_UnsupportedErr
; // cannot decipher message
1544 PrintRoutingSocketMsg(pRSMsg
);
1547 // Process the message
1548 if (pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1549 pRSMsg
->ifam_type
== RTM_IFINFO
)
1551 if (pRSMsg
->ifam_type
== RTM_IFINFO
)
1552 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1554 result
|= 1 << pRSMsg
->ifam_index
;
1560 #endif // USES_NETLINK
1562 // Called when data appears on interface change notification socket
1563 mDNSlocal
void InterfaceChangeCallback(int fd
, void *context
)
1565 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1567 mDNSu32 changedInterfaces
= 0;
1568 struct timeval zeroTimeout
= { 0, 0 };
1573 FD_SET(pChgRec
->NotifySD
, &readFDs
);
1577 changedInterfaces
|= ProcessRoutingNotification(pChgRec
->NotifySD
);
1579 while (0 < select(pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1581 // Currently we rebuild the entire interface list whenever any interface change is
1582 // detected. If this ever proves to be a performance issue in a multi-homed
1583 // configuration, more care should be paid to changedInterfaces.
1584 if (changedInterfaces
)
1585 mDNSPlatformPosixRefreshInterfaceList(pChgRec
->mDNS
);
1588 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1589 mDNSlocal mStatus
WatchForInterfaceChange(mDNS
*const m
)
1592 IfChangeRec
*pChgRec
;
1594 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocateClear(sizeof *pChgRec
);
1595 if (pChgRec
== NULL
)
1596 return mStatus_NoMemoryErr
;
1599 err
= OpenIfNotifySocket(&pChgRec
->NotifySD
);
1601 err
= mDNSPosixAddFDToEventLoop(pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1603 mDNSPlatformMemFree(pChgRec
);
1608 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1609 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1610 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1611 mDNSlocal mDNSBool
mDNSPlatformInit_CanReceiveUnicast(void)
1614 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1615 struct sockaddr_in s5353
;
1616 s5353
.sin_family
= AF_INET
;
1617 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1618 s5353
.sin_addr
.s_addr
= 0;
1619 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1621 if (err
) debugf("No unicast UDP responses");
1622 else debugf("Unicast UDP responses okay");
1626 // mDNS core calls this routine to initialise the platform-specific data.
1627 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1633 if (mDNSPlatformInit_CanReceiveUnicast()) m
->CanReceiveUnicastOn5353
= mDNStrue
;
1635 // Tell mDNS core the names of this machine.
1637 // Set up the nice label
1638 m
->nicelabel
.c
[0] = 0;
1639 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1640 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Computer");
1642 // Set up the RFC 1034-compliant label
1643 m
->hostlabel
.c
[0] = 0;
1644 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1645 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Computer");
1649 sa
.sa_family
= AF_INET
;
1650 m
->p
->unicastSocket4
= -1;
1651 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1653 sa
.sa_family
= AF_INET6
;
1654 m
->p
->unicastSocket6
= -1;
1655 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1658 // Tell mDNS core about the network interfaces on this machine.
1659 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1661 // Tell mDNS core about DNS Servers
1663 if (err
== mStatus_NoError
) ParseDNSServers(m
, uDNS_SERVERS_FILE
);
1666 if (err
== mStatus_NoError
)
1668 err
= WatchForInterfaceChange(m
);
1669 // Failure to observe interface changes is non-fatal.
1670 if (err
!= mStatus_NoError
)
1672 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1673 err
= mStatus_NoError
;
1677 // We don't do asynchronous initialization on the Posix platform, so by the time
1678 // we get here the setup will already have succeeded or failed. If it succeeded,
1679 // we should just call mDNSCoreInitComplete() immediately.
1680 if (err
== mStatus_NoError
)
1681 mDNSCoreInitComplete(m
, mStatus_NoError
);
1683 return PosixErrorToStatus(err
);
1686 // mDNS core calls this routine to clean up the platform-specific data.
1687 // In our case all we need to do is to tear down every network interface.
1688 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1692 ClearInterfaceList(m
);
1693 if (m
->p
->unicastSocket4
!= -1)
1695 rv
= close(m
->p
->unicastSocket4
);
1699 if (m
->p
->unicastSocket6
!= -1)
1701 rv
= close(m
->p
->unicastSocket6
);
1707 // This is used internally by InterfaceChangeCallback.
1708 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1709 // can call it in response to a SIGHUP (mainly for debugging purposes).
1710 mDNSexport mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1713 // This is a pretty heavyweight way to process interface changes --
1714 // destroying the entire interface list and then making fresh one from scratch.
1715 // We should make it like the OS X version, which leaves unchanged interfaces alone.
1716 ClearInterfaceList(m
);
1717 err
= SetupInterfaceList(m
);
1718 return PosixErrorToStatus(err
);
1721 #if COMPILER_LIKES_PRAGMA_MARK
1722 #pragma mark ***** Locking
1725 // On the Posix platform, locking is a no-op because we only ever enter
1726 // mDNS core on the main thread.
1728 // mDNS core calls this routine when it wants to prevent
1729 // the platform from reentering mDNS core code.
1730 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1735 // mDNS core calls this routine when it release the lock taken by
1736 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1737 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1742 #if COMPILER_LIKES_PRAGMA_MARK
1743 #pragma mark ***** Strings
1746 mDNSexport mDNSu32
mDNSPlatformStrLCopy(void *dst
, const void *src
, mDNSu32 len
)
1749 return ((mDNSu32
)strlcpy((char *)dst
, (const char *)src
, len
));
1753 srcLen
= strlen((const char *)src
);
1756 memcpy(dst
, src
, srcLen
+ 1);
1760 memcpy(dst
, src
, len
- 1);
1761 ((char *)dst
)[len
- 1] = '\0';
1764 return ((mDNSu32
)srcLen
);
1768 // mDNS core calls this routine to get the length of a C string.
1769 // On the Posix platform this maps directly to the ANSI C strlen.
1770 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1772 return strlen((const char*)src
);
1775 // mDNS core calls this routine to copy memory.
1776 // On the Posix platform this maps directly to the ANSI C memcpy.
1777 mDNSexport
void mDNSPlatformMemCopy(void *dst
, const void *src
, mDNSu32 len
)
1779 memcpy(dst
, src
, len
);
1782 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1783 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1784 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *dst
, const void *src
, mDNSu32 len
)
1786 return memcmp(dst
, src
, len
) == 0;
1789 // If the caller wants to know the exact return of memcmp, then use this instead
1790 // of mDNSPlatformMemSame
1791 mDNSexport
int mDNSPlatformMemCmp(const void *dst
, const void *src
, mDNSu32 len
)
1793 return (memcmp(dst
, src
, len
));
1796 mDNSexport
void mDNSPlatformQsort(void *base
, int nel
, int width
, int (*compar
)(const void *, const void *))
1798 return (qsort(base
, nel
, width
, compar
));
1801 // DNSSEC stub functions
1802 mDNSexport
void VerifySignature(mDNS
*const m
, DNSSECVerifier
*dv
, DNSQuestion
*q
)
1809 mDNSexport mDNSBool
AddNSECSForCacheRecord(mDNS
*const m
, CacheRecord
*crlist
, CacheRecord
*negcr
, mDNSu8 rcode
)
1818 mDNSexport
void BumpDNSSECStats(mDNS
*const m
, DNSSECStatsAction action
, DNSSECStatsType type
, mDNSu32 value
)
1826 // Proxy stub functions
1827 mDNSexport mDNSu8
*DNSProxySetAttributes(DNSQuestion
*q
, DNSMessageHeader
*h
, DNSMessage
*msg
, mDNSu8
*ptr
, mDNSu8
*limit
)
1838 mDNSexport
void DNSProxyInit(mDNSu32 IpIfArr
[], mDNSu32 OpIf
)
1844 mDNSexport
void DNSProxyTerminate(void)
1848 // mDNS core calls this routine to clear blocks of memory.
1849 // On the Posix platform this is a simple wrapper around ANSI C memset.
1850 mDNSexport
void mDNSPlatformMemZero(void *dst
, mDNSu32 len
)
1852 memset(dst
, 0, len
);
1855 #if !MDNS_MALLOC_DEBUGGING
1856 mDNSexport
void *mDNSPlatformMemAllocate(mDNSu32 len
) { return(mallocL("mDNSPlatformMemAllocate", len
)); }
1857 mDNSexport
void *mDNSPlatformMemAllocateClear(mDNSu32 len
) { return(callocL(name
, len
)); }
1858 mDNSexport
void mDNSPlatformMemFree (void *mem
) { freeL("mDNSPlatformMemFree", mem
); }
1861 #if _PLATFORM_HAS_STRONG_PRNG_
1862 mDNSexport mDNSu32
mDNSPlatformRandomNumber(void)
1864 return(arc4random());
1867 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
1870 gettimeofday(&tv
, NULL
);
1875 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1877 mDNSexport mStatus
mDNSPlatformTimeInit(void)
1879 // No special setup is required on Posix -- we just use gettimeofday();
1880 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1881 // We should find a better way to do this
1882 return(mStatus_NoError
);
1885 mDNSexport mDNSs32
mDNSPlatformRawTime()
1888 int ret
= clock_gettime(CLOCK_MONOTONIC
, &tm
);
1889 assert(ret
== 0); // This call will only fail if the number of seconds does not fit in an object of type time_t.
1891 // tm.tv_sec is seconds since some unspecified starting point (it is usually the system start up time)
1892 // tm.tv_nsec is nanoseconds since the start of this second (i.e. values 0 to 999999999)
1893 // We use the lower 22 bits of tm.tv_sec for the top 22 bits of our result
1894 // and we multiply tm.tv_nsec by 2 / 1953125 to get a value in the range 0-1023 to go in the bottom 10 bits.
1895 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1896 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1898 return ((tm
.tv_sec
<< 10) | (tm
.tv_nsec
* 2 / 1953125));
1901 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1906 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID
, char *EthAddr
, char *IPAddr
, int iteration
)
1914 mDNSexport mDNSBool
mDNSPlatformValidRecordForInterface(const AuthRecord
*rr
, mDNSInterfaceID InterfaceID
)
1922 mDNSexport mDNSBool
mDNSPlatformValidQuestionForInterface(DNSQuestion
*q
, const NetworkInterfaceInfo
*intf
)
1930 // Used for debugging purposes. For now, just set the buffer to zero
1931 mDNSexport
void mDNSPlatformFormatTime(unsigned long te
, mDNSu8
*buf
, int bufsize
)
1934 if (bufsize
) buf
[0] = 0;
1937 mDNSexport
void mDNSPlatformSendKeepalive(mDNSAddr
*sadd
, mDNSAddr
*dadd
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu32 seq
, mDNSu32 ack
, mDNSu16 win
)
1939 (void) sadd
; // Unused
1940 (void) dadd
; // Unused
1941 (void) lport
; // Unused
1942 (void) rport
; // Unused
1943 (void) seq
; // Unused
1944 (void) ack
; // Unused
1945 (void) win
; // Unused
1948 mDNSexport mStatus
mDNSPlatformRetrieveTCPInfo(mDNSAddr
*laddr
, mDNSIPPort
*lport
, mDNSAddr
*raddr
, mDNSIPPort
*rport
, mDNSTCPInfo
*mti
)
1950 (void) laddr
; // Unused
1951 (void) raddr
; // Unused
1952 (void) lport
; // Unused
1953 (void) rport
; // Unused
1954 (void) mti
; // Unused
1956 return mStatus_NoError
;
1959 mDNSexport mStatus
mDNSPlatformGetRemoteMacAddr(mDNSAddr
*raddr
)
1961 (void) raddr
; // Unused
1963 return mStatus_NoError
;
1966 mDNSexport mStatus
mDNSPlatformStoreSPSMACAddr(mDNSAddr
*spsaddr
, char *ifname
)
1968 (void) spsaddr
; // Unused
1969 (void) ifname
; // Unused
1971 return mStatus_NoError
;
1974 mDNSexport mStatus
mDNSPlatformClearSPSData(void)
1976 return mStatus_NoError
;
1979 mDNSexport mStatus
mDNSPlatformStoreOwnerOptRecord(char *ifname
, DNSMessage
*msg
, int length
)
1981 (void) ifname
; // Unused
1982 (void) msg
; // Unused
1983 (void) length
; // Unused
1984 return mStatus_UnsupportedErr
;
1987 mDNSexport mDNSu16
mDNSPlatformGetUDPPort(UDPSocket
*sock
)
1989 (void) sock
; // unused
1994 mDNSexport mDNSBool
mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID
)
1996 (void) InterfaceID
; // unused
2001 mDNSexport
void mDNSPlatformSetSocktOpt(void *sock
, mDNSTransport_Type transType
, mDNSAddr_Type addrType
, const DNSQuestion
*q
)
2009 mDNSexport mDNSs32
mDNSPlatformGetPID()
2014 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
2016 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
2020 mDNSexport
void mDNSPosixGetFDSetForSelect(mDNS
*m
, int *nfds
, fd_set
*readfds
, fd_set
*writefds
)
2023 PosixEventSource
*iSource
;
2025 // 2. Build our list of active file descriptors
2026 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
2027 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(&numFDs
, readfds
, m
->p
->unicastSocket4
);
2029 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(&numFDs
, readfds
, m
->p
->unicastSocket6
);
2033 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(&numFDs
, readfds
, info
->multicastSocket4
);
2035 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(&numFDs
, readfds
, info
->multicastSocket6
);
2037 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
2040 // Copy over the event fds. We have to do it this way because client-provided event loops expect
2041 // to initialize their FD sets first and then call mDNSPosixGetFDSet()
2042 for (iSource
= gEventSources
; iSource
; iSource
= iSource
->next
)
2044 if (iSource
->readCallback
!= NULL
)
2045 FD_SET(iSource
->fd
, readfds
);
2046 if (iSource
->writeCallback
!= NULL
)
2047 FD_SET(iSource
->fd
, writefds
);
2048 if (numFDs
<= iSource
->fd
)
2049 numFDs
= iSource
->fd
+ 1;
2054 mDNSexport
void mDNSPosixGetNextDNSEventTime(mDNS
*m
, struct timeval
*timeout
)
2057 struct timeval interval
;
2059 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
2060 mDNSs32 nextevent
= mDNS_Execute(m
);
2062 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
2063 ticks
= nextevent
- mDNS_TimeNow(m
);
2064 if (ticks
< 1) ticks
= 1;
2065 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
2066 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
2068 // 4. If client's proposed timeout is more than what we want, then reduce it
2069 if (timeout
->tv_sec
> interval
.tv_sec
||
2070 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
2071 *timeout
= interval
;
2074 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, fd_set
*writefds
, struct timeval
*timeout
)
2076 mDNSPosixGetNextDNSEventTime(m
, timeout
);
2077 mDNSPosixGetFDSetForSelect(m
, nfds
, readfds
, writefds
);
2080 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
, fd_set
*writefds
)
2082 PosixNetworkInterface
*info
;
2083 PosixEventSource
*iSource
;
2085 assert(readfds
!= NULL
);
2086 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
2088 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
2090 FD_CLR(m
->p
->unicastSocket4
, readfds
);
2091 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
2094 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
2096 FD_CLR(m
->p
->unicastSocket6
, readfds
);
2097 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
2103 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
2105 FD_CLR(info
->multicastSocket4
, readfds
);
2106 SocketDataReady(m
, info
, info
->multicastSocket4
);
2109 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
2111 FD_CLR(info
->multicastSocket6
, readfds
);
2112 SocketDataReady(m
, info
, info
->multicastSocket6
);
2115 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
2118 // Now process routing socket events, discovery relay events and anything else of that ilk.
2119 for (iSource
= gEventSources
; iSource
; iSource
= iSource
->next
)
2121 if (iSource
->readCallback
!= NULL
&& FD_ISSET(iSource
->fd
, readfds
))
2123 iSource
->readCallback(iSource
->fd
, iSource
->readContext
);
2124 break; // in case callback removed elements from gEventSources
2126 else if (iSource
->writeCallback
!= NULL
&& FD_ISSET(iSource
->fd
, writefds
))
2128 mDNSPosixEventCallback writeCallback
= iSource
->writeCallback
;
2129 // Write events are one-shot: to get another event, the consumer has to put in a new request.
2130 // We reset this before calling the callback just in case the callback requests another write
2131 // callback, or deletes the event context from the list.
2132 iSource
->writeCallback
= NULL
;
2133 writeCallback(iSource
->fd
, iSource
->writeContext
);
2134 break; // in case callback removed elements from gEventSources
2139 mDNSu32 mDNSPlatformEventContextSize
= sizeof (PosixEventSource
);
2141 mDNSlocal
void requestIOEvents(PosixEventSource
*newSource
, const char *taskName
,
2142 mDNSPosixEventCallback callback
, void *context
, int flag
)
2144 PosixEventSource
**epp
= &gEventSources
;
2146 if (newSource
->fd
>= (int) FD_SETSIZE
|| newSource
->fd
< 0)
2148 LogMsg("requestIOEvents called with fd %d > FD_SETSIZE %d.", newSource
->fd
, FD_SETSIZE
);
2151 if (callback
== NULL
)
2153 LogMsg("requestIOEvents called no callback.", newSource
->fd
, FD_SETSIZE
);
2157 // See if this event context is already on the list; if it is, no need to scan the list.
2158 if (!(newSource
->flags
& PosixEventFlag_OnList
))
2162 // This should never happen.
2163 if (newSource
== *epp
)
2165 LogMsg("Event context marked not on list but is on list.");
2168 epp
= &(*epp
)->next
;
2173 newSource
->next
= NULL
;
2174 newSource
->flags
= PosixEventFlag_OnList
;
2178 if (flag
& PosixEventFlag_Read
)
2180 newSource
->readCallback
= callback
;
2181 newSource
->readContext
= context
;
2182 newSource
->flags
|= PosixEventFlag_Read
;
2183 newSource
->readTaskName
= taskName
;
2185 if (flag
& PosixEventFlag_Write
)
2187 newSource
->writeCallback
= callback
;
2188 newSource
->writeContext
= context
;
2189 newSource
->flags
|= PosixEventFlag_Write
;
2190 newSource
->writeTaskName
= taskName
;
2194 mDNSlocal
void requestReadEvents(PosixEventSource
*eventSource
,
2195 const char *taskName
, mDNSPosixEventCallback callback
, void *context
)
2197 requestIOEvents(eventSource
, taskName
, callback
, context
, PosixEventFlag_Read
);
2200 mDNSlocal
void requestWriteEvents(PosixEventSource
*eventSource
,
2201 const char *taskName
, mDNSPosixEventCallback callback
, void *context
)
2203 requestIOEvents(eventSource
, taskName
, callback
, context
, PosixEventFlag_Write
);
2206 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
2207 mDNSlocal mStatus
stopReadOrWriteEvents(int fd
, mDNSBool freeContext
, mDNSBool removeContext
, int flags
)
2209 PosixEventSource
*iSource
, **epp
= &gEventSources
;
2214 if (fd
== iSource
->fd
)
2216 if (flags
& PosixEventFlag_Read
)
2218 iSource
->readCallback
= NULL
;
2219 iSource
->readContext
= NULL
;
2221 if (flags
& PosixEventFlag_Write
)
2223 iSource
->writeCallback
= NULL
;
2224 iSource
->writeContext
= NULL
;
2226 if (iSource
->writeCallback
== NULL
&& iSource
->readCallback
== NULL
)
2228 if (removeContext
|| freeContext
)
2229 *epp
= iSource
->next
;
2233 return mStatus_NoError
;
2235 epp
= &(*epp
)->next
;
2237 return mStatus_NoSuchNameErr
;
2240 // Some of the mDNSPosix client code relies on being able to add FDs to the event loop without
2241 // providing storage for the event-related info. mDNSPosixAddFDToEventLoop and
2242 // mDNSPosixRemoveFDFromEventLoop handle the event structure storage automatically.
2243 mStatus
mDNSPosixAddFDToEventLoop(int fd
, mDNSPosixEventCallback callback
, void *context
)
2245 PosixEventSource
*newSource
;
2247 newSource
= (PosixEventSource
*) malloc(sizeof *newSource
);
2248 if (NULL
== newSource
)
2249 return mStatus_NoMemoryErr
;
2250 memset(newSource
, 0, sizeof *newSource
);
2253 requestReadEvents(newSource
, "mDNSPosixAddFDToEventLoop", callback
, context
);
2254 return mStatus_NoError
;
2257 mStatus
mDNSPosixRemoveFDFromEventLoop(int fd
)
2259 return stopReadOrWriteEvents(fd
, mDNStrue
, mDNStrue
, PosixEventFlag_Read
| PosixEventFlag_Write
);
2262 // Simply note the received signal in gEventSignals.
2263 mDNSlocal
void NoteSignal(int signum
)
2265 sigaddset(&gEventSignals
, signum
);
2268 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
2269 mStatus
mDNSPosixListenForSignalInEventLoop(int signum
)
2271 struct sigaction action
;
2274 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
2275 action
.sa_handler
= NoteSignal
;
2276 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
2278 sigaddset(&gEventSignalSet
, signum
);
2283 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
2284 mStatus
mDNSPosixIgnoreSignalInEventLoop(int signum
)
2286 struct sigaction action
;
2289 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
2290 action
.sa_handler
= SIG_DFL
;
2291 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
2293 sigdelset(&gEventSignalSet
, signum
);
2298 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
2299 // Return as soon as internal timeout expires, or a signal we're listening for is received.
2300 mStatus
mDNSPosixRunEventLoopOnce(mDNS
*m
, const struct timeval
*pTimeout
,
2301 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
2305 int numFDs
= 0, numReady
;
2306 struct timeval timeout
= *pTimeout
;
2308 // 1. Set up the fd_set as usual here.
2309 // This example client has no file descriptors of its own,
2310 // but a real application would call FD_SET to add them to the set here
2311 FD_ZERO(&listenFDs
);
2314 // 2. Set up the timeout.
2315 mDNSPosixGetNextDNSEventTime(m
, &timeout
);
2317 // Include the sockets that are listening to the wire in our select() set
2318 mDNSPosixGetFDSetForSelect(m
, &numFDs
, &listenFDs
, &writeFDs
);
2319 numReady
= select(numFDs
, &listenFDs
, &writeFDs
, (fd_set
*) NULL
, &timeout
);
2323 mDNSPosixProcessFDSet(m
, &listenFDs
, &writeFDs
);
2324 *pDataDispatched
= mDNStrue
;
2326 else if (numReady
< 0)
2328 if (errno
!= EINTR
) {
2329 // This should never happen, represents a coding error, and is not recoverable, since
2330 // we'll just sit here spinning and never receive another event. The usual reason for
2331 // it to happen is that an FD was closed but not removed from the event list.
2332 LogMsg("select failed: %s", strerror(errno
));
2337 *pDataDispatched
= mDNSfalse
;
2339 (void) sigprocmask(SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
2340 *pSignalsReceived
= gEventSignals
;
2341 sigemptyset(&gEventSignals
);
2342 (void) sigprocmask(SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
2344 return mStatus_NoError
;