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 #if COMPILER_LIKES_PRAGMA_MARK
415 #pragma mark ***** DDNS Config Platform Functions
418 mDNSexport
void mDNSPlatformSetDNSConfig(mDNS
*const m
, mDNSBool setservers
, mDNSBool setsearch
, domainname
*const fqdn
, DNameListElem
**RegDomains
, DNameListElem
**BrowseDomains
)
425 (void) BrowseDomains
;
428 mDNSexport mStatus
mDNSPlatformGetPrimaryInterface(mDNS
* const m
, mDNSAddr
* v4
, mDNSAddr
* v6
, mDNSAddr
* router
)
435 return mStatus_UnsupportedErr
;
438 mDNSexport
void mDNSPlatformDynDNSHostNameStatusChanged(const domainname
*const dname
, const mStatus status
)
444 #if COMPILER_LIKES_PRAGMA_MARK
445 #pragma mark ***** Init and Term
448 // This gets the current hostname, truncating it at the first dot if necessary
449 mDNSlocal
void GetUserSpecifiedRFC1034ComputerName(domainlabel
*const namelabel
)
452 gethostname((char *)(&namelabel
->c
[1]), MAX_DOMAIN_LABEL
);
453 while (len
< MAX_DOMAIN_LABEL
&& namelabel
->c
[len
+1] && namelabel
->c
[len
+1] != '.') len
++;
454 namelabel
->c
[0] = len
;
457 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
458 // Other platforms can either get the information from the appropriate place,
459 // or they can alternatively just require all registering services to provide an explicit name
460 mDNSlocal
void GetUserSpecifiedFriendlyComputerName(domainlabel
*const namelabel
)
462 // On Unix we have no better name than the host name, so we just use that.
463 GetUserSpecifiedRFC1034ComputerName(namelabel
);
466 mDNSexport
int ParseDNSServers(mDNS
*m
, const char *filePath
)
471 int numOfServers
= 0;
472 FILE *fp
= fopen(filePath
, "r");
473 if (fp
== NULL
) return -1;
474 while (fgets(line
,sizeof(line
),fp
))
477 line
[255]='\0'; // just to be safe
478 if (sscanf(line
,"%10s %15s", keyword
, nameserver
) != 2) continue; // it will skip whitespaces
479 if (strncasecmp(keyword
,"nameserver",10)) continue;
480 if (inet_aton(nameserver
, (struct in_addr
*)&ina
) != 0)
483 DNSAddr
.type
= mDNSAddrType_IPv4
;
484 DNSAddr
.ip
.v4
.NotAnInteger
= ina
.s_addr
;
485 mDNS_AddDNSServer(m
, NULL
, mDNSInterface_Any
, &DNSAddr
, UnicastDNSPort
, mDNSfalse
);
489 return (numOfServers
> 0) ? 0 : -1;
492 // Searches the interface list looking for the named interface.
493 // Returns a pointer to if it found, or NULL otherwise.
494 mDNSlocal PosixNetworkInterface
*SearchForInterfaceByName(mDNS
*const m
, const char *intfName
)
496 PosixNetworkInterface
*intf
;
499 assert(intfName
!= NULL
);
501 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
502 while ((intf
!= NULL
) && (strcmp(intf
->intfName
, intfName
) != 0))
503 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
508 mDNSexport mDNSInterfaceID
mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS
*const m
, mDNSu32 index
)
510 PosixNetworkInterface
*intf
;
514 if (index
== kDNSServiceInterfaceIndexLocalOnly
) return(mDNSInterface_LocalOnly
);
515 if (index
== kDNSServiceInterfaceIndexP2P
) return(mDNSInterface_P2P
);
516 if (index
== kDNSServiceInterfaceIndexAny
) return(mDNSInterface_Any
);
518 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
519 while ((intf
!= NULL
) && (mDNSu32
) intf
->index
!= index
)
520 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
522 return (mDNSInterfaceID
) intf
;
525 mDNSexport mDNSu32
mDNSPlatformInterfaceIndexfromInterfaceID(mDNS
*const m
, mDNSInterfaceID id
)
527 PosixNetworkInterface
*intf
;
531 if (id
== mDNSInterface_LocalOnly
) return(kDNSServiceInterfaceIndexLocalOnly
);
532 if (id
== mDNSInterface_P2P
) return(kDNSServiceInterfaceIndexP2P
);
533 if (id
== mDNSInterface_Any
) return(kDNSServiceInterfaceIndexAny
);
535 intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
536 while ((intf
!= NULL
) && (mDNSInterfaceID
) intf
!= id
)
537 intf
= (PosixNetworkInterface
*)(intf
->coreIntf
.next
);
539 return intf
? intf
->index
: 0;
542 // Frees the specified PosixNetworkInterface structure. The underlying
543 // interface must have already been deregistered with the mDNS core.
544 mDNSlocal
void FreePosixNetworkInterface(PosixNetworkInterface
*intf
)
546 assert(intf
!= NULL
);
547 if (intf
->intfName
!= NULL
) free((void *)intf
->intfName
);
548 if (intf
->multicastSocket4
!= -1) assert(close(intf
->multicastSocket4
) == 0);
550 if (intf
->multicastSocket6
!= -1) assert(close(intf
->multicastSocket6
) == 0);
555 // Grab the first interface, deregister it, free it, and repeat until done.
556 mDNSlocal
void ClearInterfaceList(mDNS
*const m
)
560 while (m
->HostInterfaces
)
562 PosixNetworkInterface
*intf
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
563 mDNS_DeregisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
564 if (gMDNSPlatformPosixVerboseLevel
> 0) fprintf(stderr
, "Deregistered interface %s\n", intf
->intfName
);
565 FreePosixNetworkInterface(intf
);
567 num_registered_interfaces
= 0;
568 num_pkts_accepted
= 0;
569 num_pkts_rejected
= 0;
572 // Sets up a send/receive socket.
573 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
574 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
575 mDNSlocal
int SetupSocket(struct sockaddr
*intfAddr
, mDNSIPPort port
, int interfaceIndex
, int *sktPtr
)
578 static const int kOn
= 1;
579 static const int kIntTwoFiveFive
= 255;
580 static const unsigned char kByteTwoFiveFive
= 255;
581 const mDNSBool JoinMulticastGroup
= (port
.NotAnInteger
!= 0);
583 (void) interfaceIndex
; // This parameter unused on plaforms that don't have IPv6
584 assert(intfAddr
!= NULL
);
585 assert(sktPtr
!= NULL
);
586 assert(*sktPtr
== -1);
588 // Open the socket...
589 if (intfAddr
->sa_family
== AF_INET
) *sktPtr
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
591 else if (intfAddr
->sa_family
== AF_INET6
) *sktPtr
= socket(PF_INET6
, SOCK_DGRAM
, IPPROTO_UDP
);
595 if (*sktPtr
< 0) { err
= errno
; perror((intfAddr
->sa_family
== AF_INET
) ? "socket AF_INET" : "socket AF_INET6"); }
597 // ... with a shared UDP port, if it's for multicast receiving
598 if (err
== 0 && port
.NotAnInteger
)
600 #if defined(SO_REUSEPORT)
601 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEPORT
, &kOn
, sizeof(kOn
));
602 #elif defined(SO_REUSEADDR)
603 err
= setsockopt(*sktPtr
, SOL_SOCKET
, SO_REUSEADDR
, &kOn
, sizeof(kOn
));
605 #error This platform has no way to avoid address busy errors on multicast.
607 if (err
< 0) { err
= errno
; perror("setsockopt - SO_REUSExxxx"); }
610 // We want to receive destination addresses and interface identifiers.
611 if (intfAddr
->sa_family
== AF_INET
)
614 struct sockaddr_in bindAddr
;
617 #if defined(IP_PKTINFO) // Linux
618 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_PKTINFO
, &kOn
, sizeof(kOn
));
619 if (err
< 0) { err
= errno
; perror("setsockopt - IP_PKTINFO"); }
620 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
621 #if defined(IP_RECVDSTADDR)
622 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVDSTADDR
, &kOn
, sizeof(kOn
));
623 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVDSTADDR"); }
625 #if defined(IP_RECVIF)
628 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVIF
, &kOn
, sizeof(kOn
));
629 if (err
< 0) { err
= errno
; perror("setsockopt - IP_RECVIF"); }
633 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
636 #if defined(IP_RECVTTL) // Linux
639 setsockopt(*sktPtr
, IPPROTO_IP
, IP_RECVTTL
, &kOn
, sizeof(kOn
));
640 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
644 // Add multicast group membership on this interface
645 if (err
== 0 && JoinMulticastGroup
)
647 imr
.imr_multiaddr
.s_addr
= AllDNSLinkGroup_v4
.ip
.v4
.NotAnInteger
;
648 imr
.imr_interface
= ((struct sockaddr_in
*)intfAddr
)->sin_addr
;
649 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &imr
, sizeof(imr
));
650 if (err
< 0) { err
= errno
; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
653 // Specify outgoing interface too
654 if (err
== 0 && JoinMulticastGroup
)
656 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_IF
, &((struct sockaddr_in
*)intfAddr
)->sin_addr
, sizeof(struct in_addr
));
657 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_IF"); }
660 // Per the mDNS spec, send unicast packets with TTL 255
663 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
664 if (err
< 0) { err
= errno
; perror("setsockopt - IP_TTL"); }
667 // and multicast packets with TTL 255 too
668 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
671 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
672 if (err
< 0 && errno
== EINVAL
)
673 err
= setsockopt(*sktPtr
, IPPROTO_IP
, IP_MULTICAST_TTL
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
674 if (err
< 0) { err
= errno
; perror("setsockopt - IP_MULTICAST_TTL"); }
677 // And start listening for packets
680 bindAddr
.sin_family
= AF_INET
;
681 bindAddr
.sin_port
= port
.NotAnInteger
;
682 bindAddr
.sin_addr
.s_addr
= INADDR_ANY
; // Want to receive multicasts AND unicasts on this socket
683 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr
, sizeof(bindAddr
));
684 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
686 } // endif (intfAddr->sa_family == AF_INET)
689 else if (intfAddr
->sa_family
== AF_INET6
)
691 struct ipv6_mreq imr6
;
692 struct sockaddr_in6 bindAddr6
;
693 #if defined(IPV6_PKTINFO)
696 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_PKTINFO
, &kOn
, sizeof(kOn
));
697 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_PKTINFO"); }
700 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
702 #if defined(IPV6_HOPLIMIT)
705 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_HOPLIMIT
, &kOn
, sizeof(kOn
));
706 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_HOPLIMIT"); }
710 // Add multicast group membership on this interface
711 if (err
== 0 && JoinMulticastGroup
)
713 imr6
.ipv6mr_multiaddr
= *(const struct in6_addr
*)&AllDNSLinkGroup_v6
.ip
.v6
;
714 imr6
.ipv6mr_interface
= interfaceIndex
;
715 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
716 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_JOIN_GROUP
, &imr6
, sizeof(imr6
));
720 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6
.ipv6mr_multiaddr
, imr6
.ipv6mr_interface
);
721 perror("setsockopt - IPV6_JOIN_GROUP");
725 // Specify outgoing interface too
726 if (err
== 0 && JoinMulticastGroup
)
728 u_int multicast_if
= interfaceIndex
;
729 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_IF
, &multicast_if
, sizeof(multicast_if
));
730 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_IF"); }
733 // We want to receive only IPv6 packets on this socket.
734 // Without this option, we may get IPv4 addresses as mapped addresses.
737 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_V6ONLY
, &kOn
, sizeof(kOn
));
738 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_V6ONLY"); }
741 // Per the mDNS spec, send unicast packets with TTL 255
744 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
745 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_UNICAST_HOPS"); }
748 // and multicast packets with TTL 255 too
749 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
752 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kByteTwoFiveFive
, sizeof(kByteTwoFiveFive
));
753 if (err
< 0 && errno
== EINVAL
)
754 err
= setsockopt(*sktPtr
, IPPROTO_IPV6
, IPV6_MULTICAST_HOPS
, &kIntTwoFiveFive
, sizeof(kIntTwoFiveFive
));
755 if (err
< 0) { err
= errno
; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
758 // And start listening for packets
761 mDNSPlatformMemZero(&bindAddr6
, sizeof(bindAddr6
));
762 #ifndef NOT_HAVE_SA_LEN
763 bindAddr6
.sin6_len
= sizeof(bindAddr6
);
765 bindAddr6
.sin6_family
= AF_INET6
;
766 bindAddr6
.sin6_port
= port
.NotAnInteger
;
767 bindAddr6
.sin6_flowinfo
= 0;
768 bindAddr6
.sin6_addr
= in6addr_any
; // Want to receive multicasts AND unicasts on this socket
769 bindAddr6
.sin6_scope_id
= 0;
770 err
= bind(*sktPtr
, (struct sockaddr
*) &bindAddr6
, sizeof(bindAddr6
));
771 if (err
< 0) { err
= errno
; perror("bind"); fflush(stderr
); }
773 } // endif (intfAddr->sa_family == AF_INET6)
776 // Set the socket to non-blocking.
779 err
= fcntl(*sktPtr
, F_GETFL
, 0);
780 if (err
< 0) err
= errno
;
783 err
= fcntl(*sktPtr
, F_SETFL
, err
| O_NONBLOCK
);
784 if (err
< 0) err
= errno
;
789 if (err
!= 0 && *sktPtr
!= -1) { assert(close(*sktPtr
) == 0); *sktPtr
= -1; }
790 assert((err
== 0) == (*sktPtr
!= -1));
794 // Creates a PosixNetworkInterface for the interface whose IP address is
795 // intfAddr and whose name is intfName and registers it with mDNS core.
796 mDNSlocal
int SetupOneInterface(mDNS
*const m
, struct sockaddr
*intfAddr
, struct sockaddr
*intfMask
, const char *intfName
, int intfIndex
)
799 PosixNetworkInterface
*intf
;
800 PosixNetworkInterface
*alias
= NULL
;
803 assert(intfAddr
!= NULL
);
804 assert(intfName
!= NULL
);
805 assert(intfMask
!= NULL
);
807 // Allocate the interface structure itself.
808 intf
= (PosixNetworkInterface
*)malloc(sizeof(*intf
));
809 if (intf
== NULL
) { assert(0); err
= ENOMEM
; }
811 // And make a copy of the intfName.
814 intf
->intfName
= strdup(intfName
);
815 if (intf
->intfName
== NULL
) { assert(0); err
= ENOMEM
; }
820 // Set up the fields required by the mDNS core.
821 SockAddrTomDNSAddr(intfAddr
, &intf
->coreIntf
.ip
, NULL
);
822 SockAddrTomDNSAddr(intfMask
, &intf
->coreIntf
.mask
, NULL
);
823 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
824 strncpy(intf
->coreIntf
.ifname
, intfName
, sizeof(intf
->coreIntf
.ifname
));
825 intf
->coreIntf
.ifname
[sizeof(intf
->coreIntf
.ifname
)-1] = 0;
826 intf
->coreIntf
.Advertise
= m
->AdvertiseLocalAddresses
;
827 intf
->coreIntf
.McastTxRx
= mDNStrue
;
829 // Set up the extra fields in PosixNetworkInterface.
830 assert(intf
->intfName
!= NULL
); // intf->intfName already set up above
831 intf
->index
= intfIndex
;
832 intf
->multicastSocket4
= -1;
834 intf
->multicastSocket6
= -1;
836 alias
= SearchForInterfaceByName(m
, intf
->intfName
);
837 if (alias
== NULL
) alias
= intf
;
838 intf
->coreIntf
.InterfaceID
= (mDNSInterfaceID
)alias
;
841 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName
, &intf
->coreIntf
.ip
, &alias
->coreIntf
.ip
);
844 // Set up the multicast socket
847 if (alias
->multicastSocket4
== -1 && intfAddr
->sa_family
== AF_INET
)
848 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket4
);
850 else if (alias
->multicastSocket6
== -1 && intfAddr
->sa_family
== AF_INET6
)
851 err
= SetupSocket(intfAddr
, MulticastDNSPort
, intf
->index
, &alias
->multicastSocket6
);
855 // The interface is all ready to go, let's register it with the mDNS core.
857 err
= mDNS_RegisterInterface(m
, &intf
->coreIntf
, mDNSfalse
);
862 num_registered_interfaces
++;
863 debugf("SetupOneInterface: %s %#a Registered", intf
->intfName
, &intf
->coreIntf
.ip
);
864 if (gMDNSPlatformPosixVerboseLevel
> 0)
865 fprintf(stderr
, "Registered interface %s\n", intf
->intfName
);
869 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
870 debugf("SetupOneInterface: %s %#a failed to register %d", intfName
, &intf
->coreIntf
.ip
, err
);
871 if (intf
) { FreePosixNetworkInterface(intf
); intf
= NULL
; }
874 assert((err
== 0) == (intf
!= NULL
));
879 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
880 mDNSlocal
int SetupInterfaceList(mDNS
*const m
)
882 mDNSBool foundav4
= mDNSfalse
;
884 struct ifi_info
*intfList
= get_ifi_info(AF_INET
, mDNStrue
);
885 struct ifi_info
*firstLoopback
= NULL
;
888 debugf("SetupInterfaceList");
890 if (intfList
== NULL
) err
= ENOENT
;
893 if (err
== 0) /* Link the IPv6 list to the end of the IPv4 list */
895 struct ifi_info
**p
= &intfList
;
896 while (*p
) p
= &(*p
)->ifi_next
;
897 *p
= get_ifi_info(AF_INET6
, mDNStrue
);
903 struct ifi_info
*i
= intfList
;
906 if ( ((i
->ifi_addr
->sa_family
== AF_INET
)
908 || (i
->ifi_addr
->sa_family
== AF_INET6
)
910 ) && (i
->ifi_flags
& IFF_UP
) && !(i
->ifi_flags
& IFF_POINTOPOINT
))
912 if (i
->ifi_flags
& IFF_LOOPBACK
)
914 if (firstLoopback
== NULL
)
919 if (SetupOneInterface(m
, i
->ifi_addr
, i
->ifi_netmask
, i
->ifi_name
, i
->ifi_index
) == 0)
920 if (i
->ifi_addr
->sa_family
== AF_INET
)
927 // If we found no normal interfaces but we did find a loopback interface, register the
928 // loopback interface. This allows self-discovery if no interfaces are configured.
929 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
930 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
931 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
932 if (!foundav4
&& firstLoopback
)
933 (void) SetupOneInterface(m
, firstLoopback
->ifi_addr
, firstLoopback
->ifi_netmask
, firstLoopback
->ifi_name
, firstLoopback
->ifi_index
);
937 if (intfList
!= NULL
) free_ifi_info(intfList
);
943 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
945 // Open a socket that will receive interface change notifications
946 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
948 mStatus err
= mStatus_NoError
;
949 struct sockaddr_nl snl
;
953 sock
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
957 // Configure read to be non-blocking because inbound msg size is not known in advance
958 (void) fcntl(sock
, F_SETFL
, O_NONBLOCK
);
960 /* Subscribe the socket to Link & IP addr notifications. */
961 mDNSPlatformMemZero(&snl
, sizeof snl
);
962 snl
.nl_family
= AF_NETLINK
;
963 snl
.nl_groups
= RTMGRP_LINK
| RTMGRP_IPV4_IFADDR
;
964 ret
= bind(sock
, (struct sockaddr
*) &snl
, sizeof snl
);
974 mDNSlocal
void PrintNetLinkMsg(const struct nlmsghdr
*pNLMsg
)
976 const char *kNLMsgTypes
[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
977 const char *kNLRtMsgTypes
[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
979 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg
->nlmsg_len
,
980 pNLMsg
->nlmsg_type
< RTM_BASE
? kNLMsgTypes
[pNLMsg
->nlmsg_type
] : kNLRtMsgTypes
[pNLMsg
->nlmsg_type
- RTM_BASE
],
981 pNLMsg
->nlmsg_flags
);
983 if (RTM_NEWLINK
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETLINK
)
985 struct ifinfomsg
*pIfInfo
= (struct ifinfomsg
*) NLMSG_DATA(pNLMsg
);
986 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo
->ifi_family
,
987 pIfInfo
->ifi_type
, pIfInfo
->ifi_index
, pIfInfo
->ifi_flags
, pIfInfo
->ifi_change
);
990 else if (RTM_NEWADDR
<= pNLMsg
->nlmsg_type
&& pNLMsg
->nlmsg_type
<= RTM_GETADDR
)
992 struct ifaddrmsg
*pIfAddr
= (struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
);
993 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr
->ifa_family
,
994 pIfAddr
->ifa_index
, pIfAddr
->ifa_flags
);
1000 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1001 // Read through the messages on sd and if any indicate that any interface records should
1002 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1006 struct nlmsghdr
*pNLMsg
= (struct nlmsghdr
*) buff
;
1009 // The structure here is more complex than it really ought to be because,
1010 // unfortunately, there's no good way to size a buffer in advance large
1011 // enough to hold all pending data and so avoid message fragmentation.
1012 // (Note that FIONREAD is not supported on AF_NETLINK.)
1014 readCount
= read(sd
, buff
, sizeof buff
);
1017 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1018 // If not, discard already-processed messages in buffer and read more data.
1019 if (((char*) &pNLMsg
[1] > (buff
+ readCount
)) || // i.e. *pNLMsg extends off end of buffer
1020 ((char*) pNLMsg
+ pNLMsg
->nlmsg_len
> (buff
+ readCount
)))
1022 if (buff
< (char*) pNLMsg
) // we have space to shuffle
1024 // discard processed data
1025 readCount
-= ((char*) pNLMsg
- buff
);
1026 memmove(buff
, pNLMsg
, readCount
);
1027 pNLMsg
= (struct nlmsghdr
*) buff
;
1030 readCount
+= read(sd
, buff
+ readCount
, sizeof buff
- readCount
);
1031 continue; // spin around and revalidate with new readCount
1034 break; // Otherwise message does not fit in buffer
1038 PrintNetLinkMsg(pNLMsg
);
1041 // Process the NetLink message
1042 if (pNLMsg
->nlmsg_type
== RTM_GETLINK
|| pNLMsg
->nlmsg_type
== RTM_NEWLINK
)
1043 result
|= 1 << ((struct ifinfomsg
*) NLMSG_DATA(pNLMsg
))->ifi_index
;
1044 else if (pNLMsg
->nlmsg_type
== RTM_DELADDR
|| pNLMsg
->nlmsg_type
== RTM_NEWADDR
)
1045 result
|= 1 << ((struct ifaddrmsg
*) NLMSG_DATA(pNLMsg
))->ifa_index
;
1047 // Advance pNLMsg to the next message in the buffer
1048 if ((pNLMsg
->nlmsg_flags
& NLM_F_MULTI
) != 0 && pNLMsg
->nlmsg_type
!= NLMSG_DONE
)
1050 ssize_t len
= readCount
- ((char*)pNLMsg
- buff
);
1051 pNLMsg
= NLMSG_NEXT(pNLMsg
, len
);
1060 #else // USES_NETLINK
1062 // Open a socket that will receive interface change notifications
1063 mDNSlocal mStatus
OpenIfNotifySocket(int *pFD
)
1065 *pFD
= socket(AF_ROUTE
, SOCK_RAW
, 0);
1068 return mStatus_UnknownErr
;
1070 // Configure read to be non-blocking because inbound msg size is not known in advance
1071 (void) fcntl(*pFD
, F_SETFL
, O_NONBLOCK
);
1073 return mStatus_NoError
;
1077 mDNSlocal
void PrintRoutingSocketMsg(const struct ifa_msghdr
*pRSMsg
)
1079 const char *kRSMsgTypes
[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1080 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1081 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1083 int index
= pRSMsg
->ifam_type
== RTM_IFINFO
? ((struct if_msghdr
*) pRSMsg
)->ifm_index
: pRSMsg
->ifam_index
;
1085 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg
->ifam_msglen
, kRSMsgTypes
[pRSMsg
->ifam_type
], index
);
1089 mDNSlocal mDNSu32
ProcessRoutingNotification(int sd
)
1090 // Read through the messages on sd and if any indicate that any interface records should
1091 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1095 struct ifa_msghdr
*pRSMsg
= (struct ifa_msghdr
*) buff
;
1098 readCount
= read(sd
, buff
, sizeof buff
);
1099 if (readCount
< (ssize_t
) sizeof(struct ifa_msghdr
))
1100 return mStatus_UnsupportedErr
; // cannot decipher message
1103 PrintRoutingSocketMsg(pRSMsg
);
1106 // Process the message
1107 if (pRSMsg
->ifam_type
== RTM_NEWADDR
|| pRSMsg
->ifam_type
== RTM_DELADDR
||
1108 pRSMsg
->ifam_type
== RTM_IFINFO
)
1110 if (pRSMsg
->ifam_type
== RTM_IFINFO
)
1111 result
|= 1 << ((struct if_msghdr
*) pRSMsg
)->ifm_index
;
1113 result
|= 1 << pRSMsg
->ifam_index
;
1119 #endif // USES_NETLINK
1121 // Called when data appears on interface change notification socket
1122 mDNSlocal
void InterfaceChangeCallback(int fd
, short filter
, void *context
)
1124 IfChangeRec
*pChgRec
= (IfChangeRec
*) context
;
1126 mDNSu32 changedInterfaces
= 0;
1127 struct timeval zeroTimeout
= { 0, 0 };
1130 (void)filter
; // Unused
1133 FD_SET(pChgRec
->NotifySD
, &readFDs
);
1137 changedInterfaces
|= ProcessRoutingNotification(pChgRec
->NotifySD
);
1139 while (0 < select(pChgRec
->NotifySD
+ 1, &readFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &zeroTimeout
));
1141 // Currently we rebuild the entire interface list whenever any interface change is
1142 // detected. If this ever proves to be a performance issue in a multi-homed
1143 // configuration, more care should be paid to changedInterfaces.
1144 if (changedInterfaces
)
1145 mDNSPlatformPosixRefreshInterfaceList(pChgRec
->mDNS
);
1148 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1149 mDNSlocal mStatus
WatchForInterfaceChange(mDNS
*const m
)
1152 IfChangeRec
*pChgRec
;
1154 pChgRec
= (IfChangeRec
*) mDNSPlatformMemAllocate(sizeof *pChgRec
);
1155 if (pChgRec
== NULL
)
1156 return mStatus_NoMemoryErr
;
1159 err
= OpenIfNotifySocket(&pChgRec
->NotifySD
);
1161 err
= mDNSPosixAddFDToEventLoop(pChgRec
->NotifySD
, InterfaceChangeCallback
, pChgRec
);
1166 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1167 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1168 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1169 mDNSlocal mDNSBool
mDNSPlatformInit_CanReceiveUnicast(void)
1172 int s
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
1173 struct sockaddr_in s5353
;
1174 s5353
.sin_family
= AF_INET
;
1175 s5353
.sin_port
= MulticastDNSPort
.NotAnInteger
;
1176 s5353
.sin_addr
.s_addr
= 0;
1177 err
= bind(s
, (struct sockaddr
*)&s5353
, sizeof(s5353
));
1179 if (err
) debugf("No unicast UDP responses");
1180 else debugf("Unicast UDP responses okay");
1184 // mDNS core calls this routine to initialise the platform-specific data.
1185 mDNSexport mStatus
mDNSPlatformInit(mDNS
*const m
)
1191 if (mDNSPlatformInit_CanReceiveUnicast()) m
->CanReceiveUnicastOn5353
= mDNStrue
;
1193 // Tell mDNS core the names of this machine.
1195 // Set up the nice label
1196 m
->nicelabel
.c
[0] = 0;
1197 GetUserSpecifiedFriendlyComputerName(&m
->nicelabel
);
1198 if (m
->nicelabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->nicelabel
, "Computer");
1200 // Set up the RFC 1034-compliant label
1201 m
->hostlabel
.c
[0] = 0;
1202 GetUserSpecifiedRFC1034ComputerName(&m
->hostlabel
);
1203 if (m
->hostlabel
.c
[0] == 0) MakeDomainLabelFromLiteralString(&m
->hostlabel
, "Computer");
1207 sa
.sa_family
= AF_INET
;
1208 m
->p
->unicastSocket4
= -1;
1209 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket4
);
1211 sa
.sa_family
= AF_INET6
;
1212 m
->p
->unicastSocket6
= -1;
1213 if (err
== mStatus_NoError
) err
= SetupSocket(&sa
, zeroIPPort
, 0, &m
->p
->unicastSocket6
);
1216 // Tell mDNS core about the network interfaces on this machine.
1217 if (err
== mStatus_NoError
) err
= SetupInterfaceList(m
);
1219 // Tell mDNS core about DNS Servers
1221 if (err
== mStatus_NoError
) ParseDNSServers(m
, uDNS_SERVERS_FILE
);
1224 if (err
== mStatus_NoError
)
1226 err
= WatchForInterfaceChange(m
);
1227 // Failure to observe interface changes is non-fatal.
1228 if (err
!= mStatus_NoError
)
1230 fprintf(stderr
, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err
);
1231 err
= mStatus_NoError
;
1235 // We don't do asynchronous initialization on the Posix platform, so by the time
1236 // we get here the setup will already have succeeded or failed. If it succeeded,
1237 // we should just call mDNSCoreInitComplete() immediately.
1238 if (err
== mStatus_NoError
)
1239 mDNSCoreInitComplete(m
, mStatus_NoError
);
1241 return PosixErrorToStatus(err
);
1244 // mDNS core calls this routine to clean up the platform-specific data.
1245 // In our case all we need to do is to tear down every network interface.
1246 mDNSexport
void mDNSPlatformClose(mDNS
*const m
)
1249 ClearInterfaceList(m
);
1250 if (m
->p
->unicastSocket4
!= -1) assert(close(m
->p
->unicastSocket4
) == 0);
1252 if (m
->p
->unicastSocket6
!= -1) assert(close(m
->p
->unicastSocket6
) == 0);
1256 mDNSexport mStatus
mDNSPlatformPosixRefreshInterfaceList(mDNS
*const m
)
1259 ClearInterfaceList(m
);
1260 err
= SetupInterfaceList(m
);
1261 return PosixErrorToStatus(err
);
1264 #if COMPILER_LIKES_PRAGMA_MARK
1265 #pragma mark ***** Locking
1268 // On the Posix platform, locking is a no-op because we only ever enter
1269 // mDNS core on the main thread.
1271 // mDNS core calls this routine when it wants to prevent
1272 // the platform from reentering mDNS core code.
1273 mDNSexport
void mDNSPlatformLock (const mDNS
*const m
)
1278 // mDNS core calls this routine when it release the lock taken by
1279 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1280 mDNSexport
void mDNSPlatformUnlock (const mDNS
*const m
)
1285 #if COMPILER_LIKES_PRAGMA_MARK
1286 #pragma mark ***** Strings
1289 // mDNS core calls this routine to copy C strings.
1290 // On the Posix platform this maps directly to the ANSI C strcpy.
1291 mDNSexport
void mDNSPlatformStrCopy(void *dst
, const void *src
)
1293 strcpy((char *)dst
, (char *)src
);
1296 // mDNS core calls this routine to get the length of a C string.
1297 // On the Posix platform this maps directly to the ANSI C strlen.
1298 mDNSexport mDNSu32
mDNSPlatformStrLen (const void *src
)
1300 return strlen((char*)src
);
1303 // mDNS core calls this routine to copy memory.
1304 // On the Posix platform this maps directly to the ANSI C memcpy.
1305 mDNSexport
void mDNSPlatformMemCopy(void *dst
, const void *src
, mDNSu32 len
)
1307 memcpy(dst
, src
, len
);
1310 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1311 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1312 mDNSexport mDNSBool
mDNSPlatformMemSame(const void *dst
, const void *src
, mDNSu32 len
)
1314 return memcmp(dst
, src
, len
) == 0;
1317 // mDNS core calls this routine to clear blocks of memory.
1318 // On the Posix platform this is a simple wrapper around ANSI C memset.
1319 mDNSexport
void mDNSPlatformMemZero(void *dst
, mDNSu32 len
)
1321 memset(dst
, 0, len
);
1324 mDNSexport
void * mDNSPlatformMemAllocate(mDNSu32 len
) { return(malloc(len
)); }
1325 mDNSexport
void mDNSPlatformMemFree (void *mem
) { free(mem
); }
1327 mDNSexport mDNSu32
mDNSPlatformRandomSeed(void)
1330 gettimeofday(&tv
, NULL
);
1334 mDNSexport mDNSs32 mDNSPlatformOneSecond
= 1024;
1336 mDNSexport mStatus
mDNSPlatformTimeInit(void)
1338 // No special setup is required on Posix -- we just use gettimeofday();
1339 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1340 // We should find a better way to do this
1341 return(mStatus_NoError
);
1344 mDNSexport mDNSs32
mDNSPlatformRawTime()
1347 gettimeofday(&tv
, NULL
);
1348 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1349 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1350 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1351 // 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.
1352 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1353 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1354 return((tv
.tv_sec
<< 10) | (tv
.tv_usec
* 16 / 15625));
1357 mDNSexport mDNSs32
mDNSPlatformUTC(void)
1362 mDNSexport
void mDNSPlatformSendWakeupPacket(mDNS
*const m
, mDNSInterfaceID InterfaceID
, char *EthAddr
, char *IPAddr
, int iteration
)
1371 mDNSlocal
void mDNSPosixAddToFDSet(int *nfds
, fd_set
*readfds
, int s
)
1373 if (*nfds
< s
+ 1) *nfds
= s
+ 1;
1377 mDNSexport
void mDNSPosixGetFDSet(mDNS
*m
, int *nfds
, fd_set
*readfds
, struct timeval
*timeout
)
1380 struct timeval interval
;
1382 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1383 mDNSs32 nextevent
= mDNS_Execute(m
);
1385 // 2. Build our list of active file descriptors
1386 PosixNetworkInterface
*info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1387 if (m
->p
->unicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket4
);
1389 if (m
->p
->unicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, m
->p
->unicastSocket6
);
1393 if (info
->multicastSocket4
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket4
);
1395 if (info
->multicastSocket6
!= -1) mDNSPosixAddToFDSet(nfds
, readfds
, info
->multicastSocket6
);
1397 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1400 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1401 ticks
= nextevent
- mDNS_TimeNow(m
);
1402 if (ticks
< 1) ticks
= 1;
1403 interval
.tv_sec
= ticks
>> 10; // The high 22 bits are seconds
1404 interval
.tv_usec
= ((ticks
& 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1406 // 4. If client's proposed timeout is more than what we want, then reduce it
1407 if (timeout
->tv_sec
> interval
.tv_sec
||
1408 (timeout
->tv_sec
== interval
.tv_sec
&& timeout
->tv_usec
> interval
.tv_usec
))
1409 *timeout
= interval
;
1412 mDNSexport
void mDNSPosixProcessFDSet(mDNS
*const m
, fd_set
*readfds
)
1414 PosixNetworkInterface
*info
;
1416 assert(readfds
!= NULL
);
1417 info
= (PosixNetworkInterface
*)(m
->HostInterfaces
);
1419 if (m
->p
->unicastSocket4
!= -1 && FD_ISSET(m
->p
->unicastSocket4
, readfds
))
1421 FD_CLR(m
->p
->unicastSocket4
, readfds
);
1422 SocketDataReady(m
, NULL
, m
->p
->unicastSocket4
);
1425 if (m
->p
->unicastSocket6
!= -1 && FD_ISSET(m
->p
->unicastSocket6
, readfds
))
1427 FD_CLR(m
->p
->unicastSocket6
, readfds
);
1428 SocketDataReady(m
, NULL
, m
->p
->unicastSocket6
);
1434 if (info
->multicastSocket4
!= -1 && FD_ISSET(info
->multicastSocket4
, readfds
))
1436 FD_CLR(info
->multicastSocket4
, readfds
);
1437 SocketDataReady(m
, info
, info
->multicastSocket4
);
1440 if (info
->multicastSocket6
!= -1 && FD_ISSET(info
->multicastSocket6
, readfds
))
1442 FD_CLR(info
->multicastSocket6
, readfds
);
1443 SocketDataReady(m
, info
, info
->multicastSocket6
);
1446 info
= (PosixNetworkInterface
*)(info
->coreIntf
.next
);
1451 mDNSlocal
void DetermineMaxEventFD(void)
1453 PosixEventSource
*iSource
;
1456 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1457 if (gMaxFD
< iSource
->fd
)
1458 gMaxFD
= iSource
->fd
;
1461 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1462 mStatus
mDNSPosixAddFDToEventLoop(int fd
, mDNSPosixEventCallback callback
, void *context
)
1464 PosixEventSource
*newSource
;
1466 if (gEventSources
.LinkOffset
== 0)
1467 InitLinkedList(&gEventSources
, offsetof(PosixEventSource
, Next
));
1469 if (fd
>= (int) FD_SETSIZE
|| fd
< 0)
1470 return mStatus_UnsupportedErr
;
1471 if (callback
== NULL
)
1472 return mStatus_BadParamErr
;
1474 newSource
= (PosixEventSource
*) malloc(sizeof *newSource
);
1475 if (NULL
== newSource
)
1476 return mStatus_NoMemoryErr
;
1478 newSource
->Callback
= callback
;
1479 newSource
->Context
= context
;
1482 AddToTail(&gEventSources
, newSource
);
1483 FD_SET(fd
, &gEventFDs
);
1485 DetermineMaxEventFD();
1487 return mStatus_NoError
;
1490 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1491 mStatus
mDNSPosixRemoveFDFromEventLoop(int fd
)
1493 PosixEventSource
*iSource
;
1495 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1497 if (fd
== iSource
->fd
)
1499 FD_CLR(fd
, &gEventFDs
);
1500 RemoveFromList(&gEventSources
, iSource
);
1502 DetermineMaxEventFD();
1503 return mStatus_NoError
;
1506 return mStatus_NoSuchNameErr
;
1509 // Simply note the received signal in gEventSignals.
1510 mDNSlocal
void NoteSignal(int signum
)
1512 sigaddset(&gEventSignals
, signum
);
1515 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1516 mStatus
mDNSPosixListenForSignalInEventLoop(int signum
)
1518 struct sigaction action
;
1521 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1522 action
.sa_handler
= NoteSignal
;
1523 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1525 sigaddset(&gEventSignalSet
, signum
);
1530 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1531 mStatus
mDNSPosixIgnoreSignalInEventLoop(int signum
)
1533 struct sigaction action
;
1536 mDNSPlatformMemZero(&action
, sizeof action
); // more portable than member-wise assignment
1537 action
.sa_handler
= SIG_DFL
;
1538 err
= sigaction(signum
, &action
, (struct sigaction
*) NULL
);
1540 sigdelset(&gEventSignalSet
, signum
);
1545 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1546 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1547 mStatus
mDNSPosixRunEventLoopOnce(mDNS
*m
, const struct timeval
*pTimeout
,
1548 sigset_t
*pSignalsReceived
, mDNSBool
*pDataDispatched
)
1550 fd_set listenFDs
= gEventFDs
;
1551 int fdMax
= 0, numReady
;
1552 struct timeval timeout
= *pTimeout
;
1554 // Include the sockets that are listening to the wire in our select() set
1555 mDNSPosixGetFDSet(m
, &fdMax
, &listenFDs
, &timeout
); // timeout may get modified
1559 numReady
= select(fdMax
+ 1, &listenFDs
, (fd_set
*) NULL
, (fd_set
*) NULL
, &timeout
);
1561 // If any data appeared, invoke its callback
1564 PosixEventSource
*iSource
;
1566 (void) mDNSPosixProcessFDSet(m
, &listenFDs
); // call this first to process wire data for clients
1568 for (iSource
=(PosixEventSource
*)gEventSources
.Head
; iSource
; iSource
= iSource
->Next
)
1570 if (FD_ISSET(iSource
->fd
, &listenFDs
))
1572 iSource
->Callback(iSource
->fd
, 0, iSource
->Context
);
1573 break; // in case callback removed elements from gEventSources
1576 *pDataDispatched
= mDNStrue
;
1579 *pDataDispatched
= mDNSfalse
;
1581 (void) sigprocmask(SIG_BLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1582 *pSignalsReceived
= gEventSignals
;
1583 sigemptyset(&gEventSignals
);
1584 (void) sigprocmask(SIG_UNBLOCK
, &gEventSignalSet
, (sigset_t
*) NULL
);
1586 return mStatus_NoError
;