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