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