1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
19 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
20 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
21 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
22 * therefore common sense dictates that if they are part of a compound statement then they
23 * should be indented to the same level as everything else in that compound statement.
24 * Indenting curly braces at the same level as the "if" implies that curly braces are
25 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
26 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
27 * understand why variable y is not of type "char*" just proves the point that poor code
28 * layout leads people to unfortunate misunderstandings about how the C language really works.)
31 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
32 #include "DNSCommon.h"
33 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
45 #include <sys/types.h>
47 #include <sys/socket.h>
49 #include <sys/select.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 #include <time.h> // platform support for UTC time
55 #include <asm/types.h>
56 #include <linux/netlink.h>
57 #include <linux/rtnetlink.h>
59 #include <net/route.h>
61 #endif // USES_NETLINK
64 #include "GenLinkedList.h"
66 // ***************************************************************************
69 // We keep a list of client-supplied event sources in PosixEventSource records
70 struct PosixEventSource
72 mDNSPosixEventCallback Callback
;
75 struct PosixEventSource
*Next
;
77 typedef struct PosixEventSource PosixEventSource
;
79 // Context record for interface change callback
85 typedef struct IfChangeRec IfChangeRec
;
87 // Note that static data is initialized to zero in (modern) C.
88 static fd_set gEventFDs
;
89 static int gMaxFD
; // largest fd in gEventFDs
90 static GenLinkedList gEventSources
; // linked list of PosixEventSource's
91 static sigset_t gEventSignalSet
; // Signals which event loop listens for
92 static sigset_t gEventSignals
; // Signals which were received while inside loop
94 // ***************************************************************************
95 // Globals (for debugging)
97 static int num_registered_interfaces
= 0;
98 static int num_pkts_accepted
= 0;
99 static int num_pkts_rejected
= 0;
101 // ***************************************************************************
104 int gMDNSPlatformPosixVerboseLevel
= 0;
106 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
108 mDNSlocal
void SockAddrTomDNSAddr(const struct sockaddr
*const sa
, mDNSAddr
*ipAddr
, mDNSIPPort
*ipPort
)
110 switch (sa
->sa_family
)
114 struct sockaddr_in
*sin
= (struct sockaddr_in
*)sa
;
115 ipAddr
->type
= mDNSAddrType_IPv4
;
116 ipAddr
->ip
.v4
.NotAnInteger
= sin
->sin_addr
.s_addr
;
117 if (ipPort
) ipPort
->NotAnInteger
= sin
->sin_port
;
124 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)sa
;
125 #ifndef NOT_HAVE_SA_LEN
126 assert(sin6
->sin6_len
== sizeof(*sin6
));
128 ipAddr
->type
= mDNSAddrType_IPv6
;
129 ipAddr
->ip
.v6
= *(mDNSv6Addr
*)&sin6
->sin6_addr
;
130 if (ipPort
) ipPort
->NotAnInteger
= sin6
->sin6_port
;
136 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa
->sa_family
);
137 ipAddr
->type
= mDNSAddrType_None
;
138 if (ipPort
) ipPort
->NotAnInteger
= 0;
143 #if COMPILER_LIKES_PRAGMA_MARK
144 #pragma mark ***** Send and Receive
147 // mDNS core calls this routine when it needs to send a packet.
148 mDNSexport mStatus
mDNSPlatformSendUDP(const mDNS
*const m
, const void *const msg
, const mDNSu8
*const end
,
149 mDNSInterfaceID InterfaceID
, UDPSocket
*src
, const mDNSAddr
*dst
, mDNSIPPort dstPort
)
152 struct sockaddr_storage to
;
153 PosixNetworkInterface
* thisIntf
= (PosixNetworkInterface
*)(InterfaceID
);
154 int sendingsocket
= -1;
156 (void)src
; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
161 assert((((char *) end
) - ((char *) msg
)) > 0);
162 assert(dstPort
.NotAnInteger
!= 0);
164 if (dst
->type
== mDNSAddrType_IPv4
)
166 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&to
;
167 #ifndef NOT_HAVE_SA_LEN
168 sin
->sin_len
= sizeof(*sin
);
170 sin
->sin_family
= AF_INET
;
171 sin
->sin_port
= dstPort
.NotAnInteger
;
172 sin
->sin_addr
.s_addr
= dst
->ip
.v4
.NotAnInteger
;
173 sendingsocket
= thisIntf
? thisIntf
->multicastSocket4
: m
->p
->unicastSocket4
;
177 else if (dst
->type
== mDNSAddrType_IPv6
)
179 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&to
;
180 mDNSPlatformMemZero(sin6
, sizeof(*sin6
));
181 #ifndef NOT_HAVE_SA_LEN
182 sin6
->sin6_len
= sizeof(*sin6
);
184 sin6
->sin6_family
= AF_INET6
;
185 sin6
->sin6_port
= dstPort
.NotAnInteger
;
186 sin6
->sin6_addr
= *(struct in6_addr
*)&dst
->ip
.v6
;
187 sendingsocket
= thisIntf
? thisIntf
->multicastSocket6
: m
->p
->unicastSocket6
;
191 if (sendingsocket
>= 0)
192 err
= sendto(sendingsocket
, msg
, (char*)end
- (char*)msg
, 0, (struct sockaddr
*)&to
, GET_SA_LEN(to
));
194 if (err
> 0) err
= 0;
197 static int MessageCount
= 0;
198 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
199 if (!mDNSAddressIsAllDNSLinkGroup(dst
))
200 if (errno
== EHOSTDOWN
|| errno
== ENETDOWN
|| errno
== EHOSTUNREACH
|| errno
== ENETUNREACH
) return(mStatus_TransientErr
);
202 if (MessageCount
< 1000)
206 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
207 errno
, strerror(errno
), dst
, &thisIntf
->coreIntf
.ip
, thisIntf
->intfName
, thisIntf
->index
);
209 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno
, strerror(errno
), dst
);
213 return PosixErrorToStatus(err
);
216 // This routine is called when the main loop detects that data is available on a socket.
217 mDNSlocal
void SocketDataReady(mDNS
*const m
, PosixNetworkInterface
*intf
, int skt
)
219 mDNSAddr senderAddr
, destAddr
;
220 mDNSIPPort senderPort
;
223 struct my_in_pktinfo packetInfo
;
224 struct sockaddr_storage from
;
229 const mDNSInterfaceID InterfaceID
= intf
? intf
->coreIntf
.InterfaceID
: NULL
;
234 fromLen
= sizeof(from
);
236 packetLen
= recvfrom_flags(skt
, &packet
, sizeof(packet
), &flags
, (struct sockaddr
*) &from
, &fromLen
, &packetInfo
, &ttl
);
240 SockAddrTomDNSAddr((struct sockaddr
*)&from
, &senderAddr
, &senderPort
);
241 SockAddrTomDNSAddr((struct sockaddr
*)&packetInfo
.ipi_addr
, &destAddr
, NULL
);
243 // If we have broken IP_RECVDSTADDR functionality (so far
244 // I've only seen this on OpenBSD) then apply a hack to
245 // convince mDNS Core that this isn't a spoof packet.
246 // Basically what we do is check to see whether the
247 // packet arrived as a multicast and, if so, set its
248 // destAddr to the mDNS address.
250 // I must admit that I could just be doing something
251 // wrong on OpenBSD and hence triggering this problem
252 // but I'm at a loss as to how.
254 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
255 // no way to tell the destination address or interface this packet arrived on,
256 // so all we can do is just assume it's a multicast
258 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
259 if ((destAddr
.NotAnInteger
== 0) && (flags
& MSG_MCAST
))
261 destAddr
.type
= senderAddr
.type
;
262 if (senderAddr
.type
== mDNSAddrType_IPv4
) destAddr
.ip
.v4
= AllDNSLinkGroup_v4
.ip
.v4
;
263 else if (senderAddr
.type
== mDNSAddrType_IPv6
) destAddr
.ip
.v6
= AllDNSLinkGroup_v6
.ip
.v6
;
267 // We only accept the packet if the interface on which it came
268 // in matches the interface associated with this socket.
269 // We do this match by name or by index, depending on which
270 // information is available. recvfrom_flags sets the name
271 // to "" if the name isn't available, or the index to -1
272 // if the index is available. This accomodates the various
273 // different capabilities of our target platforms.
278 // Ignore multicasts accidentally delivered to our unicast receiving socket
279 if (mDNSAddrIsDNSMulticast(&destAddr
)) packetLen
= -1;
283 if (packetInfo
.ipi_ifname
[0] != 0) reject
= (strcmp(packetInfo
.ipi_ifname
, intf
->intfName
) != 0);
284 else if (packetInfo
.ipi_ifindex
!= -1) reject
= (packetInfo
.ipi_ifindex
!= intf
->index
);
288 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
289 &senderAddr
, &destAddr
, packetInfo
.ipi_ifname
, packetInfo
.ipi_ifindex
,
290 &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
293 if (num_pkts_rejected
> (num_pkts_accepted
+ 1) * (num_registered_interfaces
+ 1) * 2)
296 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
297 num_pkts_accepted
+ num_pkts_rejected
, num_pkts_accepted
, num_pkts_rejected
);
298 num_pkts_accepted
= 0;
299 num_pkts_rejected
= 0;
304 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
305 &senderAddr
, &destAddr
, &intf
->coreIntf
.ip
, intf
->intfName
, intf
->index
, skt
);
312 mDNSCoreReceive(m
, &packet
, (mDNSu8
*)&packet
+ packetLen
,
313 &senderAddr
, senderPort
, &destAddr
, MulticastDNSPort
, InterfaceID
);
316 mDNSexport TCPSocket
*mDNSPlatformTCPSocket(mDNS
* const m
, TCPSocketFlags flags
, mDNSIPPort
* port
)
319 (void)flags
; // Unused
320 (void)port
; // Unused
324 mDNSexport TCPSocket
*mDNSPlatformTCPAccept(TCPSocketFlags flags
, int sd
)
326 (void)flags
; // Unused
331 mDNSexport
int mDNSPlatformTCPGetFD(TCPSocket
*sock
)
333 (void)sock
; // Unused
337 mDNSexport mStatus
mDNSPlatformTCPConnect(TCPSocket
*sock
, const mDNSAddr
*dst
, mDNSOpaque16 dstport
, domainname
*hostname
, mDNSInterfaceID InterfaceID
,
338 TCPConnectionCallback callback
, void *context
)
340 (void)sock
; // Unused
342 (void)dstport
; // Unused
343 (void)hostname
; // Unused
344 (void)InterfaceID
; // Unused
345 (void)callback
; // Unused
346 (void)context
; // Unused
347 return(mStatus_UnsupportedErr
);
350 mDNSexport
void mDNSPlatformTCPCloseConnection(TCPSocket
*sock
)
352 (void)sock
; // Unused
355 mDNSexport
long mDNSPlatformReadTCP(TCPSocket
*sock
, void *buf
, unsigned long buflen
, mDNSBool
* closed
)
357 (void)sock
; // Unused
359 (void)buflen
; // Unused
360 (void)closed
; // Unused
364 mDNSexport
long mDNSPlatformWriteTCP(TCPSocket
*sock
, const char *msg
, unsigned long len
)
366 (void)sock
; // Unused
372 mDNSexport UDPSocket
*mDNSPlatformUDPSocket(mDNS
* const m
, mDNSIPPort port
)
375 (void)port
; // Unused
379 mDNSexport
void mDNSPlatformUDPClose(UDPSocket
*sock
)
381 (void)sock
; // Unused
384 mDNSexport
void mDNSPlatformUpdateProxyList(mDNS
*const m
, const mDNSInterfaceID InterfaceID
)
387 (void)InterfaceID
; // Unused
390 mDNSexport
void mDNSPlatformSendRawPacket(const void *const msg
, const mDNSu8
*const end
, mDNSInterfaceID InterfaceID
)
394 (void)InterfaceID
; // Unused
397 mDNSexport
void mDNSPlatformSetLocalAddressCacheEntry(mDNS
*const m
, const mDNSAddr
*const tpa
, const mDNSEthAddr
*const tha
, mDNSInterfaceID InterfaceID
)
402 (void)InterfaceID
; // Unused
405 mDNSexport mStatus
mDNSPlatformTLSSetupCerts(void)
407 return(mStatus_UnsupportedErr
);
410 mDNSexport
void mDNSPlatformTLSTearDownCerts(void)
414 mDNSexport
void mDNSPlatformSetAllowSleep(mDNS
*const m
, mDNSBool allowSleep
, const char *reason
)
421 #if COMPILER_LIKES_PRAGMA_MARK
423 #pragma mark - /etc/hosts support
426 mDNSexport
void FreeEtcHosts(mDNS
*const m
, AuthRecord
*const rr
, mStatus result
)
434 #if COMPILER_LIKES_PRAGMA_MARK
435 #pragma mark ***** DDNS Config Platform Functions
438 mDNSexport
void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**BrowseDomains
)
445 (void) BrowseDomains
;
448 mDNSexport mStatus
mDNSPlatformGetPrimaryInterface(mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
455 return mStatus_UnsupportedErr
;
458 mDNSexport
void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
)
464 #if COMPILER_LIKES_PRAGMA_MARK
465 #pragma mark ***** Init and Term
468 // This gets the current hostname, truncating it at the first dot if necessary
469 mDNSlocal
void GetUserSpecifiedRFC1034ComputerName(domainlabel
*const namelabel
)
472 gethostname((char *)(&namelabel
->c
[1]), MAX_DOMAIN_LABEL
);
473 while (len
< MAX_DOMAIN_LABEL
&& namelabel
->c
[len
+1] && namelabel
->c
[len
+1] != '.') len
++;
474 namelabel
->c
[0] = len
;
477 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
478 // Other platforms can either get the information from the appropriate place,
479 // or they can alternatively just require all registering services to provide an explicit name
480 mDNSlocal
void GetUserSpecifiedFriendlyComputerName(domainlabel
*const namelabel
)
482 // On Unix we have no better name than the host name, so we just use that.
483 GetUserSpecifiedRFC1034ComputerName(namelabel
);
486 mDNSexport
int ParseDNSServers(mDNS
*m
, const char *filePath
)
491 int numOfServers
= 0;
492 FILE *fp
= fopen(filePath
, "r");
493 if (fp
== NULL
) return -1;
494 while (fgets(line
,sizeof(line
),fp
))
497 line
[255]='\0'; // just to be safe
498 if (sscanf(line
,"%10s %15s", keyword
, nameserver
) != 2) continue; // it will skip whitespaces
499 if (strncasecmp(keyword
,"nameserver",10)) continue;
500 if (inet_aton(nameserver
, (struct in_addr
*)&ina
) != 0)
503 DNSAddr
.type
= mDNSAddrType_IPv4
;
504 DNSAddr
.ip
.v4
.NotAnInteger
= ina
.s_addr
;
505 mDNS_AddDNSServer(m
, NULL
, mDNSInterface_Any
, &DNSAddr
, UnicastDNSPort
, mDNSfalse
, 0);
509 return (numOfServers
> 0) ? 0 : -1;
512 // Searches the interface list looking for the named interface.
513 // Returns a pointer to if it found, or NULL otherwise.
514 mDNSlocal PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
516 PosixNetworkInterface
*intf
;
519 assert(intfName
!= NULL
);
521 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
522 while ((intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0))
523 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
528 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 index
)
530 PosixNetworkInterface
*intf
;
534 if (index
== kDNSServiceInterfaceIndexLocalOnly
) return(mDNSInterface_LocalOnly
);
535 if (index
== kDNSServiceInterfaceIndexP2P
) return(mDNSInterface_P2P
);
536 if (index
== kDNSServiceInterfaceIndexAny
) return(mDNSInterface_Any
);
538 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
539 while ((intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
540 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
542 return (mDNSInterfaceID
) intf
;
545 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
, mDNSBool suppressNetworkChange
)
547 PosixNetworkInterface
*intf
;
548 (void) suppressNetworkChange
; // Unused
552 if (id
== mDNSInterface_LocalOnly
) return(kDNSServiceInterfaceIndexLocalOnly
);
553 if (id
== mDNSInterface_P2P
) return(kDNSServiceInterfaceIndexP2P
);
554 if (id
== mDNSInterface_Any
) return(kDNSServiceInterfaceIndexAny
);
556 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
557 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
558 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
560 return intf
? intf
->index
: 0;
563 // Frees the specified PosixNetworkInterface structure. The underlying
564 // interface must have already been deregistered with the mDNS core.
565 mDNSlocal
void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
567 assert(intf
!= NULL
);
568 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
569 if (intf
->multicastSocket4
!= -1) assert(close(intf
->multicastSocket4
) == 0);
571 if (intf
->multicastSocket6
!= -1) assert(close(intf
->multicastSocket6
) == 0);
576 // Grab the first interface, deregister it, free it, and repeat until done.
577 mDNSlocal
void ClearInterfaceList(mDNS
*const m
)
581 while (m
->HostInterfaces
)
583 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
584 mDNS_DeregisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
585 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
586 FreePosixNetworkInterface(intf
);
588 num_registered_interfaces
= 0;
589 num_pkts_accepted
= 0;
590 num_pkts_rejected
= 0;
593 // Sets up a send/receive socket.
594 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
595 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
596 mDNSlocal
int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
599 static const int kOn
= 1;
600 static const int kIntTwoFiveFive
= 255;
601 static const unsigned char kByteTwoFiveFive
= 255;
602 const mDNSBool JoinMulticastGroup
= (port
.NotAnInteger
!= 0);
604 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
605 assert(intfAddr
!= NULL
);
606 assert(sktPtr
!= NULL
);
607 assert(*sktPtr
== -1);
609 // Open the socket...
610 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
612 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
616 if (*sktPtr
< 0) { err
= errno
; perror((intfAddr
->sa_family
== AF_INET
) ? "socket AF_INET" : "socket AF_INET6"); }
618 // ... with a shared UDP port, if it's for multicast receiving
619 if (err
== 0 && port
.NotAnInteger
)
621 #if defined(SO_REUSEPORT)
622 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
623 #elif defined(SO_REUSEADDR)
624 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
626 #error This platform has no way to avoid address busy errors on multicast.
628 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
631 // We want to receive destination addresses and interface identifiers.
632 if (intfAddr
->sa_family
== AF_INET
)
635 struct sockaddr_in bindAddr
;
638 #if defined(IP_PKTINFO) // Linux
639 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
640 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
641 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
642 #if defined(IP_RECVDSTADDR)
643 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
644 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
646 #if defined(IP_RECVIF)
649 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
650 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
654 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
657 #if defined(IP_RECVTTL) // Linux
660 setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
661 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
665 // Add multicast group membership on this interface
666 if (err
== 0 && JoinMulticastGroup
)
668 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
669 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
670 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
671 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
674 // Specify outgoing interface too
675 if (err
== 0 && JoinMulticastGroup
)
677 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
678 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
681 // Per the mDNS spec, send unicast packets with TTL 255
684 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
685 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
688 // and multicast packets with TTL 255 too
689 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
692 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
693 if (err
< 0 && errno
== EINVAL
)
694 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
695 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
698 // And start listening for packets
701 bindAddr
.sin_family
= AF_INET
;
702 bindAddr
.sin_port
= port
.NotAnInteger
;
703 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
704 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
705 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
707 } // endif (intfAddr->sa_family == AF_INET)
710 else if (intfAddr
->sa_family
== AF_INET6
)
712 struct ipv6_mreq imr6
;
713 struct sockaddr_in6 bindAddr6
;
714 #if defined(IPV6_PKTINFO)
717 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_PKTINFO
, &kOn
, sizeof(kOn
));
718 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
721 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
723 #if defined(IPV6_HOPLIMIT)
726 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_HOPLIMIT
, &kOn
, sizeof(kOn
));
727 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
731 // Add multicast group membership on this interface
732 if (err
== 0 && JoinMulticastGroup
)
734 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroup_v6
.ip
.v6
;
735 imr6
.ipv6mr_interface
= interfaceIndex
;
736 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
737 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
741 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
742 perror("setsockopt - IPV6_JOIN_GROUP");
746 // Specify outgoing interface too
747 if (err
== 0 && JoinMulticastGroup
)
749 u_int multicast_if
= interfaceIndex
;
750 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
751 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
754 // We want to receive only IPv6 packets on this socket.
755 // Without this option, we may get IPv4 addresses as mapped addresses.
758 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
759 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
762 // Per the mDNS spec, send unicast packets with TTL 255
765 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
766 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
769 // and multicast packets with TTL 255 too
770 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
773 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
774 if (err
< 0 && errno
== EINVAL
)
775 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
776 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
779 // And start listening for packets
782 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
783 #ifndef NOT_HAVE_SA_LEN
784 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
786 bindAddr6
.sin6_family
= AF_INET6
;
787 bindAddr6
.sin6_port
= port
.NotAnInteger
;
788 bindAddr6
.sin6_flowinfo
= 0;
789 bindAddr6
.sin6_addr
= in6addr_any
; // Want to receive multicasts AND unicasts on this socket
790 bindAddr6
.sin6_scope_id
= 0;
791 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
792 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
794 } // endif (intfAddr->sa_family == AF_INET6)
797 // Set the socket to non-blocking.
800 err
= fcntl(*sktPtr
, F_GETFL
, 0);
801 if (err
< 0) err
= errno
;
804 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
805 if (err
< 0) err
= errno
;
810 if (err
!= 0 && *sktPtr
!= -1) { assert(close(*sktPtr
) == 0); *sktPtr
= -1; }
811 assert((err
== 0) == (*sktPtr
!= -1));
815 // Creates a PosixNetworkInterface for the interface whose IP address is
816 // intfAddr and whose name is intfName and registers it with mDNS core.
817 mDNSlocal
int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, struct sockaddr
*intfMask
, const char *intfName
, int intfIndex
)
820 PosixNetworkInterface
*intf
;
821 PosixNetworkInterface
*alias
= NULL
;
824 assert(intfAddr
!= NULL
);
825 assert(intfName
!= NULL
);
826 assert(intfMask
!= NULL
);
828 // Allocate the interface structure itself.
829 intf
= (PosixNetworkInterface
*)malloc(sizeof(*intf
));
830 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
832 // And make a copy of the intfName.
835 intf
->intfName
= strdup(intfName
);
836 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
841 // Set up the fields required by the mDNS core.
842 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
843 SockAddrTomDNSAddr(intfMask
, &intf
->coreIntf
.mask
, NULL
);
844 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
845 strncpy(intf
->coreIntf
.ifname
, intfName
, sizeof(intf
->coreIntf
.ifname
));
846 intf
->coreIntf
.ifname
[sizeof(intf
->coreIntf
.ifname
)-1] = 0;
847 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
848 intf
->coreIntf
.McastTxRx
= mDNStrue
;
850 // Set up the extra fields in PosixNetworkInterface.
851 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
852 intf
->index
= intfIndex
;
853 intf
->multicastSocket4
= -1;
855 intf
->multicastSocket6
= -1;
857 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
858 if (alias
== NULL
) alias
= intf
;
859 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
862 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
865 // Set up the multicast socket
868 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
869 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
871 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
872 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
876 // The interface is all ready to go, let's register it with the mDNS core.
878 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
883 num_registered_interfaces
++;
884 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
885 if (gMDNSPlatformPosixVerboseLevel
> 0)
886 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
890 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
891 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
892 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
895 assert((err
== 0) == (intf
!= NULL
));
900 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
901 mDNSlocal
int SetupInterfaceList(mDNS
*const m
)
903 mDNSBool foundav4
= mDNSfalse
;
905 struct ifi_info
*intfList
= get_ifi_info(AF_INET
, mDNStrue
);
906 struct ifi_info
*firstLoopback
= NULL
;
909 debugf("SetupInterfaceList");
911 if (intfList
== NULL
) err
= ENOENT
;
914 if (err
== 0) /* Link the IPv6 list to the end of the IPv4 list */
916 struct ifi_info
**p
= &intfList
;
917 while (*p
) p
= &(*p
)->ifi_next
;
918 *p
= get_ifi_info(AF_INET6
, mDNStrue
);
924 struct ifi_info
*i
= intfList
;
927 if ( ((i
->ifi_addr
->sa_family
== AF_INET
)
929 || (i
->ifi_addr
->sa_family
== AF_INET6
)
931 ) && (i
->ifi_flags
& IFF_UP
) && !(i
->ifi_flags
& IFF_POINTOPOINT
))
933 if (i
->ifi_flags
& IFF_LOOPBACK
)
935 if (firstLoopback
== NULL
)
940 if (SetupOneInterface(m
, i
->ifi_addr
, i
->ifi_netmask
, i
->ifi_name
, i
->ifi_index
) == 0)
941 if (i
->ifi_addr
->sa_family
== AF_INET
)
948 // If we found no normal interfaces but we did find a loopback interface, register the
949 // loopback interface. This allows self-discovery if no interfaces are configured.
950 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
951 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
952 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
953 if (!foundav4
&& firstLoopback
)
954 (void) SetupOneInterface(m
, firstLoopback
->ifi_addr
, firstLoopback
->ifi_netmask
, firstLoopback
->ifi_name
, firstLoopback
->ifi_index
);
958 if (intfList
!= NULL
) free_ifi_info(intfList
);
964 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
966 // Open a socket that will receive interface change notifications
967 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
969 mStatus err
= mStatus_NoError
;
970 struct sockaddr_nl snl
;
974 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
978 // Configure read to be non-blocking because inbound msg size is not known in advance
979 (void) fcntl(sock
, F_SETFL
, O_NONBLOCK
);
981 /* Subscribe the socket to Link & IP addr notifications. */
982 mDNSPlatformMemZero(&snl
, sizeof snl
);
983 snl
.nl_family
= AF_NETLINK
;
984 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
985 ret
= bind(sock
, (struct sockaddr
*) &snl
, sizeof snl
);
995 mDNSlocal
void PrintNetLinkMsg(const struct nlmsghdr
*pNLMsg
)
997 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
998 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1000 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
1001 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[pNLMsg
->nlmsg_type
- RTM_BASE
],
1002 pNLMsg
->nlmsg_flags
);
1004 if (RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
1006 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA(pNLMsg
);
1007 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
1008 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
1011 else if (RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
1013 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
);
1014 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
1015 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1021 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1022 // Read through the messages on sd and if any indicate that any interface records should
1023 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1027 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1030 // The structure here is more complex than it really ought to be because,
1031 // unfortunately, there's no good way to size a buffer in advance large
1032 // enough to hold all pending data and so avoid message fragmentation.
1033 // (Note that FIONREAD is not supported on AF_NETLINK.)
1035 readCount
= read(sd
, buff
, sizeof buff
);
1038 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1039 // If not, discard already-processed messages in buffer and read more data.
1040 if (((char*) &pNLMsg
[1] > (buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1041 ((char*) pNLMsg
+ pNLMsg
->nlmsg_len
> (buff
+ readCount
)))
1043 if (buff
< (char*) pNLMsg
) // we have space to shuffle
1045 // discard processed data
1046 readCount
-= ((char*) pNLMsg
- buff
);
1047 memmove(buff
, pNLMsg
, readCount
);
1048 pNLMsg
= (struct nlmsghdr
*) buff
;
1051 readCount
+= read(sd
, buff
+ readCount
, sizeof buff
- readCount
);
1052 continue; // spin around and revalidate with new readCount
1055 break; // Otherwise message does not fit in buffer
1059 PrintNetLinkMsg(pNLMsg
);
1062 // Process the NetLink message
1063 if (pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1064 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA(pNLMsg
))->ifi_index
;
1065 else if (pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1066 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
))->ifa_index
;
1068 // Advance pNLMsg to the next message in the buffer
1069 if ((pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1071 ssize_t len
= readCount
- ((char*)pNLMsg
- buff
);
1072 pNLMsg
= NLMSG_NEXT(pNLMsg
, len
);
1081 #else // USES_NETLINK
1083 // Open a socket that will receive interface change notifications
1084 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1086 *pFD
= socket(AF_ROUTE
, SOCK_RAW
, 0);
1089 return mStatus_UnknownErr
;
1091 // Configure read to be non-blocking because inbound msg size is not known in advance
1092 (void) fcntl(*pFD
, F_SETFL
, O_NONBLOCK
);
1094 return mStatus_NoError
;
1098 mDNSlocal
void PrintRoutingSocketMsg(const struct ifa_msghdr
*pRSMsg
)
1100 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1101 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1102 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1104 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1106 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[pRSMsg
->ifam_type
], index
);
1110 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1111 // Read through the messages on sd and if any indicate that any interface records should
1112 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1116 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1119 readCount
= read(sd
, buff
, sizeof buff
);
1120 if (readCount
< (ssize_t
) sizeof(struct ifa_msghdr
))
1121 return mStatus_UnsupportedErr
; // cannot decipher message
1124 PrintRoutingSocketMsg(pRSMsg
);
1127 // Process the message
1128 if (pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1129 pRSMsg
->ifam_type
== RTM_IFINFO
)
1131 if (pRSMsg
->ifam_type
== RTM_IFINFO
)
1132 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1134 result
|= 1 << pRSMsg
->ifam_index
;
1140 #endif // USES_NETLINK
1142 // Called when data appears on interface change notification socket
1143 mDNSlocal
void InterfaceChangeCallback(int fd
, short filter
, void *context
)
1145 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1147 mDNSu32 changedInterfaces
= 0;
1148 struct timeval zeroTimeout
= { 0, 0 };
1151 (void)filter
; // Unused
1154 FD_SET(pChgRec
->NotifySD
, &readFDs
);
1158 changedInterfaces
|= ProcessRoutingNotification(pChgRec
->NotifySD
);
1160 while (0 < select(pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1162 // Currently we rebuild the entire interface list whenever any interface change is
1163 // detected. If this ever proves to be a performance issue in a multi-homed
1164 // configuration, more care should be paid to changedInterfaces.
1165 if (changedInterfaces
)
1166 mDNSPlatformPosixRefreshInterfaceList(pChgRec
->mDNS
);
1169 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1170 mDNSlocal mStatus
WatchForInterfaceChange(mDNS
*const m
)
1173 IfChangeRec
*pChgRec
;
1175 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocate(sizeof *pChgRec
);
1176 if (pChgRec
== NULL
)
1177 return mStatus_NoMemoryErr
;
1180 err
= OpenIfNotifySocket(&pChgRec
->NotifySD
);
1182 err
= mDNSPosixAddFDToEventLoop(pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1187 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1188 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1189 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1190 mDNSlocal mDNSBool
mDNSPlatformInit_CanReceiveUnicast(void)
1193 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1194 struct sockaddr_in s5353
;
1195 s5353
.sin_family
= AF_INET
;
1196 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1197 s5353
.sin_addr
.s_addr
= 0;
1198 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1200 if (err
) debugf("No unicast UDP responses");
1201 else debugf("Unicast UDP responses okay");
1205 // mDNS core calls this routine to initialise the platform-specific data.
1206 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1212 if (mDNSPlatformInit_CanReceiveUnicast()) m
->CanReceiveUnicastOn5353
= mDNStrue
;
1214 // Tell mDNS core the names of this machine.
1216 // Set up the nice label
1217 m
->nicelabel
.c
[0] = 0;
1218 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1219 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Computer");
1221 // Set up the RFC 1034-compliant label
1222 m
->hostlabel
.c
[0] = 0;
1223 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1224 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Computer");
1228 sa
.sa_family
= AF_INET
;
1229 m
->p
->unicastSocket4
= -1;
1230 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1232 sa
.sa_family
= AF_INET6
;
1233 m
->p
->unicastSocket6
= -1;
1234 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1237 // Tell mDNS core about the network interfaces on this machine.
1238 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1240 // Tell mDNS core about DNS Servers
1242 if (err
== mStatus_NoError
) ParseDNSServers(m
, uDNS_SERVERS_FILE
);
1245 if (err
== mStatus_NoError
)
1247 err
= WatchForInterfaceChange(m
);
1248 // Failure to observe interface changes is non-fatal.
1249 if (err
!= mStatus_NoError
)
1251 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1252 err
= mStatus_NoError
;
1256 // We don't do asynchronous initialization on the Posix platform, so by the time
1257 // we get here the setup will already have succeeded or failed. If it succeeded,
1258 // we should just call mDNSCoreInitComplete() immediately.
1259 if (err
== mStatus_NoError
)
1260 mDNSCoreInitComplete(m
, mStatus_NoError
);
1262 return PosixErrorToStatus(err
);
1265 // mDNS core calls this routine to clean up the platform-specific data.
1266 // In our case all we need to do is to tear down every network interface.
1267 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1270 ClearInterfaceList(m
);
1271 if (m
->p
->unicastSocket4
!= -1) assert(close(m
->p
->unicastSocket4
) == 0);
1273 if (m
->p
->unicastSocket6
!= -1) assert(close(m
->p
->unicastSocket6
) == 0);
1277 mDNSexport mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1280 ClearInterfaceList(m
);
1281 err
= SetupInterfaceList(m
);
1282 return PosixErrorToStatus(err
);
1285 #if COMPILER_LIKES_PRAGMA_MARK
1286 #pragma mark ***** Locking
1289 // On the Posix platform, locking is a no-op because we only ever enter
1290 // mDNS core on the main thread.
1292 // mDNS core calls this routine when it wants to prevent
1293 // the platform from reentering mDNS core code.
1294 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1299 // mDNS core calls this routine when it release the lock taken by
1300 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1301 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1306 #if COMPILER_LIKES_PRAGMA_MARK
1307 #pragma mark ***** Strings
1310 // mDNS core calls this routine to copy C strings.
1311 // On the Posix platform this maps directly to the ANSI C strcpy.
1312 mDNSexport
void mDNSPlatformStrCopy(void *dst
, const void *src
)
1314 strcpy((char *)dst
, (char *)src
);
1317 // mDNS core calls this routine to get the length of a C string.
1318 // On the Posix platform this maps directly to the ANSI C strlen.
1319 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1321 return strlen((char*)src
);
1324 // mDNS core calls this routine to copy memory.
1325 // On the Posix platform this maps directly to the ANSI C memcpy.
1326 mDNSexport
void mDNSPlatformMemCopy(void *dst
, const void *src
, mDNSu32 len
)
1328 memcpy(dst
, src
, len
);
1331 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1332 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1333 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *dst
, const void *src
, mDNSu32 len
)
1335 return memcmp(dst
, src
, len
) == 0;
1338 // mDNS core calls this routine to clear blocks of memory.
1339 // On the Posix platform this is a simple wrapper around ANSI C memset.
1340 mDNSexport
void mDNSPlatformMemZero(void *dst
, mDNSu32 len
)
1342 memset(dst
, 0, len
);
1345 mDNSexport
void * mDNSPlatformMemAllocate(mDNSu32 len
) { return(malloc(len
)); }
1346 mDNSexport
void mDNSPlatformMemFree (void *mem
) { free(mem
); }
1348 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
1351 gettimeofday(&tv
, NULL
);
1355 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1357 mDNSexport mStatus
mDNSPlatformTimeInit(void)
1359 // No special setup is required on Posix -- we just use gettimeofday();
1360 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1361 // We should find a better way to do this
1362 return(mStatus_NoError
);
1365 mDNSexport mDNSs32
mDNSPlatformRawTime()
1368 gettimeofday(&tv
, NULL
);
1369 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1370 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1371 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1372 // 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.
1373 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1374 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1375 return((tv
.tv_sec
<< 10) | (tv
.tv_usec
* 16 / 15625));
1378 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1383 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNS
*const m
, mDNSInterfaceID InterfaceID
, char *EthAddr
, char *IPAddr
, int iteration
)
1392 mDNSexport mDNSBool
mDNSPlatformValidRecordForInterface(AuthRecord
*rr
, const NetworkInterfaceInfo
*intf
)
1400 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
1402 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
1406 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, struct timeval
*timeout
)
1409 struct timeval interval
;
1411 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1412 mDNSs32 nextevent
= mDNS_Execute(m
);
1414 // 2. Build our list of active file descriptors
1415 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1416 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket4
);
1418 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket6
);
1422 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket4
);
1424 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket6
);
1426 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1429 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1430 ticks
= nextevent
- mDNS_TimeNow(m
);
1431 if (ticks
< 1) ticks
= 1;
1432 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
1433 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1435 // 4. If client's proposed timeout is more than what we want, then reduce it
1436 if (timeout
->tv_sec
> interval
.tv_sec
||
1437 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
1438 *timeout
= interval
;
1441 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
)
1443 PosixNetworkInterface
*info
;
1445 assert(readfds
!= NULL
);
1446 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1448 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
1450 FD_CLR(m
->p
->unicastSocket4
, readfds
);
1451 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
1454 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
1456 FD_CLR(m
->p
->unicastSocket6
, readfds
);
1457 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
1463 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
1465 FD_CLR(info
->multicastSocket4
, readfds
);
1466 SocketDataReady(m
, info
, info
->multicastSocket4
);
1469 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
1471 FD_CLR(info
->multicastSocket6
, readfds
);
1472 SocketDataReady(m
, info
, info
->multicastSocket6
);
1475 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1480 mDNSlocal
void DetermineMaxEventFD(void)
1482 PosixEventSource
*iSource
;
1485 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1486 if (gMaxFD
< iSource
->fd
)
1487 gMaxFD
= iSource
->fd
;
1490 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1491 mStatus
mDNSPosixAddFDToEventLoop(int fd
, mDNSPosixEventCallback callback
, void *context
)
1493 PosixEventSource
*newSource
;
1495 if (gEventSources
.LinkOffset
== 0)
1496 InitLinkedList(&gEventSources
, offsetof(PosixEventSource
, Next
));
1498 if (fd
>= (int) FD_SETSIZE
|| fd
< 0)
1499 return mStatus_UnsupportedErr
;
1500 if (callback
== NULL
)
1501 return mStatus_BadParamErr
;
1503 newSource
= (PosixEventSource
*) malloc(sizeof *newSource
);
1504 if (NULL
== newSource
)
1505 return mStatus_NoMemoryErr
;
1507 newSource
->Callback
= callback
;
1508 newSource
->Context
= context
;
1511 AddToTail(&gEventSources
, newSource
);
1512 FD_SET(fd
, &gEventFDs
);
1514 DetermineMaxEventFD();
1516 return mStatus_NoError
;
1519 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1520 mStatus
mDNSPosixRemoveFDFromEventLoop(int fd
)
1522 PosixEventSource
*iSource
;
1524 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1526 if (fd
== iSource
->fd
)
1528 FD_CLR(fd
, &gEventFDs
);
1529 RemoveFromList(&gEventSources
, iSource
);
1531 DetermineMaxEventFD();
1532 return mStatus_NoError
;
1535 return mStatus_NoSuchNameErr
;
1538 // Simply note the received signal in gEventSignals.
1539 mDNSlocal
void NoteSignal(int signum
)
1541 sigaddset(&gEventSignals
, signum
);
1544 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1545 mStatus
mDNSPosixListenForSignalInEventLoop(int signum
)
1547 struct sigaction action
;
1550 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1551 action
.sa_handler
= NoteSignal
;
1552 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1554 sigaddset(&gEventSignalSet
, signum
);
1559 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1560 mStatus
mDNSPosixIgnoreSignalInEventLoop(int signum
)
1562 struct sigaction action
;
1565 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1566 action
.sa_handler
= SIG_DFL
;
1567 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1569 sigdelset(&gEventSignalSet
, signum
);
1574 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1575 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1576 mStatus
mDNSPosixRunEventLoopOnce(mDNS
*m
, const struct timeval
*pTimeout
,
1577 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
1579 fd_set listenFDs
= gEventFDs
;
1580 int fdMax
= 0, numReady
;
1581 struct timeval timeout
= *pTimeout
;
1583 // Include the sockets that are listening to the wire in our select() set
1584 mDNSPosixGetFDSet(m
, &fdMax
, &listenFDs
, &timeout
); // timeout may get modified
1588 numReady
= select(fdMax
+ 1, &listenFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &timeout
);
1590 // If any data appeared, invoke its callback
1593 PosixEventSource
*iSource
;
1595 (void) mDNSPosixProcessFDSet(m
, &listenFDs
); // call this first to process wire data for clients
1597 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1599 if (FD_ISSET(iSource
->fd
, &listenFDs
))
1601 iSource
->Callback(iSource
->fd
, 0, iSource
->Context
);
1602 break; // in case callback removed elements from gEventSources
1605 *pDataDispatched
= mDNStrue
;
1608 *pDataDispatched
= mDNSfalse
;
1610 (void) sigprocmask(SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1611 *pSignalsReceived
= gEventSignals
;
1612 sigemptyset(&gEventSignals
);
1613 (void) sigprocmask(SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1615 return mStatus_NoError
;