Home | History | Annotate | Line # | Download | only in mDNSPosix
      1 /* -*- Mode: C; tab-width: 4; c-file-style: "bsd"; c-basic-offset: 4; fill-column: 108; indent-tabs-mode: nil; -*-
      2  *
      3  * Copyright (c) 2002-2024 Apple Inc. All rights reserved.
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *     https://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  *
     17  */
     18 
     19 #include "mDNSEmbeddedAPI.h"           // Defines the interface provided to the client layer above
     20 #include "DNSCommon.h"
     21 #include "mDNSPosix.h"               // Defines the specific types needed to run mDNS on this platform
     22 #include "PlatformCommon.h"
     23 #include "dns_sd.h"
     24 
     25 #include <assert.h>
     26 #include <stdio.h>
     27 #include <stdlib.h>
     28 #include <errno.h>
     29 #include <string.h>
     30 #include <unistd.h>
     31 #include <syslog.h>
     32 #include <stdarg.h>
     33 #include <fcntl.h>
     34 #include <sys/types.h>
     35 #include <sys/time.h>
     36 #include <sys/socket.h>
     37 #include <sys/uio.h>
     38 #include <sys/select.h>
     39 #include <netinet/in.h>
     40 #include <arpa/inet.h>
     41 #include <time.h>                   // platform support for UTC time
     42 #include <ifaddrs.h>
     43 
     44 #if USES_NETLINK
     45 #include <asm/types.h>
     46 #include <linux/netlink.h>
     47 #include <linux/rtnetlink.h>
     48 #else // USES_NETLINK
     49 #include <net/route.h>
     50 #include <net/if.h>
     51 #endif // USES_NETLINK
     52 #if defined(TARGET_OS_MAC) && TARGET_OS_MAC
     53 #include <netinet/in_var.h>
     54 #include <net/if_dl.h>
     55 #endif
     56 #if defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
     57 #include <net/if_arp.h>
     58 #include <sys/ioctl.h>
     59 #include <linux/sockios.h>
     60 #endif
     61 
     62 #include "mDNSUNP.h"
     63 #include "GenLinkedList.h"
     64 #include "mdns_strict.h"
     65 
     66 // ***************************************************************************
     67 // Structures
     68 
     69 // Context record for interface change callback
     70 struct IfChangeRec
     71 {
     72     int NotifySD;
     73     mDNS *mDNS;
     74 };
     75 typedef struct IfChangeRec IfChangeRec;
     76 
     77 // Note that static data is initialized to zero in (modern) C.
     78 static PosixEventSource *gEventSources;             // linked list of PosixEventSource's
     79 static sigset_t gEventSignalSet;                // Signals which event loop listens for
     80 static sigset_t gEventSignals;                  // Signals which were received while inside loop
     81 
     82 static PosixNetworkInterface *gRecentInterfaces;
     83 
     84 // ***************************************************************************
     85 // Globals (for debugging)
     86 
     87 static int num_registered_interfaces = 0;
     88 static int num_pkts_accepted = 0;
     89 static int num_pkts_rejected = 0;
     90 
     91 // ***************************************************************************
     92 // Locals
     93 mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
     94                                     const char *taskName, mDNSPosixEventCallback callback, void *context);
     95 mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeSource, mDNSBool removeSource, int flags);
     96 mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
     97                                      const char *taskName, mDNSPosixEventCallback callback, void *context);
     98 mDNSlocal void UDPReadCallback(int fd, void *context);
     99 mDNSlocal int SetupIPv4Socket(int fd);
    100 #if HAVE_IPV6
    101 mDNSlocal int SetupIPv6Socket(int fd);
    102 #endif
    103 
    104 // ***************************************************************************
    105 // Constants
    106 
    107 static const int kOn = 1;
    108 static const int kIntTwoFiveFive = 255;
    109 static const unsigned char kByteTwoFiveFive = 255;
    110 
    111 // ***************************************************************************
    112 // Functions
    113 
    114 #if MDNS_MALLOC_DEBUGGING
    115 mDNSexport void mDNSPlatformValidateLists(void)
    116 {
    117     // This should validate gEventSources and any other Posix-specific stuff that gets allocated.
    118 }
    119 #endif
    120 
    121 int gMDNSPlatformPosixVerboseLevel = 0;
    122 
    123 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
    124 
    125 mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
    126 {
    127     switch (sa->sa_family)
    128     {
    129     case AF_INET:
    130     {
    131         struct sockaddr_in *sin          = (struct sockaddr_in*)sa;
    132         ipAddr->type                     = mDNSAddrType_IPv4;
    133         ipAddr->ip.v4.NotAnInteger       = sin->sin_addr.s_addr;
    134         if (ipPort) ipPort->NotAnInteger = sin->sin_port;
    135         break;
    136     }
    137 
    138 #if HAVE_IPV6
    139     case AF_INET6:
    140     {
    141         struct sockaddr_in6 *sin6        = (struct sockaddr_in6*)sa;
    142 #ifndef NOT_HAVE_SA_LEN
    143         assert(sin6->sin6_len == sizeof(*sin6));
    144 #endif
    145         ipAddr->type                     = mDNSAddrType_IPv6;
    146         ipAddr->ip.v6                    = *(mDNSv6Addr*)&sin6->sin6_addr;
    147         if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
    148         break;
    149     }
    150 #endif
    151 
    152     default:
    153         verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
    154         ipAddr->type = mDNSAddrType_None;
    155         if (ipPort) ipPort->NotAnInteger = 0;
    156         break;
    157     }
    158 }
    159 
    160 #if COMPILER_LIKES_PRAGMA_MARK
    161 #pragma mark ***** Send and Receive
    162 #endif
    163 
    164 // mDNS core calls this routine when it needs to send a packet.
    165 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
    166                                        mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
    167                                        mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
    168 {
    169     int err = 0;
    170     struct sockaddr_storage to;
    171     PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
    172     int sendingsocket = -1;
    173     struct sockaddr *sa = (struct sockaddr *)&to;
    174 
    175     (void) useBackgroundTrafficClass;
    176 
    177     assert(m != NULL);
    178     assert(msg != NULL);
    179     assert(end != NULL);
    180     assert((((char *) end) - ((char *) msg)) > 0);
    181 
    182     if (dstPort.NotAnInteger == 0)
    183     {
    184         LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
    185         return PosixErrorToStatus(EINVAL);
    186     }
    187     if (dst->type == mDNSAddrType_IPv4)
    188     {
    189         struct sockaddr_in *sin = (struct sockaddr_in*)&to;
    190 #ifndef NOT_HAVE_SA_LEN
    191         sin->sin_len            = sizeof(*sin);
    192 #endif
    193         sin->sin_family         = AF_INET;
    194         sin->sin_port           = dstPort.NotAnInteger;
    195         sin->sin_addr.s_addr    = dst->ip.v4.NotAnInteger;
    196         sendingsocket           = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
    197     }
    198 
    199 #if HAVE_IPV6
    200     else if (dst->type == mDNSAddrType_IPv6)
    201     {
    202         struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
    203         mDNSPlatformMemZero(sin6, sizeof(*sin6));
    204 #ifndef NOT_HAVE_SA_LEN
    205         sin6->sin6_len            = sizeof(*sin6);
    206 #endif
    207         sin6->sin6_family         = AF_INET6;
    208         sin6->sin6_port           = dstPort.NotAnInteger;
    209         sin6->sin6_addr           = *(struct in6_addr*)&dst->ip.v6;
    210         sendingsocket             = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
    211     }
    212 #endif
    213     // In case we get some other address family, return an error, since it's not supported.
    214     else
    215     {
    216         return kDNSServiceErr_BadParam;
    217     }
    218 
    219     // We don't open the socket until we get a send, because we don't know whether it's IPv4 or IPv6.
    220     if (src)
    221     {
    222         if (src->events.fd == -1)
    223         {
    224             int sock = socket(sa->sa_family, SOCK_DGRAM, IPPROTO_UDP);
    225             struct sockaddr_storage from;
    226             socklen_t fromlen;
    227             int times = 0;
    228             uint16_t *pport;
    229 
    230             if (sock < 0)
    231             {
    232                 LogMsg("Can't create UDP socket: %s", strerror(errno));
    233                 return PosixErrorToStatus(errno);
    234             }
    235 
    236             // Randomize the port.
    237             if (src->randomizePort)
    238             {
    239                 memset(&from, 0, sizeof from);
    240                 if (sa->sa_family == AF_INET)
    241                 {
    242                     ((struct sockaddr_in *)&from)->sin_family = AF_INET;
    243                     fromlen = sizeof (struct sockaddr_in);
    244                     pport = &((struct sockaddr_in *)&from)->sin_port;
    245                     err = SetupIPv4Socket(sock);
    246                     if (err) { return err; }
    247                 }
    248 #if HAVE_IPV6
    249                 else
    250                 {
    251                     ((struct sockaddr_in6 *)&from)->sin6_family = AF_INET6;
    252                     fromlen = sizeof (struct sockaddr_in6);
    253                     pport = &((struct sockaddr_in6 *)&from)->sin6_port;
    254                     err = SetupIPv6Socket(sock);
    255                     if (err) { return err; }
    256                 }
    257 #endif
    258 #ifndef NOT_HAVE_SA_LEN
    259                 ((struct sockaddr *)&from)->sa_len = fromlen;
    260 #endif
    261 
    262                 while (times++ < 1000)
    263                 {
    264                     *pport = 0xC000 + mDNSRandom(0x3FFF);
    265                     if (bind(sock, (struct sockaddr *)&from, fromlen) >= 0)
    266                     {
    267                         src->port.NotAnInteger = *pport;
    268                         src->events.fd = sock;
    269                         break;
    270                     }
    271                     if (errno != EADDRINUSE)
    272                     {
    273                         LogMsg("Can't get randomized port: %s", strerror(errno));
    274                         return PosixErrorToStatus(errno);
    275                     }
    276                 }
    277                 if (src->events.fd == -1)
    278                 {
    279                     LogMsg("Unable to get random port: too many tries.");
    280                     return PosixErrorToStatus(EADDRINUSE);
    281                 }
    282                 requestReadEvents(&src->events, "mDNSPosix::UDPReadCallback", UDPReadCallback, src);
    283             }
    284         }
    285         sendingsocket = src->events.fd;
    286     }
    287 
    288     if (sendingsocket >= 0)
    289         err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
    290 
    291     if      (err > 0) err = 0;
    292     else if (err < 0)
    293     {
    294         static int MessageCount = 0;
    295         // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
    296         if (!mDNSAddressIsAllDNSLinkGroup(dst)) {
    297             if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
    298 	} else if (errno == EADDRNOTAVAIL) return(mStatus_TransientErr);
    299 
    300         if (MessageCount < 1000)
    301         {
    302             MessageCount++;
    303             if (thisIntf)
    304                 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
    305                        errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
    306             else
    307                 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
    308         }
    309     }
    310 
    311     return PosixErrorToStatus(err);
    312 }
    313 
    314 mDNSlocal void TCPReadCallback(int fd, void *context)
    315 {
    316     TCPSocket *sock = context;
    317     (void)fd;
    318 
    319     // TLS reading is handled in mDNSPlatformTCPRead().
    320         sock->callback(sock, sock->context, mDNSfalse, sock->err);
    321 }
    322 
    323 mDNSlocal void tcpConnectCallback(int fd, void *context)
    324 {
    325     TCPSocket *sock = context;
    326     mDNSBool c = !sock->connected;
    327     int result;
    328     socklen_t len = sizeof result;
    329 
    330     sock->connected = mDNStrue;
    331 
    332     if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &len) < 0)
    333     {
    334         LogInfo("ERROR: TCPConnectCallback - unable to get connect error: socket %d: Error %d (%s)",
    335                sock->events.fd, result, strerror(result));
    336         sock->err = mStatus_ConnFailed;
    337     }
    338     else
    339     {
    340         if (result != 0)
    341         {
    342             sock->err = mStatus_ConnFailed;
    343             if (result == EHOSTUNREACH || result == EADDRNOTAVAIL || result == ENETDOWN)
    344             {
    345                 LogInfo("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
    346                         sock->events.fd, result, strerror(result));
    347             }
    348             else
    349             {
    350                 LogMsg("ERROR: TCPConnectCallback - connect failed: socket %d: Error %d (%s)",
    351                        sock->events.fd, result, strerror(result));
    352             }
    353         }
    354         else
    355         {
    356             if (sock->flags & kTCPSocketFlags_UseTLS) {
    357 #ifdef POSIX_HAS_TLS
    358                 sock->tls = mDNSPosixTLSClientStateCreate(sock);
    359                 if (sock->tls == mDNSNULL) {
    360                     LogMsg("ERROR: TCPConnectCallback: TLS context state create failed");
    361                     sock->err = mStatus_NoMemoryErr;
    362                 } else {
    363                     if (!mDNSPosixTLSStart(sock)) {
    364                         LogMsg("ERROR: TCPConnectCallback: TLS start failed");
    365                         sock->err = mStatus_ConnFailed;
    366                     }
    367                 }
    368 #else
    369                 // We shouldn't ever get here, because we should have already gotten an error when we created the
    370                 // socket.
    371                 LogMsg("Error: TCPSocketConnectCallback reached on TLS socket with no TLS support.");
    372                 sock->err = mStatus_ConnFailed;
    373 #endif
    374             }
    375             if (sock->err == 0) {
    376             // The connection succeeded.
    377             sock->connected = mDNStrue;
    378             // Select for read events.
    379             sock->events.fd = fd;
    380             requestReadEvents(&sock->events, "mDNSPosix::tcpConnectCallback", TCPReadCallback, sock);
    381         }
    382     }
    383     }
    384 
    385     if (sock->callback)
    386     {
    387         sock->callback(sock, sock->context, c, sock->err);
    388         // Here sock must be assumed to be invalid, in case the callback freed it.
    389         return;
    390     }
    391 }
    392 
    393 // Searches the interface list looking for the named interface.
    394 // Returns a pointer to if it found, or NULL otherwise.
    395 mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *const intfName)
    396 {
    397     PosixNetworkInterface *intf;
    398 
    399     assert(m != NULL);
    400     assert(intfName != NULL);
    401 
    402     intf = (PosixNetworkInterface*)(m->HostInterfaces);
    403     while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
    404         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
    405 
    406     return intf;
    407 }
    408 
    409 mDNSlocal PosixNetworkInterface *SearchForInterfaceByIndex(mDNS *const m, const mDNSu32 index)
    410 {
    411     PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
    412     while (intf && (((mDNSu32)intf->index) != index))
    413     {
    414         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
    415     }
    416     return intf;
    417 }
    418 
    419 // This routine is called when the main loop detects that data is available on a socket.
    420 mDNSlocal void SocketDataReady(mDNS *const m, const PosixNetworkInterface *intf, const int skt, UDPSocket *const sock)
    421 {
    422     mDNSAddr senderAddr, destAddr;
    423     mDNSIPPort senderPort, destPort;
    424     ssize_t packetLen;
    425     DNSMessage packet;
    426     struct my_in_pktinfo packetInfo;
    427     struct sockaddr_storage from;
    428     socklen_t fromLen;
    429     int flags;
    430     mDNSu8 ttl;
    431     mDNSBool reject;
    432 
    433     assert(m    != NULL);
    434     assert(skt  >= 0);
    435 
    436     fromLen = sizeof(from);
    437     flags   = 0;
    438     packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
    439 
    440     if (packetLen >= 0)
    441     {
    442         SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
    443         SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, &destPort);
    444 
    445         // If we have broken IP_RECVDSTADDR functionality (so far
    446         // I've only seen this on OpenBSD) then apply a hack to
    447         // convince mDNS Core that this isn't a spoof packet.
    448         // Basically what we do is check to see whether the
    449         // packet arrived as a multicast and, if so, set its
    450         // destAddr to the mDNS address.
    451         //
    452         // I must admit that I could just be doing something
    453         // wrong on OpenBSD and hence triggering this problem
    454         // but I'm at a loss as to how.
    455         //
    456         // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
    457         // no way to tell the destination address or interface this packet arrived on,
    458         // so all we can do is just assume it's a multicast
    459 
    460         #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
    461         if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
    462         {
    463             destAddr.type = senderAddr.type;
    464             if      (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
    465             else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
    466         }
    467         #endif
    468 
    469         // We only accept the packet if the interface on which it came
    470         // in matches the interface associated with this socket.
    471         // We do this match by name or by index, depending on which
    472         // information is available.  recvfrom_flags sets the name
    473         // to "" if the name isn't available, or the index to -1
    474         // if the index is available.  This accomodates the various
    475         // different capabilities of our target platforms.
    476 
    477         reject = mDNSfalse;
    478         if (!intf)
    479         {
    480             // Ignore multicasts accidentally delivered to our unicast receiving socket
    481             if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
    482         }
    483         else
    484         {
    485             if      (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
    486             else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
    487 
    488             // In case a unicast packet was received on an unexpected socket, i.e., a socket associated with an
    489             // interface that doesn't match the interface on which the unicast packet was actually received, then
    490             // instead of immediately rejecting it, pass the message to mDNSCoreReceive() with the actual interface ID
    491             // instead of the ID of the interface with which the socket is associated.
    492             if (reject && !mDNSAddrIsDNSMulticast(&destAddr))
    493             {
    494                 const PosixNetworkInterface *realIntf = mDNSNULL;
    495                 if (packetInfo.ipi_ifname[0] != '\0')
    496                 {
    497                     realIntf = SearchForInterfaceByName(m, packetInfo.ipi_ifname);
    498                 }
    499                 else if (packetInfo.ipi_ifindex != -1)
    500                 {
    501                     realIntf = SearchForInterfaceByIndex(m, (mDNSu32)packetInfo.ipi_ifindex);
    502                 }
    503                 if (realIntf)
    504                 {
    505                     debugf("SocketDataReady correcting receive interface from %s/%u to %s/%u",
    506                         intf->intfName, intf->index, realIntf->intfName, realIntf->index);
    507                     intf = realIntf;
    508                     reject = mDNSfalse;
    509                 }
    510             }
    511             if (reject)
    512             {
    513                 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
    514                               &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
    515                               &intf->coreIntf.ip, intf->intfName, intf->index, skt);
    516                 packetLen = -1;
    517                 num_pkts_rejected++;
    518                 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
    519                 {
    520                     fprintf(stderr,
    521                             "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
    522                             num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
    523                     num_pkts_accepted = 0;
    524                     num_pkts_rejected = 0;
    525                 }
    526             }
    527             else
    528             {
    529                 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
    530                               &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
    531                 num_pkts_accepted++;
    532             }
    533         }
    534     }
    535 
    536     if (packetLen >= 0)
    537     {
    538         const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
    539         mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
    540                         &senderAddr, senderPort, &destAddr, sock == mDNSNULL ? MulticastDNSPort : sock->port, InterfaceID);
    541     }
    542 }
    543 
    544 mDNSlocal void UDPReadCallback(int fd, void *context)
    545 {
    546     extern mDNS mDNSStorage;
    547     SocketDataReady(&mDNSStorage, NULL, fd, (UDPSocket *)context);
    548 }
    549 
    550 mDNSexport TCPSocket *mDNSPlatformTCPSocket(TCPSocketFlags flags, mDNSAddr_Type addrType, mDNSIPPort * port,
    551                                             domainname *hostname, mDNSBool useBackgroundTrafficClass)
    552 {
    553     TCPSocket *sock;
    554     int len = sizeof (TCPSocket);
    555 
    556     (void)useBackgroundTrafficClass;
    557 
    558     if (hostname)
    559     {
    560         len += sizeof (domainname);
    561     }
    562     sock = mdns_malloc(len);
    563 
    564     if (sock == NULL)
    565     {
    566         LogMsg("mDNSPlatformTCPSocket: no memory for socket");
    567         return NULL;
    568     }
    569     memset(sock, 0, sizeof *sock);
    570 
    571     if (hostname)
    572     {
    573         sock->hostname = (domainname *)(sock + 1);
    574         LogMsg("mDNSPlatformTCPSocket: hostname %##s", hostname->c);
    575         AssignDomainName(sock->hostname, hostname);
    576     }
    577 
    578     sock->events.fd = -1;
    579     if (!mDNSPosixTCPSocketSetup(&sock->events.fd, addrType, port, &sock->port))
    580     {
    581         if (sock->events.fd != -1) close(sock->events.fd);
    582         mdns_free(sock);
    583         return mDNSNULL;
    584     }
    585 
    586     // Set up the other fields in the structure.
    587     sock->flags = flags;
    588     sock->err = mStatus_NoError;
    589     sock->setup = mDNSfalse;
    590     sock->connected = mDNSfalse;
    591     return sock;
    592 }
    593 
    594 mDNSexport mStatus mDNSPlatformTCPSocketSetCallback(TCPSocket *sock, TCPConnectionCallback callback, void *context)
    595 {
    596     sock->callback = callback;
    597     sock->context = context;
    598     return mStatus_NoError;
    599 }
    600 
    601 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int fd)
    602 {
    603     TCPSocket *sock;
    604 
    605     // In order to receive a TLS connection, use mDNSPlatformTCPListen().
    606     if (flags & kTCPSocketFlags_UseTLS)
    607     {
    608         return mDNSNULL;
    609     }
    610 
    611     sock = mDNSPlatformMemAllocateClear(sizeof(*sock));
    612     if (!sock)
    613     {
    614         return mDNSNULL;
    615     }
    616 
    617     sock->events.fd = fd;
    618     sock->flags = flags;
    619     sock->connected = mDNStrue;
    620 
    621     return sock;
    622 }
    623 
    624 
    625 mDNSlocal void tcpListenCallback(int fd, void *context)
    626 {
    627     TCPListener *listener = context;
    628     TCPSocket *sock;
    629 
    630     sock = mDNSPosixDoTCPListenCallback(fd, listener->addressType, listener->socketFlags,
    631                                  listener->callback, listener->context);
    632     if (sock != NULL)
    633     {
    634         requestReadEvents(&sock->events, "mDNSPosix::tcpListenCallback", TCPReadCallback, sock);
    635     }
    636 }
    637 
    638 mDNSexport TCPListener *mDNSPlatformTCPListen(mDNSAddr_Type addrType, mDNSIPPort *port, mDNSAddr *addr,
    639                                               TCPSocketFlags socketFlags, mDNSBool reuseAddr, int queueLength,
    640                                               TCPAcceptedCallback callback, void *context)
    641 {
    642     TCPListener *ret;
    643     int fd = -1;
    644 
    645     if (!mDNSPosixTCPListen(&fd, addrType, port, addr, reuseAddr, queueLength))
    646     {
    647         if (fd != -1)
    648         {
    649             close(fd);
    650         }
    651         return mDNSNULL;
    652     }
    653 
    654     // Allocate a listener structure
    655     ret = (TCPListener *)mDNSPlatformMemAllocateClear(sizeof *ret);
    656     if (ret == NULL)
    657     {
    658         LogMsg("mDNSPlatformTCPListen: no memory for TCPListener struct.");
    659         close(fd);
    660         return mDNSNULL;
    661     }
    662     ret->events.fd = fd;
    663     ret->callback = callback;
    664     ret->context = context;
    665     ret->addressType = addrType;
    666     ret->socketFlags = socketFlags;
    667 
    668     // When we get a connection, mDNSPosixListenCallback will be called, and it will invoke the
    669     // callback we were passed.
    670     requestReadEvents(&ret->events, "tcpListenCallback", tcpListenCallback, ret);
    671     return ret;
    672 }
    673 
    674 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
    675 {
    676     return sock->events.fd;
    677 }
    678 
    679 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport,
    680                                           mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context)
    681 {
    682     int result;
    683     union {
    684         struct sockaddr sa;
    685         struct sockaddr_in sin;
    686         struct sockaddr_in6 sin6;
    687     } addr;
    688     socklen_t len;
    689 
    690     sock->callback = callback;
    691     sock->context = context;
    692     sock->setup = mDNSfalse;
    693     sock->connected = mDNSfalse;
    694     sock->err = mStatus_NoError;
    695 
    696     result = fcntl(sock->events.fd, F_GETFL, 0);
    697     if (result < 0)
    698     {
    699         LogMsg("mDNSPlatformTCPConnect: F_GETFL failed: %s", strerror(errno));
    700         return mStatus_UnknownErr;
    701     }
    702 
    703     result = fcntl(sock->events.fd, F_SETFL, result | O_NONBLOCK);
    704     if (result < 0)
    705     {
    706         LogMsg("mDNSPlatformTCPConnect: F_SETFL failed: %s", strerror(errno));
    707         return mStatus_UnknownErr;
    708     }
    709 
    710     // If we've been asked to bind to a single interface, do it.  See comment in mDNSMacOSX.c for more info.
    711     if (InterfaceID)
    712     {
    713         PosixNetworkInterface *iface = (PosixNetworkInterface *)InterfaceID;
    714 #if defined(SO_BINDTODEVICE)
    715         result = setsockopt(sock->events.fd,
    716                             SOL_SOCKET, SO_BINDTODEVICE, iface->intfName, strlen(iface->intfName));
    717         if (result < 0)
    718         {
    719             LogMsg("mDNSPlatformTCPConnect: SO_BINDTODEVICE failed on %s: %s", iface->intfName, strerror(errno));
    720             return mStatus_BadParamErr;
    721         }
    722 #else
    723         if (dst->type == mDNSAddrType_IPv4)
    724         {
    725 #if defined(IP_BOUND_IF)
    726             result = setsockopt(sock->events.fd, IPPROTO_IP, IP_BOUND_IF, &iface->index, sizeof iface->index);
    727             if (result < 0)
    728             {
    729                 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
    730                        iface->intfName, iface->index, strerror(errno));
    731                 return mStatus_BadParamErr;
    732             }
    733 #else
    734             (void)iface;
    735 #endif // IP_BOUND_IF
    736         }
    737         else
    738         { // IPv6
    739 #if defined(IPV6_BOUND_IF)
    740             result = setsockopt(sock->events.fd, IPPROTO_IPV6, IPV6_BOUND_IF, &iface->index, sizeof iface->index);
    741             if (result < 0)
    742             {
    743                 LogMsg("mDNSPlatformTCPConnect: IP_BOUND_IF failed on %s (%d): %s",
    744                        iface->intfName, iface->index, strerror(errno));
    745                 return mStatus_BadParamErr;
    746             }
    747 #else
    748             (void)iface;
    749 #endif // IPV6_BOUND_IF
    750         }
    751 #endif // SO_BINDTODEVICE
    752     }
    753 
    754     memset(&addr, 0, sizeof addr);
    755     if (dst->type == mDNSAddrType_IPv4)
    756     {
    757         addr.sa.sa_family = AF_INET;
    758         addr.sin.sin_port = dstport.NotAnInteger;
    759         len = sizeof (struct sockaddr_in);
    760         addr.sin.sin_addr.s_addr = dst->ip.v4.NotAnInteger;
    761     }
    762     else
    763     {
    764         addr.sa.sa_family = AF_INET6;
    765         len = sizeof (struct sockaddr_in6);
    766         addr.sin6.sin6_port = dstport.NotAnInteger;
    767         memcpy(&addr.sin6.sin6_addr.s6_addr, &dst->ip.v6, sizeof addr.sin6.sin6_addr.s6_addr);
    768     }
    769 #ifndef NOT_HAVE_SA_LEN
    770     addr.sa.sa_len = len;
    771 #endif
    772 
    773     result = connect(sock->events.fd, (struct sockaddr *)&addr, len);
    774     if (result < 0)
    775     {
    776         if (errno == EINPROGRESS)
    777         {
    778             requestWriteEvents(&sock->events, "mDNSPlatformConnect", tcpConnectCallback, sock);
    779             return mStatus_ConnPending;
    780         }
    781         if (errno == EHOSTUNREACH || errno == EADDRNOTAVAIL || errno == ENETDOWN)
    782         {
    783             LogInfo("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s)",
    784                     sock->events.fd, errno, strerror(errno));
    785         }
    786         else
    787         {
    788             LogMsg("ERROR: mDNSPlatformTCPConnect - connect failed: socket %d: Error %d (%s) length %d",
    789                    sock->events.fd, errno, strerror(errno), len);
    790         }
    791         return mStatus_ConnFailed;
    792     }
    793 
    794     LogMsg("NOTE: mDNSPlatformTCPConnect completed synchronously");
    795     return mStatus_NoError;
    796 }
    797 
    798 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
    799 {
    800     if (sock)
    801     { // can sock really be NULL when this is called?
    802         shutdown(sock->events.fd, SHUT_RDWR);
    803         stopReadOrWriteEvents(sock->events.fd, mDNSfalse, mDNStrue,
    804                               PosixEventFlag_Read | PosixEventFlag_Write);
    805         close(sock->events.fd);
    806         mdns_free(sock);
    807     }
    808 }
    809 
    810 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool *closed)
    811 {
    812     ssize_t nread;
    813 
    814     *closed = mDNSfalse;
    815     if (sock->flags & kTCPSocketFlags_UseTLS)
    816     {
    817 #ifdef POSIX_HAS_TLS
    818         nread = mDNSPosixTLSRead(sock, buf, buflen, closed);
    819 #else
    820         nread = mStatus_ConnFailed;
    821         *closed = mDNStrue;
    822 #endif
    823     } else {
    824         nread = mDNSPosixReadTCP(sock->events.fd, buf, buflen, closed);
    825     }
    826     return nread;
    827 }
    828 
    829 mDNSexport mDNSBool mDNSPlatformTCPWritable(TCPSocket *sock)
    830 {
    831     fd_set w;
    832     int nfds = sock->events.fd + 1;
    833     int count;
    834     struct timeval tv;
    835 
    836     if (nfds > FD_SETSIZE)
    837     {
    838         LogMsg("ERROR: mDNSPlatformTCPWritable called on an fd that won't fit in an fd_set.");
    839         return mDNStrue; // hope for the best?
    840     }
    841     FD_SET(sock->events.fd, &w);
    842     tv.tv_sec = tv.tv_usec = 0;
    843     count = select(nfds, NULL, &w, NULL, &tv);
    844     if (count > 0)
    845     {
    846         return mDNStrue;
    847     }
    848     return mDNSfalse;
    849 }
    850 
    851 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
    852 {
    853     if (sock->flags & kTCPSocketFlags_UseTLS)
    854     {
    855 #ifdef POSIX_HAS_TLS
    856         return mDNSPosixTLSWrite(sock, msg, len);
    857 #else
    858         return mStatus_ConnFailed;
    859 #endif
    860     }
    861     else
    862     {
    863         return mDNSPosixWriteTCP(sock->events.fd, msg, len);
    864     }
    865 }
    866 
    867 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNSIPPort port)
    868 {
    869     mDNSBool randomizePort = mDNSIPPortIsZero(port);
    870     UDPSocket *p = callocL("UDPSocket", sizeof(UDPSocket));
    871     if (!p) { LogMsg("mDNSPlatformUDPSocket: memory exhausted"); return(mDNSNULL); }
    872     p->randomizePort = randomizePort;
    873     p->port = port;
    874     p->events.fd = -1;
    875     return(p);
    876 }
    877 
    878 mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
    879 {
    880     if (sock && sock->events.fd != -1)
    881     {
    882         stopReadOrWriteEvents(sock->events.fd, mDNSfalse, mDNStrue,
    883                               PosixEventFlag_Read | PosixEventFlag_Write);
    884         close(sock->events.fd);
    885         mdns_free(sock);
    886     }
    887 }
    888 
    889 mDNSexport void mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID)
    890 {
    891     (void)InterfaceID;          // Unused
    892 }
    893 
    894 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
    895 {
    896     (void)msg;          // Unused
    897     (void)end;          // Unused
    898     (void)InterfaceID;          // Unused
    899 }
    900 
    901 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
    902 {
    903     (void)tpa;          // Unused
    904     (void)tha;          // Unused
    905     (void)InterfaceID;          // Unused
    906 }
    907 
    908 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
    909 {
    910     return(mStatus_UnsupportedErr);
    911 }
    912 
    913 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
    914 {
    915 }
    916 
    917 mDNSexport void mDNSPlatformSetAllowSleep(mDNSBool allowSleep, const char *reason)
    918 {
    919     (void) allowSleep;
    920     (void) reason;
    921 }
    922 
    923 #if COMPILER_LIKES_PRAGMA_MARK
    924 #pragma mark -
    925 #pragma mark - /etc/hosts support
    926 #endif
    927 
    928 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
    929 {
    930     (void)m;  // unused
    931     (void)rr;
    932     (void)result;
    933 }
    934 
    935 
    936 #if COMPILER_LIKES_PRAGMA_MARK
    937 #pragma mark ***** DDNS Config Platform Functions
    938 #endif
    939 
    940 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
    941     DNameListElem **BrowseDomains, mDNSBool ackConfig)
    942 {
    943     (void) setservers;
    944     (void) setsearch;
    945     (void) ackConfig;
    946 
    947     if (fqdn         ) fqdn->c[0]      = 0;
    948     if (RegDomains   ) *RegDomains     = NULL;
    949     if (BrowseDomains) *BrowseDomains  = NULL;
    950 
    951     return mDNStrue;
    952 }
    953 
    954 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
    955 {
    956     (void) v4;
    957     (void) v6;
    958     (void) router;
    959 
    960     return mStatus_UnsupportedErr;
    961 }
    962 
    963 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
    964 {
    965     (void) dname;
    966     (void) status;
    967 }
    968 
    969 #if COMPILER_LIKES_PRAGMA_MARK
    970 #pragma mark ***** Init and Term
    971 #endif
    972 
    973 // This gets the current hostname, truncating it at the first dot if necessary
    974 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
    975 {
    976     int len = 0;
    977     gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
    978     while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
    979     namelabel->c[0] = len;
    980 }
    981 
    982 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
    983 // Other platforms can either get the information from the appropriate place,
    984 // or they can alternatively just require all registering services to provide an explicit name
    985 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
    986 {
    987     // On Unix we have no better name than the host name, so we just use that.
    988     GetUserSpecifiedRFC1034ComputerName(namelabel);
    989 }
    990 
    991 mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
    992 {
    993     char line[256];
    994     char nameserver[16];
    995     char keyword[11];
    996     int numOfServers = 0;
    997     FILE *fp = fopen(filePath, "r");
    998     if (fp == NULL) return -1;
    999     while (fgets(line,sizeof(line),fp))
   1000     {
   1001         struct in_addr ina;
   1002 	struct in6_addr ina6;
   1003         line[255]='\0';     // just to be safe
   1004         if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue;   // it will skip whitespaces
   1005         if (strncasecmp(keyword,"nameserver",10)) continue;
   1006         if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
   1007         {
   1008             mDNSAddr DNSAddr;
   1009             DNSAddr.type = mDNSAddrType_IPv4;
   1010             DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
   1011             mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, mDNSfalse, mDNSfalse, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
   1012             numOfServers++;
   1013         }
   1014     }
   1015     fclose(fp);
   1016     return (numOfServers > 0) ? 0 : -1;
   1017 }
   1018 
   1019 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
   1020 {
   1021     PosixNetworkInterface *intf;
   1022 
   1023     assert(m != NULL);
   1024 
   1025     if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
   1026     if (index == kDNSServiceInterfaceIndexP2P      ) return(mDNSInterface_P2P);
   1027     if (index == kDNSServiceInterfaceIndexAny      ) return(mDNSInterface_Any);
   1028 
   1029     intf = (PosixNetworkInterface*)SearchForInterfaceByIndex(m, index);
   1030     return (mDNSInterfaceID) intf;
   1031 }
   1032 
   1033 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
   1034 {
   1035     PosixNetworkInterface *intf;
   1036     (void) suppressNetworkChange; // Unused
   1037 
   1038     assert(m != NULL);
   1039 
   1040     if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
   1041     if (id == mDNSInterface_P2P      ) return(kDNSServiceInterfaceIndexP2P);
   1042     if (id == mDNSInterface_Any      ) return(kDNSServiceInterfaceIndexAny);
   1043 
   1044     intf = (PosixNetworkInterface*)(m->HostInterfaces);
   1045     while ((intf != NULL) && (mDNSInterfaceID) intf != id)
   1046         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
   1047 
   1048     if (intf) return intf->index;
   1049 
   1050     // If we didn't find the interface, check the RecentInterfaces list as well
   1051     intf = gRecentInterfaces;
   1052     while ((intf != NULL) && (mDNSInterfaceID) intf != id)
   1053         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
   1054 
   1055     return intf ? intf->index : 0;
   1056 }
   1057 
   1058 // Frees the specified PosixNetworkInterface structure. The underlying
   1059 // interface must have already been deregistered with the mDNS core.
   1060 mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
   1061 {
   1062     int rv;
   1063     assert(intf != NULL);
   1064     if (intf->intfName != NULL) mdns_free(intf->intfName);
   1065     if (intf->multicastSocket4 != -1)
   1066     {
   1067         rv = close(intf->multicastSocket4);
   1068         assert(rv == 0);
   1069     }
   1070 #if HAVE_IPV6
   1071     if (intf->multicastSocket6 != -1)
   1072     {
   1073         rv = close(intf->multicastSocket6);
   1074         assert(rv == 0);
   1075     }
   1076 #endif
   1077 
   1078     // Move interface to the RecentInterfaces list for a minute
   1079     intf->LastSeen = mDNSPlatformUTC();
   1080     intf->coreIntf.next = &gRecentInterfaces->coreIntf;
   1081     gRecentInterfaces = intf;
   1082 }
   1083 
   1084 // Grab the first interface, deregister it, free it, and repeat until done.
   1085 mDNSlocal void ClearInterfaceList(mDNS *const m)
   1086 {
   1087     assert(m != NULL);
   1088 
   1089     while (m->HostInterfaces)
   1090     {
   1091         PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
   1092         mDNS_DeregisterInterface(m, &intf->coreIntf, NormalActivation);
   1093         if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
   1094         FreePosixNetworkInterface(intf);
   1095     }
   1096     num_registered_interfaces = 0;
   1097     num_pkts_accepted = 0;
   1098     num_pkts_rejected = 0;
   1099 }
   1100 
   1101 #if HAVE_IPV6
   1102 mDNSlocal int SetupIPv6Socket(int fd)
   1103 {
   1104     int err;
   1105 
   1106     #if defined(IPV6_PKTINFO)
   1107     err = setsockopt(fd, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
   1108     if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
   1109     #else
   1110         #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
   1111     #endif
   1112     return err;
   1113 }
   1114 #endif
   1115 
   1116 mDNSlocal int SetupIPv4Socket(int fd)
   1117 {
   1118     int err;
   1119 
   1120 #if defined(IP_PKTINFO)                                 // Linux
   1121     err = setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
   1122     if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
   1123 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF)     // BSD and Solaris
   1124 #if defined(IP_RECVDSTADDR)
   1125     err = setsockopt(fd, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
   1126     if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
   1127 #endif
   1128 #if defined(IP_RECVIF)
   1129     if (err == 0)
   1130     {
   1131         err = setsockopt(fd, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
   1132         if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
   1133     }
   1134 #endif
   1135 #else
   1136 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
   1137 #endif
   1138     return err;
   1139 }
   1140 
   1141 // Sets up a send/receive socket.
   1142 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
   1143 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
   1144 mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
   1145 {
   1146     int err = 0;
   1147     const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
   1148 
   1149     (void) interfaceIndex;  // This parameter unused on plaforms that don't have IPv6
   1150     assert(intfAddr != NULL);
   1151     assert(sktPtr != NULL);
   1152     assert(*sktPtr == -1);
   1153 
   1154     // Open the socket...
   1155     if      (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET,  SOCK_DGRAM, IPPROTO_UDP);
   1156 #if HAVE_IPV6
   1157     else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
   1158 #endif
   1159     else return EINVAL;
   1160 
   1161     if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
   1162 
   1163     // ... with a shared UDP port, if it's for multicast receiving
   1164     if (err == 0 && port.NotAnInteger)
   1165     {
   1166         // <rdar://problem/20946253> Suggestions from Jonny Trnbom at Axis Communications
   1167         // We test for SO_REUSEADDR first, as suggested by Jonny Trnbom from Axis Communications
   1168         // Linux kernel versions 3.9 introduces support for socket option
   1169         // SO_REUSEPORT, however this is not implemented the same as on *BSD
   1170         // systems. Linux version implements a "port hijacking" prevention
   1171         // mechanism, limiting processes wanting to bind to an already existing
   1172         // addr:port to have the same effective UID as the first who bound it. What
   1173         // this meant for us was that the daemon ran as one user and when for
   1174         // instance mDNSClientPosix was executed by another user, it wasn't allowed
   1175         // to bind to the socket. Our suggestion was to switch the order in which
   1176         // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
   1177         // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
   1178         #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && !defined(__NetBSD__)
   1179         err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
   1180         #elif defined(SO_REUSEPORT)
   1181         err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
   1182         #else
   1183             #error This platform has no way to avoid address busy errors on multicast.
   1184         #endif
   1185         if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
   1186 
   1187 #if TARGET_OS_MAC
   1188         // Enable inbound packets on IFEF_AWDL interface.
   1189         // Only done for multicast sockets, since we don't expect unicast socket operations
   1190         // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
   1191         #ifndef SO_RECV_ANYIF
   1192         #define SO_RECV_ANYIF   0x1104      /* unrestricted inbound processing */
   1193         #endif
   1194         if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
   1195 #endif
   1196     }
   1197 
   1198     // We want to receive destination addresses and interface identifiers.
   1199     if (intfAddr->sa_family == AF_INET)
   1200     {
   1201         struct ip_mreq imr;
   1202         struct sockaddr_in bindAddr;
   1203         if (err == 0)
   1204         {
   1205             err = SetupIPv4Socket(*sktPtr);
   1206         }
   1207     #if defined(IP_RECVTTL)                                 // Linux
   1208         if (err == 0)
   1209         {
   1210             setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
   1211             // We no longer depend on being able to get the received TTL, so don't worry if the option fails
   1212         }
   1213     #endif
   1214 
   1215         // Add multicast group membership on this interface
   1216         if (err == 0 && JoinMulticastGroup)
   1217         {
   1218             imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
   1219             imr.imr_interface        = ((struct sockaddr_in*)intfAddr)->sin_addr;
   1220             err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
   1221             if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
   1222         }
   1223 
   1224         // Specify outgoing interface too
   1225         if (err == 0 && JoinMulticastGroup)
   1226         {
   1227             err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
   1228             if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
   1229         }
   1230 
   1231         // Per the mDNS spec, send unicast packets with TTL 255
   1232         if (err == 0)
   1233         {
   1234             err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
   1235             if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
   1236         }
   1237 
   1238         // and multicast packets with TTL 255 too
   1239         // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
   1240         if (err == 0)
   1241         {
   1242             err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
   1243             if (err < 0 && errno == EINVAL)
   1244                 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
   1245             if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
   1246         }
   1247 
   1248         // And start listening for packets
   1249         if (err == 0)
   1250         {
   1251 	    mDNSPlatformMemZero(&bindAddr, sizeof(bindAddr));
   1252 #ifndef NOT_HAVE_SA_LEN
   1253 	    bindAddr.sin_len         = sizeof(bindAddr);
   1254 #endif
   1255             bindAddr.sin_family      = AF_INET;
   1256             bindAddr.sin_port        = port.NotAnInteger;
   1257             bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
   1258             err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
   1259             if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
   1260         }
   1261     }     // endif (intfAddr->sa_family == AF_INET)
   1262 
   1263 #if HAVE_IPV6
   1264     else if (intfAddr->sa_family == AF_INET6)
   1265     {
   1266         struct ipv6_mreq imr6;
   1267         struct sockaddr_in6 bindAddr6;
   1268         if (err == 0) {
   1269             err = SetupIPv6Socket(*sktPtr);
   1270         }
   1271     #if defined(IPV6_HOPLIMIT)
   1272         if (err == 0)
   1273         {
   1274             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
   1275             if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
   1276         }
   1277     #endif
   1278 
   1279         // Add multicast group membership on this interface
   1280         if (err == 0 && JoinMulticastGroup)
   1281         {
   1282             imr6.ipv6mr_multiaddr       = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
   1283             imr6.ipv6mr_interface       = interfaceIndex;
   1284             //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
   1285             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
   1286             if (err < 0)
   1287             {
   1288                 err = errno;
   1289                 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
   1290                 perror("setsockopt - IPV6_JOIN_GROUP");
   1291             }
   1292         }
   1293 
   1294         // Specify outgoing interface too
   1295         if (err == 0 && JoinMulticastGroup)
   1296         {
   1297             u_int multicast_if = interfaceIndex;
   1298             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
   1299             if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
   1300         }
   1301 
   1302         // We want to receive only IPv6 packets on this socket.
   1303         // Without this option, we may get IPv4 addresses as mapped addresses.
   1304         if (err == 0)
   1305         {
   1306             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
   1307             if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
   1308         }
   1309 
   1310         // Per the mDNS spec, send unicast packets with TTL 255
   1311         if (err == 0)
   1312         {
   1313             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
   1314             if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
   1315         }
   1316 
   1317         // and multicast packets with TTL 255 too
   1318         // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
   1319         if (err == 0)
   1320         {
   1321             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
   1322             if (err < 0 && errno == EINVAL)
   1323                 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
   1324             if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
   1325         }
   1326 
   1327         // And start listening for packets
   1328         if (err == 0)
   1329         {
   1330             mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
   1331 #ifndef NOT_HAVE_SA_LEN
   1332             bindAddr6.sin6_len         = sizeof(bindAddr6);
   1333 #endif
   1334             bindAddr6.sin6_family      = AF_INET6;
   1335             bindAddr6.sin6_port        = port.NotAnInteger;
   1336             bindAddr6.sin6_flowinfo    = 0;
   1337             bindAddr6.sin6_addr        = in6addr_any; // Want to receive multicasts AND unicasts on this socket
   1338             bindAddr6.sin6_scope_id    = 0;
   1339             err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
   1340             if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
   1341         }
   1342     }     // endif (intfAddr->sa_family == AF_INET6)
   1343 #endif
   1344 
   1345     // Set the socket to non-blocking.
   1346     if (err == 0)
   1347     {
   1348         err = fcntl(*sktPtr, F_GETFL, 0);
   1349         if (err < 0) err = errno;
   1350         else
   1351         {
   1352             err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
   1353             if (err < 0) err = errno;
   1354         }
   1355     }
   1356 
   1357     // Clean up
   1358     if (err != 0 && *sktPtr != -1)
   1359     {
   1360         int rv;
   1361         rv = close(*sktPtr);
   1362         assert(rv == 0);
   1363         *sktPtr = -1;
   1364     }
   1365     assert((err == 0) == (*sktPtr != -1));
   1366     return err;
   1367 }
   1368 
   1369 // Creates a PosixNetworkInterface for the interface whose IP address is
   1370 // intfAddr and whose name is intfName and registers it with mDNS core.
   1371 mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask,
   1372     const mDNSu8 *intfHaddr, mDNSu16 intfHlen, const char *intfName, int intfIndex)
   1373 {
   1374     int err = 0;
   1375     PosixNetworkInterface *intf;
   1376     PosixNetworkInterface *alias = NULL;
   1377 
   1378     assert(m != NULL);
   1379     assert(intfAddr != NULL);
   1380     assert(intfName != NULL);
   1381     assert(intfHaddr != NULL || intfHlen == 0);
   1382     assert(intfMask != NULL);
   1383 
   1384     // Allocate the interface structure itself.
   1385     intf = (PosixNetworkInterface*)mdns_calloc(1, sizeof(*intf));
   1386     if (intf == NULL) { assert(0); err = ENOMEM; }
   1387 
   1388     // And make a copy of the intfName.
   1389     if (err == 0)
   1390     {
   1391 #ifdef LINUX
   1392         char *s;
   1393         int len;
   1394         s = strchr(intfName, ':');
   1395         if (s != NULL)
   1396         {
   1397             len = (s - intfName) + 1;
   1398         }
   1399         else
   1400         {
   1401             len = strlen(intfName) + 1;
   1402         }
   1403         intf->intfName = malloc(len);
   1404         if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
   1405         memcpy(intf->intfName, intfName, len - 1);
   1406         intfName[len - 1] = 0;
   1407 #else
   1408         intf->intfName = mdns_strdup(intfName);
   1409         if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
   1410 #endif
   1411     }
   1412 
   1413     if (err == 0)
   1414     {
   1415         // Set up the fields required by the mDNS core.
   1416         SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
   1417         SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
   1418         if (intfHlen == sizeof(intf->coreIntf.MAC.b))
   1419         {
   1420             mDNSPlatformMemCopy(intf->coreIntf.MAC.b, intfHaddr, sizeof(intf->coreIntf.MAC.b));
   1421 
   1422             // Configure primary MAC address.
   1423             // Ideally, we would pick the default route interface with the lowest metric (see mDNSWin32).
   1424             // For now, simply assume the first one that we find is the primary one (see mDNSMacOSX).
   1425             if (mDNSSameEthAddress(&m->PrimaryMAC, &zeroEthAddr))
   1426                 mDNSPlatformMemCopy(&m->PrimaryMAC, &intf->coreIntf.MAC, sizeof(m->PrimaryMAC));
   1427         }
   1428 
   1429         //LogMsg("SetupOneInterface: %#a %#a",  &intf->coreIntf.ip,  &intf->coreIntf.mask);
   1430         mDNSPlatformStrLCopy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
   1431         intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
   1432 
   1433         intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
   1434         intf->coreIntf.McastTxRx = mDNStrue;
   1435 
   1436         // Set up the extra fields in PosixNetworkInterface.
   1437         assert(intf->intfName != NULL);         // intf->intfName already set up above
   1438         intf->index                = intfIndex;
   1439         intf->multicastSocket4     = -1;
   1440 #if HAVE_IPV6
   1441         intf->multicastSocket6     = -1;
   1442 #endif
   1443         alias                      = SearchForInterfaceByName(m, intf->intfName);
   1444         if (alias == NULL) alias   = intf;
   1445         intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
   1446 
   1447         if (alias != intf)
   1448             debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
   1449     }
   1450 
   1451     // Set up the multicast socket
   1452     if (err == 0)
   1453     {
   1454         if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
   1455             err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
   1456 #if HAVE_IPV6
   1457         else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
   1458             err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
   1459 #endif
   1460     }
   1461 
   1462     // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
   1463     // and skip the probe phase of the probe/announce packet sequence.
   1464     intf->coreIntf.DirectLink = mDNSfalse;
   1465 #ifdef DIRECTLINK_INTERFACE_NAME
   1466     if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
   1467         intf->coreIntf.DirectLink = mDNStrue;
   1468 #endif
   1469     intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;
   1470 
   1471     // The interface is all ready to go, let's register it with the mDNS core.
   1472     if (err == 0)
   1473         err = mDNS_RegisterInterface(m, &intf->coreIntf, NormalActivation);
   1474 
   1475     // Clean up.
   1476     if (err == 0)
   1477     {
   1478         num_registered_interfaces++;
   1479         debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
   1480         if (gMDNSPlatformPosixVerboseLevel > 0)
   1481             fprintf(stderr, "Registered interface %s\n", intf->intfName);
   1482     }
   1483     else
   1484     {
   1485         // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
   1486         debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
   1487         if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
   1488     }
   1489 
   1490     assert((err == 0) == (intf != NULL));
   1491 
   1492     return err;
   1493 }
   1494 
   1495 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
   1496 mDNSlocal int SetupInterfaceList(mDNS *const m)
   1497 {
   1498     mDNSBool foundav4       = mDNSfalse;
   1499     int err            = 0;
   1500     struct ifaddrs *intfList;
   1501     struct ifaddrs *firstLoopback = NULL;
   1502     int firstLoopbackIndex = 0;
   1503 
   1504     assert(m != NULL);
   1505     debugf("SetupInterfaceList");
   1506 
   1507     if (getifaddrs(&intfList) < 0)
   1508     {
   1509         err = errno;
   1510     }
   1511     if (intfList == NULL) err = ENOENT;
   1512 
   1513     if (err == 0)
   1514     {
   1515         struct ifaddrs *i = intfList;
   1516         while (i)
   1517         {
   1518             if (     i->ifa_addr != NULL &&
   1519                      ((i->ifa_addr->sa_family == AF_INET)
   1520 #if HAVE_IPV6
   1521                       || (i->ifa_addr->sa_family == AF_INET6)
   1522 #endif
   1523                       ) &&  (i->ifa_flags & IFF_UP) && !(i->ifa_flags & IFF_POINTOPOINT))
   1524             {
   1525                 int ifIndex = if_nametoindex(i->ifa_name);
   1526                 if (ifIndex == 0)
   1527                 {
   1528                     continue;
   1529                 }
   1530                 if (i->ifa_flags & IFF_LOOPBACK)
   1531                 {
   1532                     if (firstLoopback == NULL)
   1533                     {
   1534                         firstLoopback = i;
   1535                         firstLoopbackIndex = ifIndex;
   1536                     }
   1537                 }
   1538                 else
   1539                 {
   1540 #define ethernet_addr_len 6
   1541                     uint8_t hwaddr[ethernet_addr_len];
   1542                     int hwaddr_len = 0;
   1543 
   1544 #if defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
   1545                     struct ifreq ifr;
   1546                     int sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
   1547                     if (sockfd >= 0)
   1548                     {
   1549                         /* Add hardware address */
   1550                         memcpy(ifr.ifr_name, i->ifa_name, IFNAMSIZ);
   1551                         if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) != -1)
   1552                         {
   1553                             if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER)
   1554                             {
   1555                                 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ethernet_addr_len);
   1556                                 hwaddr_len = ethernet_addr_len;
   1557                             }
   1558                         }
   1559                         close(sockfd);
   1560                     }
   1561                     else
   1562                     {
   1563                         memset(hwaddr, 0, sizeof(hwaddr));
   1564                     }
   1565 #endif // TARGET_OS_LINUX
   1566 
   1567 #if defined(TARGET_OS_MAC) && TARGET_OS_MAC
   1568                     for (struct ifaddrs *hw_scan = intfList; hw_scan != NULL; hw_scan = hw_scan->ifa_next)
   1569                     {
   1570                         if (hw_scan->ifa_addr != NULL &&
   1571                             hw_scan->ifa_addr->sa_family == AF_LINK && !strcmp(hw_scan->ifa_name, i->ifa_name))
   1572                         {
   1573                             struct sockaddr_dl *sdl = (struct sockaddr_dl *)hw_scan->ifa_addr;
   1574                             if (sdl->sdl_alen == ethernet_addr_len)
   1575                             {
   1576                                 hwaddr_len = ethernet_addr_len;
   1577                                 memcpy(hwaddr, LLADDR(sdl), hwaddr_len);
   1578                             }
   1579                             break;
   1580                         }
   1581                     }
   1582 #endif
   1583                     if (SetupOneInterface(m, i->ifa_addr, i->ifa_netmask,
   1584                                           hwaddr, hwaddr_len, i->ifa_name, ifIndex) == 0)
   1585                     {
   1586                         if (i->ifa_addr->sa_family == AF_INET)
   1587                             foundav4 = mDNStrue;
   1588                     }
   1589                 }
   1590             }
   1591             i = i->ifa_next;
   1592         }
   1593 
   1594         // If we found no normal interfaces but we did find a loopback interface, register the
   1595         // loopback interface.  This allows self-discovery if no interfaces are configured.
   1596         // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
   1597         // In the interim, we skip loopback interface only if we found at least one v4 interface to use
   1598         // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
   1599         if (!foundav4 && firstLoopback)
   1600             (void) SetupOneInterface(m, firstLoopback->ifa_addr, firstLoopback->ifa_netmask,
   1601                 NULL, 0, firstLoopback->ifa_name, firstLoopbackIndex);
   1602     }
   1603 
   1604     // Clean up.
   1605     if (intfList != NULL) freeifaddrs(intfList);
   1606 
   1607     // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
   1608     PosixNetworkInterface **ri = &gRecentInterfaces;
   1609     const mDNSs32 utc = mDNSPlatformUTC();
   1610     while (*ri)
   1611     {
   1612         PosixNetworkInterface *pi = *ri;
   1613         if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
   1614         else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; mdns_free(pi); }
   1615     }
   1616 
   1617     return err;
   1618 }
   1619 
   1620 #if USES_NETLINK
   1621 
   1622 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
   1623 
   1624 // Open a socket that will receive interface change notifications
   1625 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
   1626 {
   1627     mStatus err = mStatus_NoError;
   1628     struct sockaddr_nl snl;
   1629     int sock;
   1630     int ret;
   1631 
   1632     sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
   1633     if (sock < 0)
   1634         return errno;
   1635 
   1636     // Configure read to be non-blocking because inbound msg size is not known in advance
   1637     (void) fcntl(sock, F_SETFL, O_NONBLOCK);
   1638 
   1639     /* Subscribe the socket to Link & IP addr notifications. */
   1640     mDNSPlatformMemZero(&snl, sizeof snl);
   1641 #ifndef NOT_HAVE_SA_LEN
   1642     snl.nl_len    = sizeof(snl);
   1643 #endif
   1644     snl.nl_family = AF_NETLINK;
   1645     snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
   1646     ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
   1647     if (0 == ret)
   1648         *pFD = sock;
   1649     else
   1650         err = errno;
   1651 
   1652     return err;
   1653 }
   1654 
   1655 #if MDNS_DEBUGMSGS
   1656 mDNSlocal void      PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
   1657 {
   1658     const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
   1659     const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
   1660 
   1661     printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
   1662            pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
   1663            pNLMsg->nlmsg_flags);
   1664 
   1665     if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
   1666     {
   1667         struct ifinfomsg    *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
   1668         printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
   1669                pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
   1670 
   1671     }
   1672     else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
   1673     {
   1674         struct ifaddrmsg    *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
   1675         printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
   1676                pIfAddr->ifa_index, pIfAddr->ifa_flags);
   1677     }
   1678     printf("\n");
   1679 }
   1680 #endif
   1681 
   1682 mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
   1683 // Read through the messages on sd and if any indicate that any interface records should
   1684 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
   1685 {
   1686     ssize_t readCount;
   1687     char buff[4096];
   1688     struct nlmsghdr         *pNLMsg = (struct nlmsghdr*) buff;
   1689     mDNSu32 result = 0;
   1690 
   1691     // The structure here is more complex than it really ought to be because,
   1692     // unfortunately, there's no good way to size a buffer in advance large
   1693     // enough to hold all pending data and so avoid message fragmentation.
   1694     // (Note that FIONREAD is not supported on AF_NETLINK.)
   1695 
   1696     readCount = read(sd, buff, sizeof buff);
   1697     while (1)
   1698     {
   1699         // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
   1700         // If not, discard already-processed messages in buffer and read more data.
   1701         if (((char*) &pNLMsg[1] > (buff + readCount)) ||    // i.e. *pNLMsg extends off end of buffer
   1702             ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
   1703         {
   1704             if (buff < (char*) pNLMsg)      // we have space to shuffle
   1705             {
   1706                 // discard processed data
   1707                 readCount -= ((char*) pNLMsg - buff);
   1708                 memmove(buff, pNLMsg, readCount);
   1709                 pNLMsg = (struct nlmsghdr*) buff;
   1710 
   1711                 // read more data
   1712                 readCount += read(sd, buff + readCount, sizeof buff - readCount);
   1713                 continue;                   // spin around and revalidate with new readCount
   1714             }
   1715             else
   1716                 break;  // Otherwise message does not fit in buffer
   1717         }
   1718 
   1719 #if MDNS_DEBUGMSGS
   1720         PrintNetLinkMsg(pNLMsg);
   1721 #endif
   1722 
   1723         // Process the NetLink message
   1724         if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
   1725             result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
   1726         else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
   1727             result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
   1728 
   1729         // Advance pNLMsg to the next message in the buffer
   1730         if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
   1731         {
   1732             ssize_t len = readCount - ((char*)pNLMsg - buff);
   1733             pNLMsg = NLMSG_NEXT(pNLMsg, len);
   1734         }
   1735         else
   1736             break;  // all done!
   1737     }
   1738 
   1739     return result;
   1740 }
   1741 
   1742 #else // USES_NETLINK
   1743 
   1744 // Open a socket that will receive interface change notifications
   1745 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
   1746 {
   1747     *pFD = socket(AF_ROUTE, SOCK_RAW, 0);
   1748 
   1749     if (*pFD < 0)
   1750         return mStatus_UnknownErr;
   1751 
   1752     // Configure read to be non-blocking because inbound msg size is not known in advance
   1753     (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
   1754 
   1755     return mStatus_NoError;
   1756 }
   1757 
   1758 #if MDNS_DEBUGMSGS
   1759 mDNSlocal void      PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
   1760 {
   1761     const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
   1762                                   "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
   1763                                   "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
   1764 
   1765     int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
   1766 
   1767     printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
   1768 }
   1769 #endif
   1770 
   1771 mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
   1772 // Read through the messages on sd and if any indicate that any interface records should
   1773 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
   1774 {
   1775     ssize_t readCount;
   1776     char buff[4096];
   1777     struct ifa_msghdr       *pRSMsg = (struct ifa_msghdr*) buff;
   1778     mDNSu32 result = 0;
   1779 
   1780     readCount = read(sd, buff, sizeof buff);
   1781     if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
   1782         return mStatus_UnsupportedErr;      // cannot decipher message
   1783 
   1784 #if MDNS_DEBUGMSGS
   1785     PrintRoutingSocketMsg(pRSMsg);
   1786 #endif
   1787 
   1788     // Process the message
   1789     if (pRSMsg->ifam_type == RTM_NEWADDR || pRSMsg->ifam_type == RTM_DELADDR ||
   1790         pRSMsg->ifam_type == RTM_IFINFO)
   1791     {
   1792         if (pRSMsg->ifam_type == RTM_IFINFO)
   1793             result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
   1794         else
   1795             result |= 1 << pRSMsg->ifam_index;
   1796     }
   1797 
   1798     return result;
   1799 }
   1800 
   1801 #endif // USES_NETLINK
   1802 
   1803 // Called when data appears on interface change notification socket
   1804 mDNSlocal void InterfaceChangeCallback(int fd, void *context)
   1805 {
   1806     IfChangeRec     *pChgRec = (IfChangeRec*) context;
   1807     fd_set readFDs;
   1808     mDNSu32 changedInterfaces = 0;
   1809     struct timeval zeroTimeout = { 0, 0 };
   1810 
   1811     (void)fd; // Unused
   1812 
   1813     FD_ZERO(&readFDs);
   1814     FD_SET(pChgRec->NotifySD, &readFDs);
   1815 
   1816     do
   1817     {
   1818         changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
   1819     }
   1820     while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
   1821 
   1822     // Currently we rebuild the entire interface list whenever any interface change is
   1823     // detected. If this ever proves to be a performance issue in a multi-homed
   1824     // configuration, more care should be paid to changedInterfaces.
   1825     if (changedInterfaces)
   1826         mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
   1827 }
   1828 
   1829 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
   1830 mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
   1831 {
   1832     mStatus err;
   1833     IfChangeRec *pChgRec;
   1834 
   1835     pChgRec = (IfChangeRec*) mDNSPlatformMemAllocateClear(sizeof *pChgRec);
   1836     if (pChgRec == NULL)
   1837         return mStatus_NoMemoryErr;
   1838 
   1839     pChgRec->mDNS = m;
   1840     err = OpenIfNotifySocket(&pChgRec->NotifySD);
   1841     if (err == 0)
   1842         err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
   1843     if (err)
   1844         mDNSPlatformMemFree(pChgRec);
   1845 
   1846     return err;
   1847 }
   1848 
   1849 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
   1850 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
   1851 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
   1852 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
   1853 {
   1854     int err;
   1855     int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
   1856     struct sockaddr_in s5353;
   1857 
   1858     mDNSPlatformMemZero(&s5353, sizeof(s5353));
   1859 #ifndef NOT_HAVE_SA_LEN
   1860     s5353.sin_len         = sizeof(s5353);
   1861 #endif
   1862     s5353.sin_family      = AF_INET;
   1863     s5353.sin_port        = MulticastDNSPort.NotAnInteger;
   1864     s5353.sin_addr.s_addr = 0;
   1865     err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
   1866     close(s);
   1867     if (err) debugf("No unicast UDP responses");
   1868     else debugf("Unicast UDP responses okay");
   1869     return(err == 0);
   1870 }
   1871 
   1872 // mDNS core calls this routine to initialise the platform-specific data.
   1873 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
   1874 {
   1875     int err = 0;
   1876     struct sockaddr sa;
   1877     assert(m != NULL);
   1878 
   1879     if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
   1880 
   1881     // Tell mDNS core the names of this machine.
   1882 
   1883     // Set up the nice label
   1884     m->nicelabel.c[0] = 0;
   1885     GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
   1886     if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
   1887 
   1888     // Set up the RFC 1034-compliant label
   1889     m->hostlabel.c[0] = 0;
   1890     GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
   1891     if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
   1892 
   1893     mDNS_SetFQDN(m);
   1894 
   1895     sa.sa_family = AF_INET;
   1896     m->p->unicastSocket4 = -1;
   1897     if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
   1898 #if HAVE_IPV6
   1899     sa.sa_family = AF_INET6;
   1900     m->p->unicastSocket6 = -1;
   1901     if (err == mStatus_NoError)
   1902     {
   1903 	err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
   1904 	if (err != mStatus_NoError)
   1905 	{
   1906 	    // Ignore errors configuring IPv6.
   1907 	    m->p->unicastSocket6 = -1;
   1908 	    err = mStatus_NoError;
   1909 	}
   1910     }
   1911 #endif
   1912 
   1913     // Tell mDNS core about the network interfaces on this machine.
   1914     if (err == mStatus_NoError) err = SetupInterfaceList(m);
   1915 
   1916     // Tell mDNS core about DNS Servers
   1917     mDNS_Lock(m);
   1918     if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
   1919     mDNS_Unlock(m);
   1920 
   1921     if (err == mStatus_NoError)
   1922     {
   1923         err = WatchForInterfaceChange(m);
   1924         // Failure to observe interface changes is non-fatal.
   1925         if (err != mStatus_NoError)
   1926         {
   1927             fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
   1928             err = mStatus_NoError;
   1929         }
   1930     }
   1931 
   1932 #if POSIX_HAS_TLS
   1933     // Use the SRP TLS shim.
   1934     mDNSPosixTLSInit();
   1935 #endif
   1936 
   1937     // We don't do asynchronous initialization on the Posix platform, so by the time
   1938     // we get here the setup will already have succeeded or failed.  If it succeeded,
   1939     // we should just call mDNSCoreInitComplete() immediately.
   1940     if (err == mStatus_NoError)
   1941         mDNSCoreInitComplete(m, mStatus_NoError);
   1942 
   1943     return PosixErrorToStatus(err);
   1944 }
   1945 
   1946 // mDNS core calls this routine to clean up the platform-specific data.
   1947 // In our case all we need to do is to tear down every network interface.
   1948 mDNSexport void mDNSPlatformClose(mDNS *const m)
   1949 {
   1950     int rv;
   1951     assert(m != NULL);
   1952     ClearInterfaceList(m);
   1953     if (m->p->unicastSocket4 != -1)
   1954     {
   1955         rv = close(m->p->unicastSocket4);
   1956         assert(rv == 0);
   1957     }
   1958 #if HAVE_IPV6
   1959     if (m->p->unicastSocket6 != -1)
   1960     {
   1961         rv = close(m->p->unicastSocket6);
   1962         assert(rv == 0);
   1963     }
   1964 #endif
   1965 }
   1966 
   1967 // This is used internally by InterfaceChangeCallback.
   1968 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
   1969 // can call it in response to a SIGHUP (mainly for debugging purposes).
   1970 mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
   1971 {
   1972     int err;
   1973     // This is a pretty heavyweight way to process interface changes --
   1974     // destroying the entire interface list and then making fresh one from scratch.
   1975     // We should make it like the OS X version, which leaves unchanged interfaces alone.
   1976     ClearInterfaceList(m);
   1977     err = SetupInterfaceList(m);
   1978     return PosixErrorToStatus(err);
   1979 }
   1980 
   1981 #if COMPILER_LIKES_PRAGMA_MARK
   1982 #pragma mark ***** Locking
   1983 #endif
   1984 
   1985 // On the Posix platform, locking is a no-op because we only ever enter
   1986 // mDNS core on the main thread.
   1987 
   1988 // mDNS core calls this routine when it wants to prevent
   1989 // the platform from reentering mDNS core code.
   1990 mDNSexport void    mDNSPlatformLock   (const mDNS *const m)
   1991 {
   1992     (void) m;   // Unused
   1993 }
   1994 
   1995 // mDNS core calls this routine when it release the lock taken by
   1996 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
   1997 mDNSexport void    mDNSPlatformUnlock (const mDNS *const m)
   1998 {
   1999     (void) m;   // Unused
   2000 }
   2001 
   2002 #if COMPILER_LIKES_PRAGMA_MARK
   2003 #pragma mark ***** Strings
   2004 #endif
   2005 
   2006 mDNSexport void    mDNSPlatformStrLCopy(void *dst, const void *src, mDNSu32 len)
   2007 {
   2008     mdns_strlcpy((char *)dst, (const char *)src, len);
   2009 }
   2010 
   2011 // mDNS core calls this routine to get the length of a C string.
   2012 // On the Posix platform this maps directly to the ANSI C strlen.
   2013 mDNSexport mDNSu32  mDNSPlatformStrLen (const void *src)
   2014 {
   2015     return strlen((const char*)src);
   2016 }
   2017 
   2018 // mDNS core calls this routine to copy memory.
   2019 // On the Posix platform this maps directly to the ANSI C memcpy.
   2020 mDNSexport void    mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
   2021 {
   2022     memcpy(dst, src, len);
   2023 }
   2024 
   2025 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
   2026 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
   2027 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
   2028 {
   2029     return memcmp(dst, src, len) == 0;
   2030 }
   2031 
   2032 // If the caller wants to know the exact return of memcmp, then use this instead
   2033 // of mDNSPlatformMemSame
   2034 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
   2035 {
   2036     return (memcmp(dst, src, len));
   2037 }
   2038 
   2039 mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
   2040 {
   2041     qsort(base, nel, width, compar);
   2042 }
   2043 
   2044 // Proxy stub functions
   2045 mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
   2046 {
   2047     (void) q;
   2048     (void) h;
   2049     (void) msg;
   2050     (void) ptr;
   2051     (void) limit;
   2052 
   2053     return ptr;
   2054 }
   2055 
   2056 // mDNS core calls this routine to clear blocks of memory.
   2057 // On the Posix platform this is a simple wrapper around ANSI C memset.
   2058 mDNSexport void  mDNSPlatformMemZero(void *dst, mDNSu32 len)
   2059 {
   2060     memset(dst, 0, len);
   2061 }
   2062 
   2063 #if !MDNS_MALLOC_DEBUGGING
   2064 mDNSexport void *mDNSPlatformMemAllocate(mDNSu32 len)      { return(mallocL("mDNSPlatformMemAllocate", len)); }
   2065 mDNSexport void *mDNSPlatformMemAllocateClear(mDNSu32 len) { return(callocL("mDNSPlatformMemAllocateClear", len)); }
   2066 mDNSexport void  mDNSPlatformMemFree    (void *mem)        {          freeL("mDNSPlatformMemFree", mem); }
   2067 #endif
   2068 
   2069 #if _PLATFORM_HAS_STRONG_PRNG_
   2070 mDNSexport mDNSu32 mDNSPlatformRandomNumber(void)
   2071 {
   2072     return(arc4random());
   2073 }
   2074 #else
   2075 mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
   2076 {
   2077     struct timeval tv;
   2078     gettimeofday(&tv, NULL);
   2079     return(tv.tv_usec);
   2080 }
   2081 #endif
   2082 
   2083 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
   2084 
   2085 mDNSexport mStatus mDNSPlatformTimeInit(void)
   2086 {
   2087     // No special setup is required on Posix -- we just use gettimeofday();
   2088     // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
   2089     // We should find a better way to do this
   2090     return(mStatus_NoError);
   2091 }
   2092 
   2093 mDNSexport mDNSs32 mDNSPlatformRawTime(void)
   2094 {
   2095     struct timespec tm;
   2096     int ret = clock_gettime(CLOCK_MONOTONIC, &tm);
   2097     assert(ret == 0); // This call will only fail if the number of seconds does not fit in an object of type time_t.
   2098 
   2099     // tm.tv_sec is seconds since some unspecified starting point (it is usually the system start up time)
   2100     // tm.tv_nsec is nanoseconds since the start of this second (i.e. values 0 to 999999999)
   2101     // We use the lower 22 bits of tm.tv_sec for the top 22 bits of our result
   2102     // and we multiply tm.tv_nsec by 2 / 1953125 to get a value in the range 0-1023 to go in the bottom 10 bits.
   2103     // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
   2104     // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
   2105 
   2106     return (mDNSs32)(((tm.tv_sec << 10) | (tm.tv_nsec * 2 / 1953125)));
   2107 }
   2108 
   2109 mDNSexport mDNSs32 mDNSPlatformUTC(void)
   2110 {
   2111     return time(NULL);
   2112 }
   2113 
   2114 // This should return elapsed time in seconds since boot. Posix doesn't have an API for this, so we currently assume
   2115 // that time() doesn't get adjusted, which isn't the case.
   2116 mDNSexport mDNSs32 mDNSPlatformContinuousTimeSeconds(void)
   2117 {
   2118 #ifdef CLOCK_BOOTTIME
   2119     // CLOCK_BOOTTIME is a Linux-specific constant that indicates a monotonic time that includes time asleep
   2120     const int clockid = CLOCK_BOOTTIME;
   2121 #else
   2122     // On MacOS, CLOCK_MONOTONIC is a monotonic time that includes time asleep. However, this may not be the case
   2123     // on other Posix systems, since the POSIX specification doesn't say one way or the other. E.g. on Linux
   2124     // time asleep is not accounted for, which is why we prefer CLOCK_BOOTTIME on Linux.
   2125     const int clockid = CLOCK_MONOTONIC;
   2126 #endif
   2127     struct timespec tm;
   2128     int ret = clock_gettime(clockid, &tm);
   2129     assert(ret == 0); // This call will only fail if the number of seconds does not fit in an object of type time_t.
   2130 
   2131     // We are only accurate to the second.
   2132     return (mDNSs32)tm.tv_sec;
   2133 }
   2134 
   2135 mDNSexport void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
   2136 {
   2137     (void) InterfaceID;
   2138     (void) EthAddr;
   2139     (void) IPAddr;
   2140     (void) iteration;
   2141 }
   2142 
   2143 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID)
   2144 {
   2145     (void) rr;
   2146     (void) InterfaceID;
   2147 
   2148     return 1;
   2149 }
   2150 
   2151 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(const DNSQuestion *const q, const NetworkInterfaceInfo *const intf)
   2152 {
   2153     (void) q;
   2154     (void) intf;
   2155 
   2156     return 1;
   2157 }
   2158 
   2159 // Used for debugging purposes. For now, just set the buffer to zero
   2160 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
   2161 {
   2162     (void) te;
   2163     if (bufsize) buf[0] = 0;
   2164 }
   2165 
   2166 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
   2167 {
   2168     (void) sadd;    // Unused
   2169     (void) dadd;    // Unused
   2170     (void) lport;   // Unused
   2171     (void) rport;   // Unused
   2172     (void) seq;     // Unused
   2173     (void) ack;     // Unused
   2174     (void) win;     // Unused
   2175 }
   2176 
   2177 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
   2178 {
   2179     (void) laddr;   // Unused
   2180     (void) raddr;   // Unused
   2181     (void) lport;   // Unused
   2182     (void) rport;   // Unused
   2183     (void) mti;     // Unused
   2184 
   2185     return mStatus_NoError;
   2186 }
   2187 
   2188 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNSAddr *raddr)
   2189 {
   2190     (void) raddr; // Unused
   2191 
   2192     return mStatus_NoError;
   2193 }
   2194 
   2195 mDNSexport mStatus    mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
   2196 {
   2197     (void) spsaddr; // Unused
   2198     (void) ifname;  // Unused
   2199 
   2200     return mStatus_NoError;
   2201 }
   2202 
   2203 mDNSexport mStatus    mDNSPlatformClearSPSData(void)
   2204 {
   2205     return mStatus_NoError;
   2206 }
   2207 
   2208 mDNSexport mStatus mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length)
   2209 {
   2210     (void) ifname; // Unused
   2211     (void) msg;    // Unused
   2212     (void) length; // Unused
   2213     return mStatus_UnsupportedErr;
   2214 }
   2215 
   2216 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
   2217 {
   2218     (void) sock; // unused
   2219 
   2220     return (mDNSu16)-1;
   2221 }
   2222 
   2223 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
   2224 {
   2225     (void) InterfaceID; // unused
   2226 
   2227     return mDNSfalse;
   2228 }
   2229 
   2230 mDNSexport void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q)
   2231 {
   2232     (void) sock;
   2233     (void) transType;
   2234     (void) addrType;
   2235     (void) q;
   2236 }
   2237 
   2238 mDNSexport mDNSs32 mDNSPlatformGetPID(void)
   2239 {
   2240     return 0;
   2241 }
   2242 
   2243 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
   2244 {
   2245     if (*nfds < s + 1) *nfds = s + 1;
   2246     FD_SET(s, readfds);
   2247 }
   2248 
   2249 mDNSlocal void mDNSPosixGetFDSetForSelect(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds)
   2250 {
   2251     int numFDs = *nfds;
   2252     PosixEventSource *iSource;
   2253 
   2254     // 2. Build our list of active file descriptors
   2255     PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
   2256     if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket4);
   2257 #if HAVE_IPV6
   2258     if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, m->p->unicastSocket6);
   2259 #endif
   2260     while (info)
   2261     {
   2262         if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket4);
   2263 #if HAVE_IPV6
   2264         if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(&numFDs, readfds, info->multicastSocket6);
   2265 #endif
   2266         info = (PosixNetworkInterface *)(info->coreIntf.next);
   2267     }
   2268 
   2269     // Copy over the event fds.   We have to do it this way because client-provided event loops expect
   2270     // to initialize their FD sets first and then call mDNSPosixGetFDSet()
   2271     for (iSource = gEventSources; iSource; iSource = iSource->next)
   2272     {
   2273         if (iSource->readCallback != NULL)
   2274             FD_SET(iSource->fd, readfds);
   2275         if (iSource->writeCallback != NULL)
   2276             FD_SET(iSource->fd, writefds);
   2277         if (numFDs <= iSource->fd)
   2278             numFDs = iSource->fd + 1;
   2279     }
   2280     *nfds = numFDs;
   2281 }
   2282 
   2283 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, fd_set *writefds, struct timeval *timeout)
   2284 {
   2285     mDNSs32 ticks;
   2286     struct timeval interval;
   2287 
   2288     // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
   2289     mDNSs32 nextevent = mDNS_Execute(m);
   2290 
   2291     // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
   2292     ticks = nextevent - mDNS_TimeNow(m);
   2293     if (ticks < 1) ticks = 1;
   2294     interval.tv_sec  = ticks >> 10;                     // The high 22 bits are seconds
   2295     interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16;  // The low 10 bits are 1024ths
   2296 
   2297     // 4. If client's proposed timeout is more than what we want, then reduce it
   2298     if (timeout->tv_sec > interval.tv_sec ||
   2299         (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
   2300         *timeout = interval;
   2301 
   2302     mDNSPosixGetFDSetForSelect(m, nfds, readfds, writefds);
   2303 }
   2304 
   2305 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds, fd_set *writefds)
   2306 {
   2307     PosixNetworkInterface *info;
   2308     PosixEventSource    *iSource;
   2309     assert(m       != NULL);
   2310     assert(readfds != NULL);
   2311     info = (PosixNetworkInterface *)(m->HostInterfaces);
   2312 
   2313     if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
   2314     {
   2315         FD_CLR(m->p->unicastSocket4, readfds);
   2316         SocketDataReady(m, NULL, m->p->unicastSocket4, NULL);
   2317     }
   2318 #if HAVE_IPV6
   2319     if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
   2320     {
   2321         FD_CLR(m->p->unicastSocket6, readfds);
   2322         SocketDataReady(m, NULL, m->p->unicastSocket6, NULL);
   2323     }
   2324 #endif
   2325 
   2326     while (info)
   2327     {
   2328         if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
   2329         {
   2330             FD_CLR(info->multicastSocket4, readfds);
   2331             SocketDataReady(m, info, info->multicastSocket4, NULL);
   2332         }
   2333 #if HAVE_IPV6
   2334         if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
   2335         {
   2336             FD_CLR(info->multicastSocket6, readfds);
   2337             SocketDataReady(m, info, info->multicastSocket6, NULL);
   2338         }
   2339 #endif
   2340         info = (PosixNetworkInterface *)(info->coreIntf.next);
   2341     }
   2342 
   2343     // Now process routing socket events, discovery relay events and anything else of that ilk.
   2344     for (iSource = gEventSources; iSource; iSource = iSource->next)
   2345     {
   2346         if (iSource->readCallback != NULL && FD_ISSET(iSource->fd, readfds))
   2347         {
   2348             iSource->readCallback(iSource->fd, iSource->readContext);
   2349             break;  // in case callback removed elements from gEventSources
   2350         }
   2351         else if (iSource->writeCallback != NULL && FD_ISSET(iSource->fd, writefds))
   2352         {
   2353             mDNSPosixEventCallback writeCallback = iSource->writeCallback;
   2354             // Write events are one-shot: to get another event, the consumer has to put in a new request.
   2355             // We reset this before calling the callback just in case the callback requests another write
   2356             // callback, or deletes the event context from the list.
   2357             iSource->writeCallback = NULL;
   2358             writeCallback(iSource->fd, iSource->writeContext);
   2359             break;  // in case callback removed elements from gEventSources
   2360         }
   2361     }
   2362 }
   2363 
   2364 mDNSu32 mDNSPlatformEventContextSize = sizeof (PosixEventSource);
   2365 
   2366 mDNSlocal void requestIOEvents(PosixEventSource *newSource, const char *taskName,
   2367                                   mDNSPosixEventCallback callback, void *context, int flag)
   2368 {
   2369     PosixEventSource **epp = &gEventSources;
   2370 
   2371     if (newSource->fd >= (int) FD_SETSIZE || newSource->fd < 0)
   2372     {
   2373         LogMsg("requestIOEvents called with fd %d > FD_SETSIZE %d.", newSource->fd, FD_SETSIZE);
   2374         assert(0);
   2375     }
   2376     if (callback == NULL)
   2377     {
   2378         LogMsg("requestIOEvents called no callback.", newSource->fd, FD_SETSIZE);
   2379         assert(0);
   2380     }
   2381 
   2382     // See if this event context is already on the list; if it is, no need to scan the list.
   2383     if (!(newSource->flags & PosixEventFlag_OnList))
   2384     {
   2385         while (*epp)
   2386         {
   2387             // This should never happen.
   2388             if (newSource == *epp)
   2389             {
   2390                 LogMsg("Event context marked not on list but is on list.");
   2391                 assert(0);
   2392             }
   2393             epp = &(*epp)->next;
   2394         }
   2395         if (*epp == NULL)
   2396         {
   2397             *epp = newSource;
   2398             newSource->next = NULL;
   2399             newSource->flags = PosixEventFlag_OnList;
   2400         }
   2401     }
   2402 
   2403     if (flag & PosixEventFlag_Read)
   2404     {
   2405         newSource->readCallback = callback;
   2406         newSource->readContext = context;
   2407         newSource->flags |= PosixEventFlag_Read;
   2408         newSource->readTaskName = taskName;
   2409     }
   2410     if (flag & PosixEventFlag_Write)
   2411     {
   2412         newSource->writeCallback = callback;
   2413         newSource->writeContext = context;
   2414         newSource->flags |= PosixEventFlag_Write;
   2415         newSource->writeTaskName = taskName;
   2416     }
   2417 }
   2418 
   2419 mDNSlocal void requestReadEvents(PosixEventSource *eventSource,
   2420                                     const char *taskName, mDNSPosixEventCallback callback, void *context)
   2421 {
   2422     requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Read);
   2423 }
   2424 
   2425 mDNSlocal void requestWriteEvents(PosixEventSource *eventSource,
   2426                                      const char *taskName, mDNSPosixEventCallback callback, void *context)
   2427 {
   2428     requestIOEvents(eventSource, taskName, callback, context, PosixEventFlag_Write);
   2429 }
   2430 
   2431 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
   2432 mDNSlocal mStatus stopReadOrWriteEvents(int fd, mDNSBool freeContext, mDNSBool removeContext, int flags)
   2433 {
   2434     PosixEventSource *iSource, **epp = &gEventSources;
   2435 
   2436     while (*epp)
   2437     {
   2438         iSource = *epp;
   2439         if (fd == iSource->fd)
   2440         {
   2441             if (flags & PosixEventFlag_Read)
   2442             {
   2443                 iSource->readCallback = NULL;
   2444                 iSource->readContext = NULL;
   2445             }
   2446             if (flags & PosixEventFlag_Write)
   2447             {
   2448                 iSource->writeCallback = NULL;
   2449                 iSource->writeContext = NULL;
   2450             }
   2451             if (iSource->writeCallback == NULL && iSource->readCallback == NULL)
   2452             {
   2453                 if (removeContext || freeContext)
   2454                     *epp = iSource->next;
   2455                 if (freeContext)
   2456                     mdns_free(iSource);
   2457             }
   2458             return mStatus_NoError;
   2459         }
   2460         epp = &(*epp)->next;
   2461     }
   2462     return mStatus_NoSuchNameErr;
   2463 }
   2464 
   2465 // Some of the mDNSPosix client code relies on being able to add FDs to the event loop without
   2466 // providing storage for the event-related info.   mDNSPosixAddFDToEventLoop and
   2467 // mDNSPosixRemoveFDFromEventLoop handle the event structure storage automatically.
   2468 mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
   2469 {
   2470     PosixEventSource *newSource;
   2471 
   2472     newSource = (PosixEventSource*) mdns_malloc(sizeof *newSource);
   2473     if (NULL == newSource)
   2474         return mStatus_NoMemoryErr;
   2475     memset(newSource, 0, sizeof *newSource);
   2476     newSource->fd = fd;
   2477 
   2478     requestReadEvents(newSource, "mDNSPosixAddFDToEventLoop", callback, context);
   2479     return mStatus_NoError;
   2480 }
   2481 
   2482 mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
   2483 {
   2484     return stopReadOrWriteEvents(fd, mDNStrue, mDNStrue, PosixEventFlag_Read | PosixEventFlag_Write);
   2485 }
   2486 
   2487 // Simply note the received signal in gEventSignals.
   2488 mDNSlocal void  NoteSignal(int signum)
   2489 {
   2490     sigaddset(&gEventSignals, signum);
   2491 }
   2492 
   2493 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
   2494 mStatus mDNSPosixListenForSignalInEventLoop(int signum)
   2495 {
   2496     struct sigaction action;
   2497     mStatus err;
   2498 
   2499     mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
   2500     action.sa_handler = NoteSignal;
   2501     err = sigaction(signum, &action, (struct sigaction*) NULL);
   2502 
   2503     sigaddset(&gEventSignalSet, signum);
   2504 
   2505     return err;
   2506 }
   2507 
   2508 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
   2509 mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
   2510 {
   2511     struct sigaction action;
   2512     mStatus err;
   2513 
   2514     mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
   2515     action.sa_handler = SIG_DFL;
   2516     err = sigaction(signum, &action, (struct sigaction*) NULL);
   2517 
   2518     sigdelset(&gEventSignalSet, signum);
   2519 
   2520     return err;
   2521 }
   2522 
   2523 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
   2524 // Return as soon as internal timeout expires, or a signal we're listening for is received.
   2525 mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
   2526                                   sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
   2527 {
   2528     fd_set listenFDs;
   2529     fd_set writeFDs;
   2530     int numFDs = 0, numReady;
   2531     struct timeval timeout = *pTimeout;
   2532 
   2533     // 1. Set up the fd_set as usual here.
   2534     // This example client has no file descriptors of its own,
   2535     // but a real application would call FD_SET to add them to the set here
   2536     FD_ZERO(&listenFDs);
   2537     FD_ZERO(&writeFDs);
   2538 
   2539     // 2. Set up the timeout.
   2540     // MainLoop has already called mDNS_Execute and udsserver_idle, so the timeout we
   2541     // were passed is already set up.
   2542 
   2543     // Include the sockets that are listening to the wire in our select() set
   2544     mDNSPosixGetFDSetForSelect(m, &numFDs, &listenFDs, &writeFDs);
   2545     numReady = select(numFDs, &listenFDs, &writeFDs, (fd_set*) NULL, &timeout);
   2546 
   2547     if (numReady > 0)
   2548     {
   2549         mDNSPosixProcessFDSet(m, &listenFDs, &writeFDs);
   2550         *pDataDispatched = mDNStrue;
   2551     }
   2552     else if (numReady < 0)
   2553     {
   2554 	if (errno != EINTR) {
   2555             // This should never happen, represents a coding error, and is not recoverable, since
   2556             // we'll just sit here spinning and never receive another event.   The usual reason for
   2557             // it to happen is that an FD was closed but not removed from the event list.
   2558             LogMsg("select failed: %s", strerror(errno));
   2559             abort();
   2560         }
   2561     }
   2562     else
   2563         *pDataDispatched = mDNSfalse;
   2564 
   2565     (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
   2566     *pSignalsReceived = gEventSignals;
   2567     sigemptyset(&gEventSignals);
   2568     (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
   2569 
   2570     return mStatus_NoError;
   2571 }
   2572