]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/mDNSPosix.c
39cd66c76d85c51b619cfeb8d3ba223ae65ca7e5
[apple/mdnsresponder.git] / mDNSPosix / mDNSPosix.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved.
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
16 *
17 */
18
19 #include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
20 #include "DNSCommon.h"
21 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
22 #include "dns_sd.h"
23 #include "dnssec.h"
24 #include "nsec.h"
25
26 #include <assert.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <syslog.h>
33 #include <stdarg.h>
34 #include <fcntl.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <sys/socket.h>
38 #include <sys/uio.h>
39 #include <sys/select.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <time.h> // platform support for UTC time
43
44 #if USES_NETLINK
45 #include <asm/types.h>
46 #include <linux/netlink.h>
47 #include <linux/rtnetlink.h>
48 #else // USES_NETLINK
49 #include <net/route.h>
50 #include <net/if.h>
51 #endif // USES_NETLINK
52
53 #include "mDNSUNP.h"
54 #include "GenLinkedList.h"
55
56 // ***************************************************************************
57 // Structures
58
59 // We keep a list of client-supplied event sources in PosixEventSource records
60 struct PosixEventSource
61 {
62 mDNSPosixEventCallback Callback;
63 void *Context;
64 int fd;
65 struct PosixEventSource *Next;
66 };
67 typedef struct PosixEventSource PosixEventSource;
68
69 // Context record for interface change callback
70 struct IfChangeRec
71 {
72 int NotifySD;
73 mDNS *mDNS;
74 };
75 typedef struct IfChangeRec IfChangeRec;
76
77 // Note that static data is initialized to zero in (modern) C.
78 static fd_set gEventFDs;
79 static int gMaxFD; // largest fd in gEventFDs
80 static GenLinkedList gEventSources; // linked list of PosixEventSource's
81 static sigset_t gEventSignalSet; // Signals which event loop listens for
82 static sigset_t gEventSignals; // Signals which were received while inside loop
83
84 static PosixNetworkInterface *gRecentInterfaces;
85
86 // ***************************************************************************
87 // Globals (for debugging)
88
89 static int num_registered_interfaces = 0;
90 static int num_pkts_accepted = 0;
91 static int num_pkts_rejected = 0;
92
93 // ***************************************************************************
94 // Functions
95
96 int gMDNSPlatformPosixVerboseLevel = 0;
97
98 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
99
100 mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
101 {
102 switch (sa->sa_family)
103 {
104 case AF_INET:
105 {
106 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
107 ipAddr->type = mDNSAddrType_IPv4;
108 ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
109 if (ipPort) ipPort->NotAnInteger = sin->sin_port;
110 break;
111 }
112
113 #if HAVE_IPV6
114 case AF_INET6:
115 {
116 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
117 #ifndef NOT_HAVE_SA_LEN
118 assert(sin6->sin6_len == sizeof(*sin6));
119 #endif
120 ipAddr->type = mDNSAddrType_IPv6;
121 ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
122 if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
123 break;
124 }
125 #endif
126
127 default:
128 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
129 ipAddr->type = mDNSAddrType_None;
130 if (ipPort) ipPort->NotAnInteger = 0;
131 break;
132 }
133 }
134
135 #if COMPILER_LIKES_PRAGMA_MARK
136 #pragma mark ***** Send and Receive
137 #endif
138
139 // mDNS core calls this routine when it needs to send a packet.
140 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
141 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
142 mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
143 {
144 int err = 0;
145 struct sockaddr_storage to;
146 PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
147 int sendingsocket = -1;
148
149 (void)src; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
150 (void) useBackgroundTrafficClass;
151
152 assert(m != NULL);
153 assert(msg != NULL);
154 assert(end != NULL);
155 assert((((char *) end) - ((char *) msg)) > 0);
156
157 if (dstPort.NotAnInteger == 0)
158 {
159 LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
160 return PosixErrorToStatus(EINVAL);
161 }
162 if (dst->type == mDNSAddrType_IPv4)
163 {
164 struct sockaddr_in *sin = (struct sockaddr_in*)&to;
165 #ifndef NOT_HAVE_SA_LEN
166 sin->sin_len = sizeof(*sin);
167 #endif
168 sin->sin_family = AF_INET;
169 sin->sin_port = dstPort.NotAnInteger;
170 sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
171 sendingsocket = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
172 }
173
174 #if HAVE_IPV6
175 else if (dst->type == mDNSAddrType_IPv6)
176 {
177 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
178 mDNSPlatformMemZero(sin6, sizeof(*sin6));
179 #ifndef NOT_HAVE_SA_LEN
180 sin6->sin6_len = sizeof(*sin6);
181 #endif
182 sin6->sin6_family = AF_INET6;
183 sin6->sin6_port = dstPort.NotAnInteger;
184 sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
185 sendingsocket = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
186 }
187 #endif
188
189 if (sendingsocket >= 0)
190 err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
191
192 if (err > 0) err = 0;
193 else if (err < 0)
194 {
195 static int MessageCount = 0;
196 // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
197 if (!mDNSAddressIsAllDNSLinkGroup(dst))
198 if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
199
200 if (MessageCount < 1000)
201 {
202 MessageCount++;
203 if (thisIntf)
204 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
205 errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
206 else
207 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
208 }
209 }
210
211 return PosixErrorToStatus(err);
212 }
213
214 // This routine is called when the main loop detects that data is available on a socket.
215 mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
216 {
217 mDNSAddr senderAddr, destAddr;
218 mDNSIPPort senderPort;
219 ssize_t packetLen;
220 DNSMessage packet;
221 struct my_in_pktinfo packetInfo;
222 struct sockaddr_storage from;
223 socklen_t fromLen;
224 int flags;
225 mDNSu8 ttl;
226 mDNSBool reject;
227 const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
228
229 assert(m != NULL);
230 assert(skt >= 0);
231
232 fromLen = sizeof(from);
233 flags = 0;
234 packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
235
236 if (packetLen >= 0)
237 {
238 SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
239 SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
240
241 // If we have broken IP_RECVDSTADDR functionality (so far
242 // I've only seen this on OpenBSD) then apply a hack to
243 // convince mDNS Core that this isn't a spoof packet.
244 // Basically what we do is check to see whether the
245 // packet arrived as a multicast and, if so, set its
246 // destAddr to the mDNS address.
247 //
248 // I must admit that I could just be doing something
249 // wrong on OpenBSD and hence triggering this problem
250 // but I'm at a loss as to how.
251 //
252 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
253 // no way to tell the destination address or interface this packet arrived on,
254 // so all we can do is just assume it's a multicast
255
256 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
257 if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
258 {
259 destAddr.type = senderAddr.type;
260 if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
261 else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
262 }
263 #endif
264
265 // We only accept the packet if the interface on which it came
266 // in matches the interface associated with this socket.
267 // We do this match by name or by index, depending on which
268 // information is available. recvfrom_flags sets the name
269 // to "" if the name isn't available, or the index to -1
270 // if the index is available. This accomodates the various
271 // different capabilities of our target platforms.
272
273 reject = mDNSfalse;
274 if (!intf)
275 {
276 // Ignore multicasts accidentally delivered to our unicast receiving socket
277 if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
278 }
279 else
280 {
281 if (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
282 else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
283
284 if (reject)
285 {
286 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
287 &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
288 &intf->coreIntf.ip, intf->intfName, intf->index, skt);
289 packetLen = -1;
290 num_pkts_rejected++;
291 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
292 {
293 fprintf(stderr,
294 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
295 num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
296 num_pkts_accepted = 0;
297 num_pkts_rejected = 0;
298 }
299 }
300 else
301 {
302 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
303 &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
304 num_pkts_accepted++;
305 }
306 }
307 }
308
309 if (packetLen >= 0)
310 mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
311 &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
312 }
313
314 mDNSexport mDNSBool mDNSPlatformPeekUDP(mDNS *const m, UDPSocket *src)
315 {
316 (void)m; // unused
317 (void)src; // unused
318 return mDNSfalse;
319 }
320
321 mDNSexport TCPSocket *mDNSPlatformTCPSocket(mDNS * const m, TCPSocketFlags flags, mDNSIPPort * port, mDNSBool useBackgroundTrafficClass)
322 {
323 (void)m; // Unused
324 (void)flags; // Unused
325 (void)port; // Unused
326 (void)useBackgroundTrafficClass; // Unused
327 return NULL;
328 }
329
330 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd)
331 {
332 (void)flags; // Unused
333 (void)sd; // Unused
334 return NULL;
335 }
336
337 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
338 {
339 (void)sock; // Unused
340 return -1;
341 }
342
343 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname, mDNSInterfaceID InterfaceID,
344 TCPConnectionCallback callback, void *context)
345 {
346 (void)sock; // Unused
347 (void)dst; // Unused
348 (void)dstport; // Unused
349 (void)hostname; // Unused
350 (void)InterfaceID; // Unused
351 (void)callback; // Unused
352 (void)context; // Unused
353 return(mStatus_UnsupportedErr);
354 }
355
356 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
357 {
358 (void)sock; // Unused
359 }
360
361 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
362 {
363 (void)sock; // Unused
364 (void)buf; // Unused
365 (void)buflen; // Unused
366 (void)closed; // Unused
367 return 0;
368 }
369
370 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
371 {
372 (void)sock; // Unused
373 (void)msg; // Unused
374 (void)len; // Unused
375 return 0;
376 }
377
378 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNS * const m, mDNSIPPort port)
379 {
380 (void)m; // Unused
381 (void)port; // Unused
382 return NULL;
383 }
384
385 mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
386 {
387 (void)sock; // Unused
388 }
389
390 mDNSexport void mDNSPlatformUpdateProxyList(mDNS *const m, const mDNSInterfaceID InterfaceID)
391 {
392 (void)m; // Unused
393 (void)InterfaceID; // Unused
394 }
395
396 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
397 {
398 (void)msg; // Unused
399 (void)end; // Unused
400 (void)InterfaceID; // Unused
401 }
402
403 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
404 {
405 (void)m; // Unused
406 (void)tpa; // Unused
407 (void)tha; // Unused
408 (void)InterfaceID; // Unused
409 }
410
411 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
412 {
413 return(mStatus_UnsupportedErr);
414 }
415
416 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
417 {
418 }
419
420 mDNSexport void mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason)
421 {
422 (void) m;
423 (void) allowSleep;
424 (void) reason;
425 }
426
427 #if COMPILER_LIKES_PRAGMA_MARK
428 #pragma mark -
429 #pragma mark - /etc/hosts support
430 #endif
431
432 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
433 {
434 (void)m; // unused
435 (void)rr;
436 (void)result;
437 }
438
439
440 #if COMPILER_LIKES_PRAGMA_MARK
441 #pragma mark ***** DDNS Config Platform Functions
442 #endif
443
444 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
445 DNameListElem **BrowseDomains, mDNSBool ackConfig)
446 {
447 (void) m;
448 (void) setservers;
449 (void) fqdn;
450 (void) setsearch;
451 (void) RegDomains;
452 (void) BrowseDomains;
453 (void) ackConfig;
454
455 return mDNStrue;
456 }
457
458 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNS * const m, mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
459 {
460 (void) m;
461 (void) v4;
462 (void) v6;
463 (void) router;
464
465 return mStatus_UnsupportedErr;
466 }
467
468 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
469 {
470 (void) dname;
471 (void) status;
472 }
473
474 #if COMPILER_LIKES_PRAGMA_MARK
475 #pragma mark ***** Init and Term
476 #endif
477
478 // This gets the current hostname, truncating it at the first dot if necessary
479 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
480 {
481 int len = 0;
482 gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
483 while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
484 namelabel->c[0] = len;
485 }
486
487 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
488 // Other platforms can either get the information from the appropriate place,
489 // or they can alternatively just require all registering services to provide an explicit name
490 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
491 {
492 // On Unix we have no better name than the host name, so we just use that.
493 GetUserSpecifiedRFC1034ComputerName(namelabel);
494 }
495
496 mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
497 {
498 char line[256];
499 char nameserver[16];
500 char keyword[11];
501 int numOfServers = 0;
502 FILE *fp = fopen(filePath, "r");
503 if (fp == NULL) return -1;
504 while (fgets(line,sizeof(line),fp))
505 {
506 struct in_addr ina;
507 line[255]='\0'; // just to be safe
508 if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue; // it will skip whitespaces
509 if (strncasecmp(keyword,"nameserver",10)) continue;
510 if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
511 {
512 mDNSAddr DNSAddr;
513 DNSAddr.type = mDNSAddrType_IPv4;
514 DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
515 mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
516 numOfServers++;
517 }
518 }
519 return (numOfServers > 0) ? 0 : -1;
520 }
521
522 // Searches the interface list looking for the named interface.
523 // Returns a pointer to if it found, or NULL otherwise.
524 mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
525 {
526 PosixNetworkInterface *intf;
527
528 assert(m != NULL);
529 assert(intfName != NULL);
530
531 intf = (PosixNetworkInterface*)(m->HostInterfaces);
532 while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
533 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
534
535 return intf;
536 }
537
538 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
539 {
540 PosixNetworkInterface *intf;
541
542 assert(m != NULL);
543
544 if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
545 if (index == kDNSServiceInterfaceIndexP2P ) return(mDNSInterface_P2P);
546 if (index == kDNSServiceInterfaceIndexAny ) return(mDNSInterface_Any);
547
548 intf = (PosixNetworkInterface*)(m->HostInterfaces);
549 while ((intf != NULL) && (mDNSu32) intf->index != index)
550 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
551
552 return (mDNSInterfaceID) intf;
553 }
554
555 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
556 {
557 PosixNetworkInterface *intf;
558 (void) suppressNetworkChange; // Unused
559
560 assert(m != NULL);
561
562 if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
563 if (id == mDNSInterface_P2P ) return(kDNSServiceInterfaceIndexP2P);
564 if (id == mDNSInterface_Any ) return(kDNSServiceInterfaceIndexAny);
565
566 intf = (PosixNetworkInterface*)(m->HostInterfaces);
567 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
568 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
569
570 if (intf) return intf->index;
571
572 // If we didn't find the interface, check the RecentInterfaces list as well
573 intf = gRecentInterfaces;
574 while ((intf != NULL) && (mDNSInterfaceID) intf != id)
575 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
576
577 return intf ? intf->index : 0;
578 }
579
580 // Frees the specified PosixNetworkInterface structure. The underlying
581 // interface must have already been deregistered with the mDNS core.
582 mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
583 {
584 assert(intf != NULL);
585 if (intf->intfName != NULL) free((void *)intf->intfName);
586 if (intf->multicastSocket4 != -1) assert(close(intf->multicastSocket4) == 0);
587 #if HAVE_IPV6
588 if (intf->multicastSocket6 != -1) assert(close(intf->multicastSocket6) == 0);
589 #endif
590
591 // Move interface to the RecentInterfaces list for a minute
592 intf->LastSeen = mDNSPlatformUTC();
593 intf->coreIntf.next = &gRecentInterfaces->coreIntf;
594 gRecentInterfaces = intf;
595 }
596
597 // Grab the first interface, deregister it, free it, and repeat until done.
598 mDNSlocal void ClearInterfaceList(mDNS *const m)
599 {
600 assert(m != NULL);
601
602 while (m->HostInterfaces)
603 {
604 PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
605 mDNS_DeregisterInterface(m, &intf->coreIntf, mDNSfalse);
606 if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
607 FreePosixNetworkInterface(intf);
608 }
609 num_registered_interfaces = 0;
610 num_pkts_accepted = 0;
611 num_pkts_rejected = 0;
612 }
613
614 // Sets up a send/receive socket.
615 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
616 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
617 mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
618 {
619 int err = 0;
620 static const int kOn = 1;
621 static const int kIntTwoFiveFive = 255;
622 static const unsigned char kByteTwoFiveFive = 255;
623 const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
624
625 (void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
626 assert(intfAddr != NULL);
627 assert(sktPtr != NULL);
628 assert(*sktPtr == -1);
629
630 // Open the socket...
631 if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
632 #if HAVE_IPV6
633 else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
634 #endif
635 else return EINVAL;
636
637 if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
638
639 // ... with a shared UDP port, if it's for multicast receiving
640 if (err == 0 && port.NotAnInteger)
641 {
642 #if defined(SO_REUSEPORT)
643 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
644 #elif defined(SO_REUSEADDR)
645 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
646 #else
647 #error This platform has no way to avoid address busy errors on multicast.
648 #endif
649 if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
650
651 // Enable inbound packets on IFEF_AWDL interface.
652 // Only done for multicast sockets, since we don't expect unicast socket operations
653 // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
654 #ifndef SO_RECV_ANYIF
655 #define SO_RECV_ANYIF 0x1104 /* unrestricted inbound processing */
656 #endif
657 if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
658 }
659
660 // We want to receive destination addresses and interface identifiers.
661 if (intfAddr->sa_family == AF_INET)
662 {
663 struct ip_mreq imr;
664 struct sockaddr_in bindAddr;
665 if (err == 0)
666 {
667 #if defined(IP_PKTINFO) // Linux
668 err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
669 if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
670 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
671 #if defined(IP_RECVDSTADDR)
672 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
673 if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
674 #endif
675 #if defined(IP_RECVIF)
676 if (err == 0)
677 {
678 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
679 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
680 }
681 #endif
682 #else
683 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
684 #endif
685 }
686 #if defined(IP_RECVTTL) // Linux
687 if (err == 0)
688 {
689 setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
690 // We no longer depend on being able to get the received TTL, so don't worry if the option fails
691 }
692 #endif
693
694 // Add multicast group membership on this interface
695 if (err == 0 && JoinMulticastGroup)
696 {
697 imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
698 imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
699 err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
700 if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
701 }
702
703 // Specify outgoing interface too
704 if (err == 0 && JoinMulticastGroup)
705 {
706 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
707 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
708 }
709
710 // Per the mDNS spec, send unicast packets with TTL 255
711 if (err == 0)
712 {
713 err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
714 if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
715 }
716
717 // and multicast packets with TTL 255 too
718 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
719 if (err == 0)
720 {
721 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
722 if (err < 0 && errno == EINVAL)
723 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
724 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
725 }
726
727 // And start listening for packets
728 if (err == 0)
729 {
730 bindAddr.sin_family = AF_INET;
731 bindAddr.sin_port = port.NotAnInteger;
732 bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
733 err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
734 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
735 }
736 } // endif (intfAddr->sa_family == AF_INET)
737
738 #if HAVE_IPV6
739 else if (intfAddr->sa_family == AF_INET6)
740 {
741 struct ipv6_mreq imr6;
742 struct sockaddr_in6 bindAddr6;
743 #if defined(IPV6_PKTINFO)
744 if (err == 0)
745 {
746 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
747 if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
748 }
749 #else
750 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
751 #endif
752 #if defined(IPV6_HOPLIMIT)
753 if (err == 0)
754 {
755 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
756 if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
757 }
758 #endif
759
760 // Add multicast group membership on this interface
761 if (err == 0 && JoinMulticastGroup)
762 {
763 imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
764 imr6.ipv6mr_interface = interfaceIndex;
765 //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
766 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
767 if (err < 0)
768 {
769 err = errno;
770 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
771 perror("setsockopt - IPV6_JOIN_GROUP");
772 }
773 }
774
775 // Specify outgoing interface too
776 if (err == 0 && JoinMulticastGroup)
777 {
778 u_int multicast_if = interfaceIndex;
779 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
780 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
781 }
782
783 // We want to receive only IPv6 packets on this socket.
784 // Without this option, we may get IPv4 addresses as mapped addresses.
785 if (err == 0)
786 {
787 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
788 if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
789 }
790
791 // Per the mDNS spec, send unicast packets with TTL 255
792 if (err == 0)
793 {
794 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
795 if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
796 }
797
798 // and multicast packets with TTL 255 too
799 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
800 if (err == 0)
801 {
802 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
803 if (err < 0 && errno == EINVAL)
804 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
805 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
806 }
807
808 // And start listening for packets
809 if (err == 0)
810 {
811 mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
812 #ifndef NOT_HAVE_SA_LEN
813 bindAddr6.sin6_len = sizeof(bindAddr6);
814 #endif
815 bindAddr6.sin6_family = AF_INET6;
816 bindAddr6.sin6_port = port.NotAnInteger;
817 bindAddr6.sin6_flowinfo = 0;
818 bindAddr6.sin6_addr = in6addr_any; // Want to receive multicasts AND unicasts on this socket
819 bindAddr6.sin6_scope_id = 0;
820 err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
821 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
822 }
823 } // endif (intfAddr->sa_family == AF_INET6)
824 #endif
825
826 // Set the socket to non-blocking.
827 if (err == 0)
828 {
829 err = fcntl(*sktPtr, F_GETFL, 0);
830 if (err < 0) err = errno;
831 else
832 {
833 err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
834 if (err < 0) err = errno;
835 }
836 }
837
838 // Clean up
839 if (err != 0 && *sktPtr != -1) { assert(close(*sktPtr) == 0); *sktPtr = -1; }
840 assert((err == 0) == (*sktPtr != -1));
841 return err;
842 }
843
844 // Creates a PosixNetworkInterface for the interface whose IP address is
845 // intfAddr and whose name is intfName and registers it with mDNS core.
846 mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
847 {
848 int err = 0;
849 PosixNetworkInterface *intf;
850 PosixNetworkInterface *alias = NULL;
851
852 assert(m != NULL);
853 assert(intfAddr != NULL);
854 assert(intfName != NULL);
855 assert(intfMask != NULL);
856
857 // Allocate the interface structure itself.
858 intf = (PosixNetworkInterface*)malloc(sizeof(*intf));
859 if (intf == NULL) { assert(0); err = ENOMEM; }
860
861 // And make a copy of the intfName.
862 if (err == 0)
863 {
864 intf->intfName = strdup(intfName);
865 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
866 }
867
868 if (err == 0)
869 {
870 // Set up the fields required by the mDNS core.
871 SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
872 SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
873
874 //LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
875 strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
876 intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
877 intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
878 intf->coreIntf.McastTxRx = mDNStrue;
879
880 // Set up the extra fields in PosixNetworkInterface.
881 assert(intf->intfName != NULL); // intf->intfName already set up above
882 intf->index = intfIndex;
883 intf->multicastSocket4 = -1;
884 #if HAVE_IPV6
885 intf->multicastSocket6 = -1;
886 #endif
887 alias = SearchForInterfaceByName(m, intf->intfName);
888 if (alias == NULL) alias = intf;
889 intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
890
891 if (alias != intf)
892 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
893 }
894
895 // Set up the multicast socket
896 if (err == 0)
897 {
898 if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
899 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
900 #if HAVE_IPV6
901 else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
902 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
903 #endif
904 }
905
906 // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
907 // and skip the probe phase of the probe/announce packet sequence.
908 intf->coreIntf.DirectLink = mDNSfalse;
909 #ifdef DIRECTLINK_INTERFACE_NAME
910 if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
911 intf->coreIntf.DirectLink = mDNStrue;
912 #endif
913
914 // The interface is all ready to go, let's register it with the mDNS core.
915 if (err == 0)
916 err = mDNS_RegisterInterface(m, &intf->coreIntf, mDNSfalse);
917
918 // Clean up.
919 if (err == 0)
920 {
921 num_registered_interfaces++;
922 debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
923 if (gMDNSPlatformPosixVerboseLevel > 0)
924 fprintf(stderr, "Registered interface %s\n", intf->intfName);
925 }
926 else
927 {
928 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
929 debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
930 if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
931 }
932
933 assert((err == 0) == (intf != NULL));
934
935 return err;
936 }
937
938 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
939 mDNSlocal int SetupInterfaceList(mDNS *const m)
940 {
941 mDNSBool foundav4 = mDNSfalse;
942 int err = 0;
943 struct ifi_info *intfList = get_ifi_info(AF_INET, mDNStrue);
944 struct ifi_info *firstLoopback = NULL;
945
946 assert(m != NULL);
947 debugf("SetupInterfaceList");
948
949 if (intfList == NULL) err = ENOENT;
950
951 #if HAVE_IPV6
952 if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
953 {
954 struct ifi_info **p = &intfList;
955 while (*p) p = &(*p)->ifi_next;
956 *p = get_ifi_info(AF_INET6, mDNStrue);
957 }
958 #endif
959
960 if (err == 0)
961 {
962 struct ifi_info *i = intfList;
963 while (i)
964 {
965 if ( ((i->ifi_addr->sa_family == AF_INET)
966 #if HAVE_IPV6
967 || (i->ifi_addr->sa_family == AF_INET6)
968 #endif
969 ) && (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT))
970 {
971 if (i->ifi_flags & IFF_LOOPBACK)
972 {
973 if (firstLoopback == NULL)
974 firstLoopback = i;
975 }
976 else
977 {
978 if (SetupOneInterface(m, i->ifi_addr, i->ifi_netmask, i->ifi_name, i->ifi_index) == 0)
979 if (i->ifi_addr->sa_family == AF_INET)
980 foundav4 = mDNStrue;
981 }
982 }
983 i = i->ifi_next;
984 }
985
986 // If we found no normal interfaces but we did find a loopback interface, register the
987 // loopback interface. This allows self-discovery if no interfaces are configured.
988 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
989 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
990 // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
991 if (!foundav4 && firstLoopback)
992 (void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_netmask, firstLoopback->ifi_name, firstLoopback->ifi_index);
993 }
994
995 // Clean up.
996 if (intfList != NULL) free_ifi_info(intfList);
997
998 // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
999 PosixNetworkInterface **ri = &gRecentInterfaces;
1000 const mDNSs32 utc = mDNSPlatformUTC();
1001 while (*ri)
1002 {
1003 PosixNetworkInterface *pi = *ri;
1004 if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
1005 else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
1006 }
1007
1008 return err;
1009 }
1010
1011 #if USES_NETLINK
1012
1013 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1014
1015 // Open a socket that will receive interface change notifications
1016 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1017 {
1018 mStatus err = mStatus_NoError;
1019 struct sockaddr_nl snl;
1020 int sock;
1021 int ret;
1022
1023 sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1024 if (sock < 0)
1025 return errno;
1026
1027 // Configure read to be non-blocking because inbound msg size is not known in advance
1028 (void) fcntl(sock, F_SETFL, O_NONBLOCK);
1029
1030 /* Subscribe the socket to Link & IP addr notifications. */
1031 mDNSPlatformMemZero(&snl, sizeof snl);
1032 snl.nl_family = AF_NETLINK;
1033 snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
1034 ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
1035 if (0 == ret)
1036 *pFD = sock;
1037 else
1038 err = errno;
1039
1040 return err;
1041 }
1042
1043 #if MDNS_DEBUGMSGS
1044 mDNSlocal void PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
1045 {
1046 const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1047 const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1048
1049 printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
1050 pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
1051 pNLMsg->nlmsg_flags);
1052
1053 if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
1054 {
1055 struct ifinfomsg *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
1056 printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
1057 pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
1058
1059 }
1060 else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
1061 {
1062 struct ifaddrmsg *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
1063 printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
1064 pIfAddr->ifa_index, pIfAddr->ifa_flags);
1065 }
1066 printf("\n");
1067 }
1068 #endif
1069
1070 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1071 // Read through the messages on sd and if any indicate that any interface records should
1072 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1073 {
1074 ssize_t readCount;
1075 char buff[4096];
1076 struct nlmsghdr *pNLMsg = (struct nlmsghdr*) buff;
1077 mDNSu32 result = 0;
1078
1079 // The structure here is more complex than it really ought to be because,
1080 // unfortunately, there's no good way to size a buffer in advance large
1081 // enough to hold all pending data and so avoid message fragmentation.
1082 // (Note that FIONREAD is not supported on AF_NETLINK.)
1083
1084 readCount = read(sd, buff, sizeof buff);
1085 while (1)
1086 {
1087 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1088 // If not, discard already-processed messages in buffer and read more data.
1089 if (((char*) &pNLMsg[1] > (buff + readCount)) || // i.e. *pNLMsg extends off end of buffer
1090 ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
1091 {
1092 if (buff < (char*) pNLMsg) // we have space to shuffle
1093 {
1094 // discard processed data
1095 readCount -= ((char*) pNLMsg - buff);
1096 memmove(buff, pNLMsg, readCount);
1097 pNLMsg = (struct nlmsghdr*) buff;
1098
1099 // read more data
1100 readCount += read(sd, buff + readCount, sizeof buff - readCount);
1101 continue; // spin around and revalidate with new readCount
1102 }
1103 else
1104 break; // Otherwise message does not fit in buffer
1105 }
1106
1107 #if MDNS_DEBUGMSGS
1108 PrintNetLinkMsg(pNLMsg);
1109 #endif
1110
1111 // Process the NetLink message
1112 if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
1113 result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
1114 else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
1115 result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
1116
1117 // Advance pNLMsg to the next message in the buffer
1118 if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
1119 {
1120 ssize_t len = readCount - ((char*)pNLMsg - buff);
1121 pNLMsg = NLMSG_NEXT(pNLMsg, len);
1122 }
1123 else
1124 break; // all done!
1125 }
1126
1127 return result;
1128 }
1129
1130 #else // USES_NETLINK
1131
1132 // Open a socket that will receive interface change notifications
1133 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1134 {
1135 *pFD = socket(AF_ROUTE, SOCK_RAW, 0);
1136
1137 if (*pFD < 0)
1138 return mStatus_UnknownErr;
1139
1140 // Configure read to be non-blocking because inbound msg size is not known in advance
1141 (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
1142
1143 return mStatus_NoError;
1144 }
1145
1146 #if MDNS_DEBUGMSGS
1147 mDNSlocal void PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
1148 {
1149 const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1150 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1151 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1152
1153 int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
1154
1155 printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
1156 }
1157 #endif
1158
1159 mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
1160 // Read through the messages on sd and if any indicate that any interface records should
1161 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1162 {
1163 ssize_t readCount;
1164 char buff[4096];
1165 struct ifa_msghdr *pRSMsg = (struct ifa_msghdr*) buff;
1166 mDNSu32 result = 0;
1167
1168 readCount = read(sd, buff, sizeof buff);
1169 if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
1170 return mStatus_UnsupportedErr; // cannot decipher message
1171
1172 #if MDNS_DEBUGMSGS
1173 PrintRoutingSocketMsg(pRSMsg);
1174 #endif
1175
1176 // Process the message
1177 if (pRSMsg->ifam_type == RTM_NEWADDR || pRSMsg->ifam_type == RTM_DELADDR ||
1178 pRSMsg->ifam_type == RTM_IFINFO)
1179 {
1180 if (pRSMsg->ifam_type == RTM_IFINFO)
1181 result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
1182 else
1183 result |= 1 << pRSMsg->ifam_index;
1184 }
1185
1186 return result;
1187 }
1188
1189 #endif // USES_NETLINK
1190
1191 // Called when data appears on interface change notification socket
1192 mDNSlocal void InterfaceChangeCallback(int fd, short filter, void *context)
1193 {
1194 IfChangeRec *pChgRec = (IfChangeRec*) context;
1195 fd_set readFDs;
1196 mDNSu32 changedInterfaces = 0;
1197 struct timeval zeroTimeout = { 0, 0 };
1198
1199 (void)fd; // Unused
1200 (void)filter; // Unused
1201
1202 FD_ZERO(&readFDs);
1203 FD_SET(pChgRec->NotifySD, &readFDs);
1204
1205 do
1206 {
1207 changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
1208 }
1209 while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
1210
1211 // Currently we rebuild the entire interface list whenever any interface change is
1212 // detected. If this ever proves to be a performance issue in a multi-homed
1213 // configuration, more care should be paid to changedInterfaces.
1214 if (changedInterfaces)
1215 mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
1216 }
1217
1218 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1219 mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
1220 {
1221 mStatus err;
1222 IfChangeRec *pChgRec;
1223
1224 pChgRec = (IfChangeRec*) mDNSPlatformMemAllocate(sizeof *pChgRec);
1225 if (pChgRec == NULL)
1226 return mStatus_NoMemoryErr;
1227
1228 pChgRec->mDNS = m;
1229 err = OpenIfNotifySocket(&pChgRec->NotifySD);
1230 if (err == 0)
1231 err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
1232
1233 return err;
1234 }
1235
1236 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1237 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1238 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1239 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
1240 {
1241 int err;
1242 int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1243 struct sockaddr_in s5353;
1244 s5353.sin_family = AF_INET;
1245 s5353.sin_port = MulticastDNSPort.NotAnInteger;
1246 s5353.sin_addr.s_addr = 0;
1247 err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
1248 close(s);
1249 if (err) debugf("No unicast UDP responses");
1250 else debugf("Unicast UDP responses okay");
1251 return(err == 0);
1252 }
1253
1254 // mDNS core calls this routine to initialise the platform-specific data.
1255 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
1256 {
1257 int err = 0;
1258 struct sockaddr sa;
1259 assert(m != NULL);
1260
1261 if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
1262
1263 // Tell mDNS core the names of this machine.
1264
1265 // Set up the nice label
1266 m->nicelabel.c[0] = 0;
1267 GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
1268 if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
1269
1270 // Set up the RFC 1034-compliant label
1271 m->hostlabel.c[0] = 0;
1272 GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
1273 if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
1274
1275 mDNS_SetFQDN(m);
1276
1277 sa.sa_family = AF_INET;
1278 m->p->unicastSocket4 = -1;
1279 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
1280 #if HAVE_IPV6
1281 sa.sa_family = AF_INET6;
1282 m->p->unicastSocket6 = -1;
1283 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
1284 #endif
1285
1286 // Tell mDNS core about the network interfaces on this machine.
1287 if (err == mStatus_NoError) err = SetupInterfaceList(m);
1288
1289 // Tell mDNS core about DNS Servers
1290 mDNS_Lock(m);
1291 if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
1292 mDNS_Unlock(m);
1293
1294 if (err == mStatus_NoError)
1295 {
1296 err = WatchForInterfaceChange(m);
1297 // Failure to observe interface changes is non-fatal.
1298 if (err != mStatus_NoError)
1299 {
1300 fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
1301 err = mStatus_NoError;
1302 }
1303 }
1304
1305 // We don't do asynchronous initialization on the Posix platform, so by the time
1306 // we get here the setup will already have succeeded or failed. If it succeeded,
1307 // we should just call mDNSCoreInitComplete() immediately.
1308 if (err == mStatus_NoError)
1309 mDNSCoreInitComplete(m, mStatus_NoError);
1310
1311 return PosixErrorToStatus(err);
1312 }
1313
1314 // mDNS core calls this routine to clean up the platform-specific data.
1315 // In our case all we need to do is to tear down every network interface.
1316 mDNSexport void mDNSPlatformClose(mDNS *const m)
1317 {
1318 assert(m != NULL);
1319 ClearInterfaceList(m);
1320 if (m->p->unicastSocket4 != -1) assert(close(m->p->unicastSocket4) == 0);
1321 #if HAVE_IPV6
1322 if (m->p->unicastSocket6 != -1) assert(close(m->p->unicastSocket6) == 0);
1323 #endif
1324 }
1325
1326 // This is used internally by InterfaceChangeCallback.
1327 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1328 // can call it in response to a SIGHUP (mainly for debugging purposes).
1329 mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
1330 {
1331 int err;
1332 // This is a pretty heavyweight way to process interface changes --
1333 // destroying the entire interface list and then making fresh one from scratch.
1334 // We should make it like the OS X version, which leaves unchanged interfaces alone.
1335 ClearInterfaceList(m);
1336 err = SetupInterfaceList(m);
1337 return PosixErrorToStatus(err);
1338 }
1339
1340 #if COMPILER_LIKES_PRAGMA_MARK
1341 #pragma mark ***** Locking
1342 #endif
1343
1344 // On the Posix platform, locking is a no-op because we only ever enter
1345 // mDNS core on the main thread.
1346
1347 // mDNS core calls this routine when it wants to prevent
1348 // the platform from reentering mDNS core code.
1349 mDNSexport void mDNSPlatformLock (const mDNS *const m)
1350 {
1351 (void) m; // Unused
1352 }
1353
1354 // mDNS core calls this routine when it release the lock taken by
1355 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1356 mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
1357 {
1358 (void) m; // Unused
1359 }
1360
1361 #if COMPILER_LIKES_PRAGMA_MARK
1362 #pragma mark ***** Strings
1363 #endif
1364
1365 // mDNS core calls this routine to copy C strings.
1366 // On the Posix platform this maps directly to the ANSI C strcpy.
1367 mDNSexport void mDNSPlatformStrCopy(void *dst, const void *src)
1368 {
1369 strcpy((char *)dst, (char *)src);
1370 }
1371
1372 // mDNS core calls this routine to get the length of a C string.
1373 // On the Posix platform this maps directly to the ANSI C strlen.
1374 mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
1375 {
1376 return strlen((char*)src);
1377 }
1378
1379 // mDNS core calls this routine to copy memory.
1380 // On the Posix platform this maps directly to the ANSI C memcpy.
1381 mDNSexport void mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
1382 {
1383 memcpy(dst, src, len);
1384 }
1385
1386 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1387 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1388 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
1389 {
1390 return memcmp(dst, src, len) == 0;
1391 }
1392
1393 // If the caller wants to know the exact return of memcmp, then use this instead
1394 // of mDNSPlatformMemSame
1395 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
1396 {
1397 return (memcmp(dst, src, len));
1398 }
1399
1400 mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
1401 {
1402 return (qsort(base, nel, width, compar));
1403 }
1404
1405 // DNSSEC stub functions
1406 mDNSexport void VerifySignature(mDNS *const m, DNSSECVerifier *dv, DNSQuestion *q)
1407 {
1408 (void)m;
1409 (void)dv;
1410 (void)q;
1411 }
1412
1413 mDNSexport mDNSBool AddNSECSForCacheRecord(mDNS *const m, CacheRecord *crlist, CacheRecord *negcr, mDNSu8 rcode)
1414 {
1415 (void)m;
1416 (void)crlist;
1417 (void)negcr;
1418 (void)rcode;
1419 return mDNSfalse;
1420 }
1421
1422 mDNSexport void BumpDNSSECStats(mDNS *const m, DNSSECStatsAction action, DNSSECStatsType type, mDNSu32 value)
1423 {
1424 (void)m;
1425 (void)action;
1426 (void)type;
1427 (void)value;
1428 }
1429
1430 // Proxy stub functions
1431 mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
1432 {
1433 (void) q;
1434 (void) h;
1435 (void) msg;
1436 (void) ptr;
1437 (void) limit;
1438
1439 return ptr;
1440 }
1441
1442 mDNSexport void DNSProxyInit(mDNS *const m, mDNSu32 IpIfArr[], mDNSu32 OpIf)
1443 {
1444 (void) m;
1445 (void) IpIfArr;
1446 (void) OpIf;
1447 }
1448
1449 mDNSexport void DNSProxyTerminate(mDNS *const m)
1450 {
1451 (void) m;
1452 }
1453
1454 // mDNS core calls this routine to clear blocks of memory.
1455 // On the Posix platform this is a simple wrapper around ANSI C memset.
1456 mDNSexport void mDNSPlatformMemZero(void *dst, mDNSu32 len)
1457 {
1458 memset(dst, 0, len);
1459 }
1460
1461 mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
1462 mDNSexport void mDNSPlatformMemFree (void *mem) { free(mem); }
1463
1464 mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
1465 {
1466 struct timeval tv;
1467 gettimeofday(&tv, NULL);
1468 return(tv.tv_usec);
1469 }
1470
1471 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
1472
1473 mDNSexport mStatus mDNSPlatformTimeInit(void)
1474 {
1475 // No special setup is required on Posix -- we just use gettimeofday();
1476 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1477 // We should find a better way to do this
1478 return(mStatus_NoError);
1479 }
1480
1481 mDNSexport mDNSs32 mDNSPlatformRawTime()
1482 {
1483 struct timeval tv;
1484 gettimeofday(&tv, NULL);
1485 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1486 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1487 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1488 // 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.
1489 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1490 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1491 return((tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625));
1492 }
1493
1494 mDNSexport mDNSs32 mDNSPlatformUTC(void)
1495 {
1496 return time(NULL);
1497 }
1498
1499 mDNSexport void mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
1500 {
1501 (void) m;
1502 (void) InterfaceID;
1503 (void) EthAddr;
1504 (void) IPAddr;
1505 (void) iteration;
1506 }
1507
1508 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(AuthRecord *rr, const NetworkInterfaceInfo *intf)
1509 {
1510 (void) rr;
1511 (void) intf;
1512
1513 return 1;
1514 }
1515
1516 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
1517 {
1518 (void) q;
1519 (void) intf;
1520
1521 return 1;
1522 }
1523
1524 // Used for debugging purposes. For now, just set the buffer to zero
1525 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
1526 {
1527 (void) te;
1528 if (bufsize) buf[0] = 0;
1529 }
1530
1531 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
1532 {
1533 (void) sadd; // Unused
1534 (void) dadd; // Unused
1535 (void) lport; // Unused
1536 (void) rport; // Unused
1537 (void) seq; // Unused
1538 (void) ack; // Unused
1539 (void) win; // Unused
1540 }
1541
1542 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNS *const m, mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
1543 {
1544 (void) m; // Unused
1545 (void) laddr; // Unused
1546 (void) raddr; // Unused
1547 (void) lport; // Unused
1548 (void) rport; // Unused
1549 (void) mti; // Unused
1550
1551 return mStatus_NoError;
1552 }
1553
1554 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNS *const m, mDNSAddr *raddr)
1555 {
1556 (void) raddr; // Unused
1557 (void) m; // Unused
1558
1559 return mStatus_NoError;
1560 }
1561
1562 mDNSexport mStatus mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
1563 {
1564 (void) spsaddr; // Unused
1565 (void) ifname; // Unused
1566
1567 return mStatus_NoError;
1568 }
1569
1570 mDNSexport mStatus mDNSPlatformClearSPSMACAddr(void)
1571 {
1572 return mStatus_NoError;
1573 }
1574
1575 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
1576 {
1577 (void) sock; // unused
1578
1579 return (mDNSu16)-1;
1580 }
1581
1582 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
1583 {
1584 (void) InterfaceID; // unused
1585
1586 return mDNSfalse;
1587 }
1588
1589 mDNSexport mDNSBool mDNSPlatformAllowPID(mDNS *const m, DNSQuestion *q)
1590 {
1591 (void) m;
1592 (void) q;
1593 return mDNStrue;
1594 }
1595
1596 mDNSexport mDNSs32 mDNSPlatformGetServiceID(mDNS *const m, DNSQuestion *q)
1597 {
1598 (void) m;
1599 (void) q;
1600 return -1;
1601 }
1602
1603 mDNSexport void mDNSPlatformSetDelegatePID(UDPSocket *src, const mDNSAddr *dst, DNSQuestion *q)
1604 {
1605 (void) src;
1606 (void) dst;
1607 (void) q;
1608 }
1609
1610 mDNSexport mDNSs32 mDNSPlatformGetPID()
1611 {
1612 return 0;
1613 }
1614
1615 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
1616 {
1617 if (*nfds < s + 1) *nfds = s + 1;
1618 FD_SET(s, readfds);
1619 }
1620
1621 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, struct timeval *timeout)
1622 {
1623 mDNSs32 ticks;
1624 struct timeval interval;
1625
1626 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1627 mDNSs32 nextevent = mDNS_Execute(m);
1628
1629 // 2. Build our list of active file descriptors
1630 PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
1631 if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket4);
1632 #if HAVE_IPV6
1633 if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket6);
1634 #endif
1635 while (info)
1636 {
1637 if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket4);
1638 #if HAVE_IPV6
1639 if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket6);
1640 #endif
1641 info = (PosixNetworkInterface *)(info->coreIntf.next);
1642 }
1643
1644 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1645 ticks = nextevent - mDNS_TimeNow(m);
1646 if (ticks < 1) ticks = 1;
1647 interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
1648 interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1649
1650 // 4. If client's proposed timeout is more than what we want, then reduce it
1651 if (timeout->tv_sec > interval.tv_sec ||
1652 (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
1653 *timeout = interval;
1654 }
1655
1656 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
1657 {
1658 PosixNetworkInterface *info;
1659 assert(m != NULL);
1660 assert(readfds != NULL);
1661 info = (PosixNetworkInterface *)(m->HostInterfaces);
1662
1663 if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
1664 {
1665 FD_CLR(m->p->unicastSocket4, readfds);
1666 SocketDataReady(m, NULL, m->p->unicastSocket4);
1667 }
1668 #if HAVE_IPV6
1669 if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
1670 {
1671 FD_CLR(m->p->unicastSocket6, readfds);
1672 SocketDataReady(m, NULL, m->p->unicastSocket6);
1673 }
1674 #endif
1675
1676 while (info)
1677 {
1678 if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
1679 {
1680 FD_CLR(info->multicastSocket4, readfds);
1681 SocketDataReady(m, info, info->multicastSocket4);
1682 }
1683 #if HAVE_IPV6
1684 if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
1685 {
1686 FD_CLR(info->multicastSocket6, readfds);
1687 SocketDataReady(m, info, info->multicastSocket6);
1688 }
1689 #endif
1690 info = (PosixNetworkInterface *)(info->coreIntf.next);
1691 }
1692 }
1693
1694 // update gMaxFD
1695 mDNSlocal void DetermineMaxEventFD(void)
1696 {
1697 PosixEventSource *iSource;
1698
1699 gMaxFD = 0;
1700 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1701 if (gMaxFD < iSource->fd)
1702 gMaxFD = iSource->fd;
1703 }
1704
1705 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1706 mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
1707 {
1708 PosixEventSource *newSource;
1709
1710 if (gEventSources.LinkOffset == 0)
1711 InitLinkedList(&gEventSources, offsetof(PosixEventSource, Next));
1712
1713 if (fd >= (int) FD_SETSIZE || fd < 0)
1714 return mStatus_UnsupportedErr;
1715 if (callback == NULL)
1716 return mStatus_BadParamErr;
1717
1718 newSource = (PosixEventSource*) malloc(sizeof *newSource);
1719 if (NULL == newSource)
1720 return mStatus_NoMemoryErr;
1721
1722 newSource->Callback = callback;
1723 newSource->Context = context;
1724 newSource->fd = fd;
1725
1726 AddToTail(&gEventSources, newSource);
1727 FD_SET(fd, &gEventFDs);
1728
1729 DetermineMaxEventFD();
1730
1731 return mStatus_NoError;
1732 }
1733
1734 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1735 mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
1736 {
1737 PosixEventSource *iSource;
1738
1739 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1740 {
1741 if (fd == iSource->fd)
1742 {
1743 FD_CLR(fd, &gEventFDs);
1744 RemoveFromList(&gEventSources, iSource);
1745 free(iSource);
1746 DetermineMaxEventFD();
1747 return mStatus_NoError;
1748 }
1749 }
1750 return mStatus_NoSuchNameErr;
1751 }
1752
1753 // Simply note the received signal in gEventSignals.
1754 mDNSlocal void NoteSignal(int signum)
1755 {
1756 sigaddset(&gEventSignals, signum);
1757 }
1758
1759 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1760 mStatus mDNSPosixListenForSignalInEventLoop(int signum)
1761 {
1762 struct sigaction action;
1763 mStatus err;
1764
1765 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
1766 action.sa_handler = NoteSignal;
1767 err = sigaction(signum, &action, (struct sigaction*) NULL);
1768
1769 sigaddset(&gEventSignalSet, signum);
1770
1771 return err;
1772 }
1773
1774 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1775 mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
1776 {
1777 struct sigaction action;
1778 mStatus err;
1779
1780 mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
1781 action.sa_handler = SIG_DFL;
1782 err = sigaction(signum, &action, (struct sigaction*) NULL);
1783
1784 sigdelset(&gEventSignalSet, signum);
1785
1786 return err;
1787 }
1788
1789 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1790 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1791 mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
1792 sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
1793 {
1794 fd_set listenFDs = gEventFDs;
1795 int fdMax = 0, numReady;
1796 struct timeval timeout = *pTimeout;
1797
1798 // Include the sockets that are listening to the wire in our select() set
1799 mDNSPosixGetFDSet(m, &fdMax, &listenFDs, &timeout); // timeout may get modified
1800 if (fdMax < gMaxFD)
1801 fdMax = gMaxFD;
1802
1803 numReady = select(fdMax + 1, &listenFDs, (fd_set*) NULL, (fd_set*) NULL, &timeout);
1804
1805 // If any data appeared, invoke its callback
1806 if (numReady > 0)
1807 {
1808 PosixEventSource *iSource;
1809
1810 (void) mDNSPosixProcessFDSet(m, &listenFDs); // call this first to process wire data for clients
1811
1812 for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1813 {
1814 if (FD_ISSET(iSource->fd, &listenFDs))
1815 {
1816 iSource->Callback(iSource->fd, 0, iSource->Context);
1817 break; // in case callback removed elements from gEventSources
1818 }
1819 }
1820 *pDataDispatched = mDNStrue;
1821 }
1822 else
1823 *pDataDispatched = mDNSfalse;
1824
1825 (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
1826 *pSignalsReceived = gEventSignals;
1827 sigemptyset(&gEventSignals);
1828 (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
1829
1830 return mStatus_NoError;
1831 }