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