1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
20 #include "DNSCommon.h"
21 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
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"
57 // ***************************************************************************
60 // We keep a list of client-supplied event sources in PosixEventSource records
61 struct PosixEventSource
63 mDNSPosixEventCallback Callback
;
66 struct PosixEventSource
*Next
;
68 typedef struct PosixEventSource PosixEventSource
;
70 // Context record for interface change callback
76 typedef struct IfChangeRec IfChangeRec
;
78 // Note that static data is initialized to zero in (modern) C.
79 static fd_set gEventFDs
;
80 static int gMaxFD
; // largest fd in gEventFDs
81 static GenLinkedList gEventSources
; // linked list of PosixEventSource's
82 static sigset_t gEventSignalSet
; // Signals which event loop listens for
83 static sigset_t gEventSignals
; // Signals which were received while inside loop
85 static PosixNetworkInterface
*gRecentInterfaces
;
87 // ***************************************************************************
88 // Globals (for debugging)
90 static int num_registered_interfaces
= 0;
91 static int num_pkts_accepted
= 0;
92 static int num_pkts_rejected
= 0;
94 // ***************************************************************************
97 int gMDNSPlatformPosixVerboseLevel
= 0;
99 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
101 mDNSlocal
void SockAddrTomDNSAddr(const struct sockaddr
*const sa
, mDNSAddr
*ipAddr
, mDNSIPPort
*ipPort
)
103 switch (sa
->sa_family
)
107 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
108 ipAddr
->type
= mDNSAddrType_IPv4
;
109 ipAddr
->ip
.v4
.NotAnInteger
= sin
->sin_addr
.s_addr
;
110 if (ipPort
) ipPort
->NotAnInteger
= sin
->sin_port
;
117 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
118 #ifndef NOT_HAVE_SA_LEN
119 assert(sin6
->sin6_len
== sizeof(*sin6
));
121 ipAddr
->type
= mDNSAddrType_IPv6
;
122 ipAddr
->ip
.v6
= *(mDNSv6Addr
*)&sin6
->sin6_addr
;
123 if (ipPort
) ipPort
->NotAnInteger
= sin6
->sin6_port
;
129 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa
->sa_family
);
130 ipAddr
->type
= mDNSAddrType_None
;
131 if (ipPort
) ipPort
->NotAnInteger
= 0;
136 #if COMPILER_LIKES_PRAGMA_MARK
137 #pragma mark ***** Send and Receive
140 // mDNS core calls this routine when it needs to send a packet.
141 mDNSexport mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
142 mDNSInterfaceID InterfaceID
, UDPSocket
*src
, const mDNSAddr
*dst
,
143 mDNSIPPort dstPort
, mDNSBool useBackgroundTrafficClass
)
146 struct sockaddr_storage to
;
147 PosixNetworkInterface
* thisIntf
= (PosixNetworkInterface
*)(InterfaceID
);
148 int sendingsocket
= -1;
150 (void)src
; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
151 (void) useBackgroundTrafficClass
;
156 assert((((char *) end
) - ((char *) msg
)) > 0);
158 if (dstPort
.NotAnInteger
== 0)
160 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
161 return PosixErrorToStatus(EINVAL
);
163 if (dst
->type
== mDNSAddrType_IPv4
)
165 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&to
;
166 #ifndef NOT_HAVE_SA_LEN
167 sin
->sin_len
= sizeof(*sin
);
169 sin
->sin_family
= AF_INET
;
170 sin
->sin_port
= dstPort
.NotAnInteger
;
171 sin
->sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
172 sendingsocket
= thisIntf
? thisIntf
->multicastSocket4
: m
->p
->unicastSocket4
;
176 else if (dst
->type
== mDNSAddrType_IPv6
)
178 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&to
;
179 mDNSPlatformMemZero(sin6
, sizeof(*sin6
));
180 #ifndef NOT_HAVE_SA_LEN
181 sin6
->sin6_len
= sizeof(*sin6
);
183 sin6
->sin6_family
= AF_INET6
;
184 sin6
->sin6_port
= dstPort
.NotAnInteger
;
185 sin6
->sin6_addr
= *(struct in6_addr
*)&dst
->ip
.v6
;
186 sendingsocket
= thisIntf
? thisIntf
->multicastSocket6
: m
->p
->unicastSocket6
;
190 if (sendingsocket
>= 0)
191 err
= sendto(sendingsocket
, msg
, (char*)end
- (char*)msg
, 0, (struct sockaddr
*)&to
, GET_SA_LEN(to
));
193 if (err
> 0) err
= 0;
196 static int MessageCount
= 0;
197 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
198 if (!mDNSAddressIsAllDNSLinkGroup(dst
))
199 if (errno
== EHOSTDOWN
|| errno
== ENETDOWN
|| errno
== EHOSTUNREACH
|| errno
== ENETUNREACH
) return(mStatus_TransientErr
);
201 if (MessageCount
< 1000)
205 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
206 errno
, strerror(errno
), dst
, &thisIntf
->coreIntf
.ip
, thisIntf
->intfName
, thisIntf
->index
);
208 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno
, strerror(errno
), dst
);
212 return PosixErrorToStatus(err
);
215 // This routine is called when the main loop detects that data is available on a socket.
216 mDNSlocal
void SocketDataReady(mDNS
*const m
, PosixNetworkInterface
*intf
, int skt
)
218 mDNSAddr senderAddr
, destAddr
;
219 mDNSIPPort senderPort
;
222 struct my_in_pktinfo packetInfo
;
223 struct sockaddr_storage from
;
228 const mDNSInterfaceID InterfaceID
= intf
? intf
->coreIntf
.InterfaceID
: NULL
;
233 fromLen
= sizeof(from
);
235 packetLen
= recvfrom_flags(skt
, &packet
, sizeof(packet
), &flags
, (struct sockaddr
*) &from
, &fromLen
, &packetInfo
, &ttl
);
239 SockAddrTomDNSAddr((struct sockaddr
*)&from
, &senderAddr
, &senderPort
);
240 SockAddrTomDNSAddr((struct sockaddr
*)&packetInfo
.ipi_addr
, &destAddr
, NULL
);
242 // If we have broken IP_RECVDSTADDR functionality (so far
243 // I've only seen this on OpenBSD) then apply a hack to
244 // convince mDNS Core that this isn't a spoof packet.
245 // Basically what we do is check to see whether the
246 // packet arrived as a multicast and, if so, set its
247 // destAddr to the mDNS address.
249 // I must admit that I could just be doing something
250 // wrong on OpenBSD and hence triggering this problem
251 // but I'm at a loss as to how.
253 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
254 // no way to tell the destination address or interface this packet arrived on,
255 // so all we can do is just assume it's a multicast
257 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
258 if ((destAddr
.NotAnInteger
== 0) && (flags
& MSG_MCAST
))
260 destAddr
.type
= senderAddr
.type
;
261 if (senderAddr
.type
== mDNSAddrType_IPv4
) destAddr
.ip
.v4
= AllDNSLinkGroup_v4
.ip
.v4
;
262 else if (senderAddr
.type
== mDNSAddrType_IPv6
) destAddr
.ip
.v6
= AllDNSLinkGroup_v6
.ip
.v6
;
266 // We only accept the packet if the interface on which it came
267 // in matches the interface associated with this socket.
268 // We do this match by name or by index, depending on which
269 // information is available. recvfrom_flags sets the name
270 // to "" if the name isn't available, or the index to -1
271 // if the index is available. This accomodates the various
272 // different capabilities of our target platforms.
277 // Ignore multicasts accidentally delivered to our unicast receiving socket
278 if (mDNSAddrIsDNSMulticast(&destAddr
)) packetLen
= -1;
282 if (packetInfo
.ipi_ifname
[0] != 0) reject
= (strcmp(packetInfo
.ipi_ifname
, intf
->intfName
) != 0);
283 else if (packetInfo
.ipi_ifindex
!= -1) reject
= (packetInfo
.ipi_ifindex
!= intf
->index
);
287 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
288 &senderAddr
, &destAddr
, packetInfo
.ipi_ifname
, packetInfo
.ipi_ifindex
,
289 &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
292 if (num_pkts_rejected
> (num_pkts_accepted
+ 1) * (num_registered_interfaces
+ 1) * 2)
295 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
296 num_pkts_accepted
+ num_pkts_rejected
, num_pkts_accepted
, num_pkts_rejected
);
297 num_pkts_accepted
= 0;
298 num_pkts_rejected
= 0;
303 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
304 &senderAddr
, &destAddr
, &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
311 mDNSCoreReceive(m
, &packet
, (mDNSu8
*)&packet
+ packetLen
,
312 &senderAddr
, senderPort
, &destAddr
, MulticastDNSPort
, InterfaceID
);
315 mDNSexport TCPSocket
*mDNSPlatformTCPSocket(TCPSocketFlags flags
, mDNSIPPort
* port
, mDNSBool useBackgroundTrafficClass
)
317 (void)flags
; // Unused
318 (void)port
; // Unused
319 (void)useBackgroundTrafficClass
; // Unused
323 mDNSexport TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int sd
)
325 (void)flags
; // Unused
330 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
332 (void)sock
; // Unused
336 mDNSexport mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
, domainname
*hostname
, mDNSInterfaceID InterfaceID
,
337 TCPConnectionCallback callback
, void *context
)
339 (void)sock
; // Unused
341 (void)dstport
; // Unused
342 (void)hostname
; // Unused
343 (void)InterfaceID
; // Unused
344 (void)callback
; // Unused
345 (void)context
; // Unused
346 return(mStatus_UnsupportedErr
);
349 mDNSexport
void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
)
351 (void)sock
; // Unused
354 mDNSexport
long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
* closed
)
356 (void)sock
; // Unused
358 (void)buflen
; // Unused
359 (void)closed
; // Unused
363 mDNSexport
long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
)
365 (void)sock
; // Unused
371 mDNSexport UDPSocket
*mDNSPlatformUDPSocket(mDNSIPPort port
)
373 (void)port
; // Unused
377 mDNSexport
void mDNSPlatformUDPClose(UDPSocket
*sock
)
379 (void)sock
; // Unused
382 mDNSexport
void mDNSPlatformUpdateProxyList(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(const mDNSAddr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
)
398 (void)InterfaceID
; // Unused
401 mDNSexport mStatus
mDNSPlatformTLSSetupCerts(void)
403 return(mStatus_UnsupportedErr
);
406 mDNSexport
void mDNSPlatformTLSTearDownCerts(void)
410 mDNSexport
void mDNSPlatformSetAllowSleep(mDNSBool allowSleep
, const char *reason
)
416 #if COMPILER_LIKES_PRAGMA_MARK
418 #pragma mark - /etc/hosts support
421 mDNSexport
void FreeEtcHosts(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
429 #if COMPILER_LIKES_PRAGMA_MARK
430 #pragma mark ***** DDNS Config Platform Functions
433 mDNSexport mDNSBool
mDNSPlatformSetDNSConfig(mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
,
434 DNameListElem
**BrowseDomains
, mDNSBool ackConfig
)
440 (void) BrowseDomains
;
446 mDNSexport mStatus
mDNSPlatformGetPrimaryInterface(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
, 0, &DNSAddr
, UnicastDNSPort
, kScopeNone
, 0, mDNSfalse
, mDNSfalse
, mDNSfalse
, 0, mDNStrue
, mDNStrue
, mDNSfalse
);
507 return (numOfServers
> 0) ? 0 : -1;
510 // Searches the interface list looking for the named interface.
511 // Returns a pointer to if it found, or NULL otherwise.
512 mDNSlocal PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
514 PosixNetworkInterface
*intf
;
517 assert(intfName
!= NULL
);
519 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
520 while ((intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0))
521 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
526 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 index
)
528 PosixNetworkInterface
*intf
;
532 if (index
== kDNSServiceInterfaceIndexLocalOnly
) return(mDNSInterface_LocalOnly
);
533 if (index
== kDNSServiceInterfaceIndexP2P
) return(mDNSInterface_P2P
);
534 if (index
== kDNSServiceInterfaceIndexAny
) return(mDNSInterface_Any
);
536 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
537 while ((intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
538 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
540 return (mDNSInterfaceID
) intf
;
543 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
, mDNSBool suppressNetworkChange
)
545 PosixNetworkInterface
*intf
;
546 (void) suppressNetworkChange
; // Unused
550 if (id
== mDNSInterface_LocalOnly
) return(kDNSServiceInterfaceIndexLocalOnly
);
551 if (id
== mDNSInterface_P2P
) return(kDNSServiceInterfaceIndexP2P
);
552 if (id
== mDNSInterface_Any
) return(kDNSServiceInterfaceIndexAny
);
554 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
555 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
556 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
558 if (intf
) return intf
->index
;
560 // If we didn't find the interface, check the RecentInterfaces list as well
561 intf
= gRecentInterfaces
;
562 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
563 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
565 return intf
? intf
->index
: 0;
568 // Frees the specified PosixNetworkInterface structure. The underlying
569 // interface must have already been deregistered with the mDNS core.
570 mDNSlocal
void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
573 assert(intf
!= NULL
);
574 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
575 if (intf
->multicastSocket4
!= -1)
577 rv
= close(intf
->multicastSocket4
);
581 if (intf
->multicastSocket6
!= -1)
583 rv
= close(intf
->multicastSocket6
);
588 // Move interface to the RecentInterfaces list for a minute
589 intf
->LastSeen
= mDNSPlatformUTC();
590 intf
->coreIntf
.next
= &gRecentInterfaces
->coreIntf
;
591 gRecentInterfaces
= intf
;
594 // Grab the first interface, deregister it, free it, and repeat until done.
595 mDNSlocal
void ClearInterfaceList(mDNS
*const m
)
599 while (m
->HostInterfaces
)
601 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
602 mDNS_DeregisterInterface(m
, &intf
->coreIntf
, NormalActivation
);
603 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
604 FreePosixNetworkInterface(intf
);
606 num_registered_interfaces
= 0;
607 num_pkts_accepted
= 0;
608 num_pkts_rejected
= 0;
611 // Sets up a send/receive socket.
612 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
613 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
614 mDNSlocal
int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
617 static const int kOn
= 1;
618 static const int kIntTwoFiveFive
= 255;
619 static const unsigned char kByteTwoFiveFive
= 255;
620 const mDNSBool JoinMulticastGroup
= (port
.NotAnInteger
!= 0);
622 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
623 assert(intfAddr
!= NULL
);
624 assert(sktPtr
!= NULL
);
625 assert(*sktPtr
== -1);
627 // Open the socket...
628 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
630 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
634 if (*sktPtr
< 0) { err
= errno
; perror((intfAddr
->sa_family
== AF_INET
) ? "socket AF_INET" : "socket AF_INET6"); }
636 // ... with a shared UDP port, if it's for multicast receiving
637 if (err
== 0 && port
.NotAnInteger
)
639 // <rdar://problem/20946253>
640 // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
641 // Linux kernel versions 3.9 introduces support for socket option
642 // SO_REUSEPORT, however this is not implemented the same as on *BSD
643 // systems. Linux version implements a "port hijacking" prevention
644 // mechanism, limiting processes wanting to bind to an already existing
645 // addr:port to have the same effective UID as the first who bound it. What
646 // this meant for us was that the daemon ran as one user and when for
647 // instance mDNSClientPosix was executed by another user, it wasn't allowed
648 // to bind to the socket. Our suggestion was to switch the order in which
649 // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
650 // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
651 #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
652 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
653 #elif defined(SO_REUSEPORT)
654 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
656 #error This platform has no way to avoid address busy errors on multicast.
658 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
660 // Enable inbound packets on IFEF_AWDL interface.
661 // Only done for multicast sockets, since we don't expect unicast socket operations
662 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
663 #ifndef SO_RECV_ANYIF
664 #define SO_RECV_ANYIF 0x1104 /* unrestricted inbound processing */
666 if (setsockopt(*sktPtr
, SOL_SOCKET
, SO_RECV_ANYIF
, &kOn
, sizeof(kOn
)) < 0) perror("setsockopt - SO_RECV_ANYIF");
669 // We want to receive destination addresses and interface identifiers.
670 if (intfAddr
->sa_family
== AF_INET
)
673 struct sockaddr_in bindAddr
;
676 #if defined(IP_PKTINFO) // Linux
677 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
678 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
679 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
680 #if defined(IP_RECVDSTADDR)
681 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
682 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
684 #if defined(IP_RECVIF)
687 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
688 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
692 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
695 #if defined(IP_RECVTTL) // Linux
698 setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
699 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
703 // Add multicast group membership on this interface
704 if (err
== 0 && JoinMulticastGroup
)
706 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
707 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
708 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
709 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
712 // Specify outgoing interface too
713 if (err
== 0 && JoinMulticastGroup
)
715 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
716 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
719 // Per the mDNS spec, send unicast packets with TTL 255
722 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
723 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
726 // and multicast packets with TTL 255 too
727 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
730 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
731 if (err
< 0 && errno
== EINVAL
)
732 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
733 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
736 // And start listening for packets
739 bindAddr
.sin_family
= AF_INET
;
740 bindAddr
.sin_port
= port
.NotAnInteger
;
741 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
742 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
743 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
745 } // endif (intfAddr->sa_family == AF_INET)
748 else if (intfAddr
->sa_family
== AF_INET6
)
750 struct ipv6_mreq imr6
;
751 struct sockaddr_in6 bindAddr6
;
752 #if defined(IPV6_PKTINFO)
755 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_PKTINFO
, &kOn
, sizeof(kOn
));
756 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
759 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
761 #if defined(IPV6_HOPLIMIT)
764 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_2292_HOPLIMIT
, &kOn
, sizeof(kOn
));
765 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
769 // Add multicast group membership on this interface
770 if (err
== 0 && JoinMulticastGroup
)
772 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroup_v6
.ip
.v6
;
773 imr6
.ipv6mr_interface
= interfaceIndex
;
774 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
775 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
779 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
780 perror("setsockopt - IPV6_JOIN_GROUP");
784 // Specify outgoing interface too
785 if (err
== 0 && JoinMulticastGroup
)
787 u_int multicast_if
= interfaceIndex
;
788 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
789 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
792 // We want to receive only IPv6 packets on this socket.
793 // Without this option, we may get IPv4 addresses as mapped addresses.
796 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
797 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
800 // Per the mDNS spec, send unicast packets with TTL 255
803 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
804 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
807 // and multicast packets with TTL 255 too
808 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
811 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
812 if (err
< 0 && errno
== EINVAL
)
813 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
814 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
817 // And start listening for packets
820 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
821 #ifndef NOT_HAVE_SA_LEN
822 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
824 bindAddr6
.sin6_family
= AF_INET6
;
825 bindAddr6
.sin6_port
= port
.NotAnInteger
;
826 bindAddr6
.sin6_flowinfo
= 0;
827 bindAddr6
.sin6_addr
= in6addr_any
; // Want to receive multicasts AND unicasts on this socket
828 bindAddr6
.sin6_scope_id
= 0;
829 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
830 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
832 } // endif (intfAddr->sa_family == AF_INET6)
835 // Set the socket to non-blocking.
838 err
= fcntl(*sktPtr
, F_GETFL
, 0);
839 if (err
< 0) err
= errno
;
842 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
843 if (err
< 0) err
= errno
;
848 if (err
!= 0 && *sktPtr
!= -1)
855 assert((err
== 0) == (*sktPtr
!= -1));
859 // Creates a PosixNetworkInterface for the interface whose IP address is
860 // intfAddr and whose name is intfName and registers it with mDNS core.
861 mDNSlocal
int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, struct sockaddr
*intfMask
, const char *intfName
, int intfIndex
)
864 PosixNetworkInterface
*intf
;
865 PosixNetworkInterface
*alias
= NULL
;
868 assert(intfAddr
!= NULL
);
869 assert(intfName
!= NULL
);
870 assert(intfMask
!= NULL
);
872 // Allocate the interface structure itself.
873 intf
= (PosixNetworkInterface
*)calloc(1, sizeof(*intf
));
874 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
876 // And make a copy of the intfName.
879 intf
->intfName
= strdup(intfName
);
880 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
885 // Set up the fields required by the mDNS core.
886 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
887 SockAddrTomDNSAddr(intfMask
, &intf
->coreIntf
.mask
, NULL
);
889 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
890 strncpy(intf
->coreIntf
.ifname
, intfName
, sizeof(intf
->coreIntf
.ifname
));
891 intf
->coreIntf
.ifname
[sizeof(intf
->coreIntf
.ifname
)-1] = 0;
892 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
893 intf
->coreIntf
.McastTxRx
= mDNStrue
;
895 // Set up the extra fields in PosixNetworkInterface.
896 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
897 intf
->index
= intfIndex
;
898 intf
->multicastSocket4
= -1;
900 intf
->multicastSocket6
= -1;
902 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
903 if (alias
== NULL
) alias
= intf
;
904 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
907 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
910 // Set up the multicast socket
913 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
914 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
916 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
917 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
921 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
922 // and skip the probe phase of the probe/announce packet sequence.
923 intf
->coreIntf
.DirectLink
= mDNSfalse
;
924 #ifdef DIRECTLINK_INTERFACE_NAME
925 if (strcmp(intfName
, STRINGIFY(DIRECTLINK_INTERFACE_NAME
)) == 0)
926 intf
->coreIntf
.DirectLink
= mDNStrue
;
928 intf
->coreIntf
.SupportsUnicastMDNSResponse
= mDNStrue
;
930 // The interface is all ready to go, let's register it with the mDNS core.
932 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
, NormalActivation
);
937 num_registered_interfaces
++;
938 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
939 if (gMDNSPlatformPosixVerboseLevel
> 0)
940 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
944 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
945 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
946 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
949 assert((err
== 0) == (intf
!= NULL
));
954 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
955 mDNSlocal
int SetupInterfaceList(mDNS
*const m
)
957 mDNSBool foundav4
= mDNSfalse
;
959 struct ifi_info
*intfList
= get_ifi_info(AF_INET
, mDNStrue
);
960 struct ifi_info
*firstLoopback
= NULL
;
963 debugf("SetupInterfaceList");
965 if (intfList
== NULL
) err
= ENOENT
;
968 if (err
== 0) /* Link the IPv6 list to the end of the IPv4 list */
970 struct ifi_info
**p
= &intfList
;
971 while (*p
) p
= &(*p
)->ifi_next
;
972 *p
= get_ifi_info(AF_INET6
, mDNStrue
);
978 struct ifi_info
*i
= intfList
;
981 if ( ((i
->ifi_addr
->sa_family
== AF_INET
)
983 || (i
->ifi_addr
->sa_family
== AF_INET6
)
985 ) && (i
->ifi_flags
& IFF_UP
) && !(i
->ifi_flags
& IFF_POINTOPOINT
))
987 if (i
->ifi_flags
& IFF_LOOPBACK
)
989 if (firstLoopback
== NULL
)
994 if (SetupOneInterface(m
, i
->ifi_addr
, i
->ifi_netmask
, i
->ifi_name
, i
->ifi_index
) == 0)
995 if (i
->ifi_addr
->sa_family
== AF_INET
)
1002 // If we found no normal interfaces but we did find a loopback interface, register the
1003 // loopback interface. This allows self-discovery if no interfaces are configured.
1004 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
1005 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
1006 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
1007 if (!foundav4
&& firstLoopback
)
1008 (void) SetupOneInterface(m
, firstLoopback
->ifi_addr
, firstLoopback
->ifi_netmask
, firstLoopback
->ifi_name
, firstLoopback
->ifi_index
);
1012 if (intfList
!= NULL
) free_ifi_info(intfList
);
1014 // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
1015 PosixNetworkInterface
**ri
= &gRecentInterfaces
;
1016 const mDNSs32 utc
= mDNSPlatformUTC();
1019 PosixNetworkInterface
*pi
= *ri
;
1020 if (utc
- pi
->LastSeen
< 60) ri
= (PosixNetworkInterface
**)&pi
->coreIntf
.next
;
1021 else { *ri
= (PosixNetworkInterface
*)pi
->coreIntf
.next
; free(pi
); }
1029 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1031 // Open a socket that will receive interface change notifications
1032 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1034 mStatus err
= mStatus_NoError
;
1035 struct sockaddr_nl snl
;
1039 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
1043 // Configure read to be non-blocking because inbound msg size is not known in advance
1044 (void) fcntl(sock
, F_SETFL
, O_NONBLOCK
);
1046 /* Subscribe the socket to Link & IP addr notifications. */
1047 mDNSPlatformMemZero(&snl
, sizeof snl
);
1048 snl
.nl_family
= AF_NETLINK
;
1049 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
1050 ret
= bind(sock
, (struct sockaddr
*) &snl
, sizeof snl
);
1060 mDNSlocal
void PrintNetLinkMsg(const struct nlmsghdr
*pNLMsg
)
1062 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1063 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1065 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
1066 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[pNLMsg
->nlmsg_type
- RTM_BASE
],
1067 pNLMsg
->nlmsg_flags
);
1069 if (RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
1071 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA(pNLMsg
);
1072 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
1073 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
1076 else if (RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
1078 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
);
1079 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
1080 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1086 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1087 // Read through the messages on sd and if any indicate that any interface records should
1088 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1092 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1095 // The structure here is more complex than it really ought to be because,
1096 // unfortunately, there's no good way to size a buffer in advance large
1097 // enough to hold all pending data and so avoid message fragmentation.
1098 // (Note that FIONREAD is not supported on AF_NETLINK.)
1100 readCount
= read(sd
, buff
, sizeof buff
);
1103 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1104 // If not, discard already-processed messages in buffer and read more data.
1105 if (((char*) &pNLMsg
[1] > (buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1106 ((char*) pNLMsg
+ pNLMsg
->nlmsg_len
> (buff
+ readCount
)))
1108 if (buff
< (char*) pNLMsg
) // we have space to shuffle
1110 // discard processed data
1111 readCount
-= ((char*) pNLMsg
- buff
);
1112 memmove(buff
, pNLMsg
, readCount
);
1113 pNLMsg
= (struct nlmsghdr
*) buff
;
1116 readCount
+= read(sd
, buff
+ readCount
, sizeof buff
- readCount
);
1117 continue; // spin around and revalidate with new readCount
1120 break; // Otherwise message does not fit in buffer
1124 PrintNetLinkMsg(pNLMsg
);
1127 // Process the NetLink message
1128 if (pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1129 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA(pNLMsg
))->ifi_index
;
1130 else if (pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1131 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
))->ifa_index
;
1133 // Advance pNLMsg to the next message in the buffer
1134 if ((pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1136 ssize_t len
= readCount
- ((char*)pNLMsg
- buff
);
1137 pNLMsg
= NLMSG_NEXT(pNLMsg
, len
);
1146 #else // USES_NETLINK
1148 // Open a socket that will receive interface change notifications
1149 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1151 *pFD
= socket(AF_ROUTE
, SOCK_RAW
, 0);
1154 return mStatus_UnknownErr
;
1156 // Configure read to be non-blocking because inbound msg size is not known in advance
1157 (void) fcntl(*pFD
, F_SETFL
, O_NONBLOCK
);
1159 return mStatus_NoError
;
1163 mDNSlocal
void PrintRoutingSocketMsg(const struct ifa_msghdr
*pRSMsg
)
1165 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1166 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1167 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1169 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1171 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[pRSMsg
->ifam_type
], index
);
1175 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1176 // Read through the messages on sd and if any indicate that any interface records should
1177 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1181 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1184 readCount
= read(sd
, buff
, sizeof buff
);
1185 if (readCount
< (ssize_t
) sizeof(struct ifa_msghdr
))
1186 return mStatus_UnsupportedErr
; // cannot decipher message
1189 PrintRoutingSocketMsg(pRSMsg
);
1192 // Process the message
1193 if (pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1194 pRSMsg
->ifam_type
== RTM_IFINFO
)
1196 if (pRSMsg
->ifam_type
== RTM_IFINFO
)
1197 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1199 result
|= 1 << pRSMsg
->ifam_index
;
1205 #endif // USES_NETLINK
1207 // Called when data appears on interface change notification socket
1208 mDNSlocal
void InterfaceChangeCallback(int fd
, short filter
, void *context
)
1210 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1212 mDNSu32 changedInterfaces
= 0;
1213 struct timeval zeroTimeout
= { 0, 0 };
1216 (void)filter
; // Unused
1219 FD_SET(pChgRec
->NotifySD
, &readFDs
);
1223 changedInterfaces
|= ProcessRoutingNotification(pChgRec
->NotifySD
);
1225 while (0 < select(pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1227 // Currently we rebuild the entire interface list whenever any interface change is
1228 // detected. If this ever proves to be a performance issue in a multi-homed
1229 // configuration, more care should be paid to changedInterfaces.
1230 if (changedInterfaces
)
1231 mDNSPlatformPosixRefreshInterfaceList(pChgRec
->mDNS
);
1234 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1235 mDNSlocal mStatus
WatchForInterfaceChange(mDNS
*const m
)
1238 IfChangeRec
*pChgRec
;
1240 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocate(sizeof *pChgRec
);
1241 if (pChgRec
== NULL
)
1242 return mStatus_NoMemoryErr
;
1245 err
= OpenIfNotifySocket(&pChgRec
->NotifySD
);
1247 err
= mDNSPosixAddFDToEventLoop(pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1252 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1253 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1254 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1255 mDNSlocal mDNSBool
mDNSPlatformInit_CanReceiveUnicast(void)
1258 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1259 struct sockaddr_in s5353
;
1260 s5353
.sin_family
= AF_INET
;
1261 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1262 s5353
.sin_addr
.s_addr
= 0;
1263 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1265 if (err
) debugf("No unicast UDP responses");
1266 else debugf("Unicast UDP responses okay");
1270 // mDNS core calls this routine to initialise the platform-specific data.
1271 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1277 if (mDNSPlatformInit_CanReceiveUnicast()) m
->CanReceiveUnicastOn5353
= mDNStrue
;
1279 // Tell mDNS core the names of this machine.
1281 // Set up the nice label
1282 m
->nicelabel
.c
[0] = 0;
1283 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1284 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Computer");
1286 // Set up the RFC 1034-compliant label
1287 m
->hostlabel
.c
[0] = 0;
1288 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1289 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Computer");
1293 sa
.sa_family
= AF_INET
;
1294 m
->p
->unicastSocket4
= -1;
1295 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1297 sa
.sa_family
= AF_INET6
;
1298 m
->p
->unicastSocket6
= -1;
1299 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1302 // Tell mDNS core about the network interfaces on this machine.
1303 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1305 // Tell mDNS core about DNS Servers
1307 if (err
== mStatus_NoError
) ParseDNSServers(m
, uDNS_SERVERS_FILE
);
1310 if (err
== mStatus_NoError
)
1312 err
= WatchForInterfaceChange(m
);
1313 // Failure to observe interface changes is non-fatal.
1314 if (err
!= mStatus_NoError
)
1316 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1317 err
= mStatus_NoError
;
1321 // We don't do asynchronous initialization on the Posix platform, so by the time
1322 // we get here the setup will already have succeeded or failed. If it succeeded,
1323 // we should just call mDNSCoreInitComplete() immediately.
1324 if (err
== mStatus_NoError
)
1325 mDNSCoreInitComplete(m
, mStatus_NoError
);
1327 return PosixErrorToStatus(err
);
1330 // mDNS core calls this routine to clean up the platform-specific data.
1331 // In our case all we need to do is to tear down every network interface.
1332 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1336 ClearInterfaceList(m
);
1337 if (m
->p
->unicastSocket4
!= -1)
1339 rv
= close(m
->p
->unicastSocket4
);
1343 if (m
->p
->unicastSocket6
!= -1)
1345 rv
= close(m
->p
->unicastSocket6
);
1351 // This is used internally by InterfaceChangeCallback.
1352 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1353 // can call it in response to a SIGHUP (mainly for debugging purposes).
1354 mDNSexport mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1357 // This is a pretty heavyweight way to process interface changes --
1358 // destroying the entire interface list and then making fresh one from scratch.
1359 // We should make it like the OS X version, which leaves unchanged interfaces alone.
1360 ClearInterfaceList(m
);
1361 err
= SetupInterfaceList(m
);
1362 return PosixErrorToStatus(err
);
1365 #if COMPILER_LIKES_PRAGMA_MARK
1366 #pragma mark ***** Locking
1369 // On the Posix platform, locking is a no-op because we only ever enter
1370 // mDNS core on the main thread.
1372 // mDNS core calls this routine when it wants to prevent
1373 // the platform from reentering mDNS core code.
1374 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1379 // mDNS core calls this routine when it release the lock taken by
1380 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1381 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1386 #if COMPILER_LIKES_PRAGMA_MARK
1387 #pragma mark ***** Strings
1390 // mDNS core calls this routine to copy C strings.
1391 // On the Posix platform this maps directly to the ANSI C strcpy.
1392 mDNSexport
void mDNSPlatformStrCopy(void *dst
, const void *src
)
1394 strcpy((char *)dst
, (const char *)src
);
1397 mDNSexport mDNSu32
mDNSPlatformStrLCopy(void *dst
, const void *src
, mDNSu32 len
)
1400 return ((mDNSu32
)strlcpy((char *)dst
, (const char *)src
, len
));
1404 srcLen
= strlen((const char *)src
);
1407 memcpy(dst
, src
, srcLen
+ 1);
1411 memcpy(dst
, src
, len
- 1);
1412 ((char *)dst
)[len
- 1] = '\0';
1415 return ((mDNSu32
)srcLen
);
1419 // mDNS core calls this routine to get the length of a C string.
1420 // On the Posix platform this maps directly to the ANSI C strlen.
1421 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1423 return strlen((const char*)src
);
1426 // mDNS core calls this routine to copy memory.
1427 // On the Posix platform this maps directly to the ANSI C memcpy.
1428 mDNSexport
void mDNSPlatformMemCopy(void *dst
, const void *src
, mDNSu32 len
)
1430 memcpy(dst
, src
, len
);
1433 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1434 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1435 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *dst
, const void *src
, mDNSu32 len
)
1437 return memcmp(dst
, src
, len
) == 0;
1440 // If the caller wants to know the exact return of memcmp, then use this instead
1441 // of mDNSPlatformMemSame
1442 mDNSexport
int mDNSPlatformMemCmp(const void *dst
, const void *src
, mDNSu32 len
)
1444 return (memcmp(dst
, src
, len
));
1447 mDNSexport
void mDNSPlatformQsort(void *base
, int nel
, int width
, int (*compar
)(const void *, const void *))
1449 return (qsort(base
, nel
, width
, compar
));
1452 // DNSSEC stub functions
1453 mDNSexport
void VerifySignature(mDNS
*const m
, DNSSECVerifier
*dv
, DNSQuestion
*q
)
1460 mDNSexport mDNSBool
AddNSECSForCacheRecord(mDNS
*const m
, CacheRecord
*crlist
, CacheRecord
*negcr
, mDNSu8 rcode
)
1469 mDNSexport
void BumpDNSSECStats(mDNS
*const m
, DNSSECStatsAction action
, DNSSECStatsType type
, mDNSu32 value
)
1477 // Proxy stub functions
1478 mDNSexport mDNSu8
*DNSProxySetAttributes(DNSQuestion
*q
, DNSMessageHeader
*h
, DNSMessage
*msg
, mDNSu8
*ptr
, mDNSu8
*limit
)
1489 mDNSexport
void DNSProxyInit(mDNSu32 IpIfArr
[], mDNSu32 OpIf
)
1495 mDNSexport
void DNSProxyTerminate(void)
1499 // mDNS core calls this routine to clear blocks of memory.
1500 // On the Posix platform this is a simple wrapper around ANSI C memset.
1501 mDNSexport
void mDNSPlatformMemZero(void *dst
, mDNSu32 len
)
1503 memset(dst
, 0, len
);
1506 mDNSexport
void * mDNSPlatformMemAllocate(mDNSu32 len
) { return(malloc(len
)); }
1507 mDNSexport
void * mDNSPlatformMemAllocateClear(mDNSu32 len
) { return(calloc(1, len
)); }
1508 mDNSexport
void mDNSPlatformMemFree (void *mem
) { free(mem
); }
1510 #if _PLATFORM_HAS_STRONG_PRNG_
1511 mDNSexport mDNSu32
mDNSPlatformRandomNumber(void)
1513 return(arc4random());
1516 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
1519 gettimeofday(&tv
, NULL
);
1524 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1526 mDNSexport mStatus
mDNSPlatformTimeInit(void)
1528 // No special setup is required on Posix -- we just use gettimeofday();
1529 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1530 // We should find a better way to do this
1531 return(mStatus_NoError
);
1534 mDNSexport mDNSs32
mDNSPlatformRawTime()
1537 gettimeofday(&tv
, NULL
);
1538 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1539 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1540 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1541 // 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.
1542 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1543 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1544 return((tv
.tv_sec
<< 10) | (tv
.tv_usec
* 16 / 15625));
1547 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1552 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID
, char *EthAddr
, char *IPAddr
, int iteration
)
1560 mDNSexport mDNSBool
mDNSPlatformValidRecordForInterface(const AuthRecord
*rr
, mDNSInterfaceID InterfaceID
)
1568 mDNSexport mDNSBool
mDNSPlatformValidQuestionForInterface(DNSQuestion
*q
, const NetworkInterfaceInfo
*intf
)
1576 // Used for debugging purposes. For now, just set the buffer to zero
1577 mDNSexport
void mDNSPlatformFormatTime(unsigned long te
, mDNSu8
*buf
, int bufsize
)
1580 if (bufsize
) buf
[0] = 0;
1583 mDNSexport
void mDNSPlatformSendKeepalive(mDNSAddr
*sadd
, mDNSAddr
*dadd
, mDNSIPPort
*lport
, mDNSIPPort
*rport
, mDNSu32 seq
, mDNSu32 ack
, mDNSu16 win
)
1585 (void) sadd
; // Unused
1586 (void) dadd
; // Unused
1587 (void) lport
; // Unused
1588 (void) rport
; // Unused
1589 (void) seq
; // Unused
1590 (void) ack
; // Unused
1591 (void) win
; // Unused
1594 mDNSexport mStatus
mDNSPlatformRetrieveTCPInfo(mDNSAddr
*laddr
, mDNSIPPort
*lport
, mDNSAddr
*raddr
, mDNSIPPort
*rport
, mDNSTCPInfo
*mti
)
1596 (void) laddr
; // Unused
1597 (void) raddr
; // Unused
1598 (void) lport
; // Unused
1599 (void) rport
; // Unused
1600 (void) mti
; // Unused
1602 return mStatus_NoError
;
1605 mDNSexport mStatus
mDNSPlatformGetRemoteMacAddr(mDNSAddr
*raddr
)
1607 (void) raddr
; // Unused
1609 return mStatus_NoError
;
1612 mDNSexport mStatus
mDNSPlatformStoreSPSMACAddr(mDNSAddr
*spsaddr
, char *ifname
)
1614 (void) spsaddr
; // Unused
1615 (void) ifname
; // Unused
1617 return mStatus_NoError
;
1620 mDNSexport mStatus
mDNSPlatformClearSPSData(void)
1622 return mStatus_NoError
;
1625 mDNSexport mStatus
mDNSPlatformStoreOwnerOptRecord(char *ifname
, DNSMessage
*msg
, int length
)
1627 (void) ifname
; // Unused
1628 (void) msg
; // Unused
1629 (void) length
; // Unused
1630 return mStatus_UnsupportedErr
;
1633 mDNSexport mDNSu16
mDNSPlatformGetUDPPort(UDPSocket
*sock
)
1635 (void) sock
; // unused
1640 mDNSexport mDNSBool
mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID
)
1642 (void) InterfaceID
; // unused
1647 mDNSexport
void mDNSPlatformSetSocktOpt(void *sock
, mDNSTransport_Type transType
, mDNSAddr_Type addrType
, const DNSQuestion
*q
)
1655 mDNSexport mDNSs32
mDNSPlatformGetPID()
1660 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
1662 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
1666 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, struct timeval
*timeout
)
1669 struct timeval interval
;
1671 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1672 mDNSs32 nextevent
= mDNS_Execute(m
);
1674 // 2. Build our list of active file descriptors
1675 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1676 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket4
);
1678 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket6
);
1682 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket4
);
1684 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket6
);
1686 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1689 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1690 ticks
= nextevent
- mDNS_TimeNow(m
);
1691 if (ticks
< 1) ticks
= 1;
1692 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
1693 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1695 // 4. If client's proposed timeout is more than what we want, then reduce it
1696 if (timeout
->tv_sec
> interval
.tv_sec
||
1697 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
1698 *timeout
= interval
;
1701 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
)
1703 PosixNetworkInterface
*info
;
1705 assert(readfds
!= NULL
);
1706 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1708 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
1710 FD_CLR(m
->p
->unicastSocket4
, readfds
);
1711 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
1714 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
1716 FD_CLR(m
->p
->unicastSocket6
, readfds
);
1717 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
1723 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
1725 FD_CLR(info
->multicastSocket4
, readfds
);
1726 SocketDataReady(m
, info
, info
->multicastSocket4
);
1729 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
1731 FD_CLR(info
->multicastSocket6
, readfds
);
1732 SocketDataReady(m
, info
, info
->multicastSocket6
);
1735 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1740 mDNSlocal
void DetermineMaxEventFD(void)
1742 PosixEventSource
*iSource
;
1745 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1746 if (gMaxFD
< iSource
->fd
)
1747 gMaxFD
= iSource
->fd
;
1750 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1751 mStatus
mDNSPosixAddFDToEventLoop(int fd
, mDNSPosixEventCallback callback
, void *context
)
1753 PosixEventSource
*newSource
;
1755 if (gEventSources
.LinkOffset
== 0)
1756 InitLinkedList(&gEventSources
, offsetof(PosixEventSource
, Next
));
1758 if (fd
>= (int) FD_SETSIZE
|| fd
< 0)
1759 return mStatus_UnsupportedErr
;
1760 if (callback
== NULL
)
1761 return mStatus_BadParamErr
;
1763 newSource
= (PosixEventSource
*) malloc(sizeof *newSource
);
1764 if (NULL
== newSource
)
1765 return mStatus_NoMemoryErr
;
1767 newSource
->Callback
= callback
;
1768 newSource
->Context
= context
;
1771 AddToTail(&gEventSources
, newSource
);
1772 FD_SET(fd
, &gEventFDs
);
1774 DetermineMaxEventFD();
1776 return mStatus_NoError
;
1779 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1780 mStatus
mDNSPosixRemoveFDFromEventLoop(int fd
)
1782 PosixEventSource
*iSource
;
1784 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1786 if (fd
== iSource
->fd
)
1788 FD_CLR(fd
, &gEventFDs
);
1789 RemoveFromList(&gEventSources
, iSource
);
1791 DetermineMaxEventFD();
1792 return mStatus_NoError
;
1795 return mStatus_NoSuchNameErr
;
1798 // Simply note the received signal in gEventSignals.
1799 mDNSlocal
void NoteSignal(int signum
)
1801 sigaddset(&gEventSignals
, signum
);
1804 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1805 mStatus
mDNSPosixListenForSignalInEventLoop(int signum
)
1807 struct sigaction action
;
1810 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1811 action
.sa_handler
= NoteSignal
;
1812 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1814 sigaddset(&gEventSignalSet
, signum
);
1819 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1820 mStatus
mDNSPosixIgnoreSignalInEventLoop(int signum
)
1822 struct sigaction action
;
1825 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1826 action
.sa_handler
= SIG_DFL
;
1827 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1829 sigdelset(&gEventSignalSet
, signum
);
1834 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1835 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1836 mStatus
mDNSPosixRunEventLoopOnce(mDNS
*m
, const struct timeval
*pTimeout
,
1837 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
1839 fd_set listenFDs
= gEventFDs
;
1840 int fdMax
= 0, numReady
;
1841 struct timeval timeout
= *pTimeout
;
1843 // Include the sockets that are listening to the wire in our select() set
1844 mDNSPosixGetFDSet(m
, &fdMax
, &listenFDs
, &timeout
); // timeout may get modified
1848 numReady
= select(fdMax
+ 1, &listenFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &timeout
);
1850 // If any data appeared, invoke its callback
1853 PosixEventSource
*iSource
;
1855 (void) mDNSPosixProcessFDSet(m
, &listenFDs
); // call this first to process wire data for clients
1857 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1859 if (FD_ISSET(iSource
->fd
, &listenFDs
))
1861 iSource
->Callback(iSource
->fd
, 0, iSource
->Context
);
1862 break; // in case callback removed elements from gEventSources
1865 *pDataDispatched
= mDNStrue
;
1868 *pDataDispatched
= mDNSfalse
;
1870 (void) sigprocmask(SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1871 *pSignalsReceived
= gEventSignals
;
1872 sigemptyset(&gEventSignals
);
1873 (void) sigprocmask(SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1875 return mStatus_NoError
;