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