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