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