Changeset f761b29 in rtems-libbsd


Ignore:
Timestamp:
Sep 19, 2018, 6:52:21 AM (8 months ago)
Author:
Sebastian Huber <sebastian.huber@…>
Branches:
a87e0f4f5c4795f77dc3956c7d1543f90f7d7710, 16fa6a4651faaa77ef72c7e03d285c143d6e54fa
Children:
f01edf1
Parents:
49ebc73
git-author:
Sebastian Huber <sebastian.huber@…> (09/19/18 06:52:21)
git-committer:
Sebastian Huber <sebastian.huber@…> (09/20/18 09:23:32)
Message:

mDNSResponder: Update to v625.41.2

The sources can be obtained via:

https://opensource.apple.com/tarballs/mDNSResponder/mDNSResponder-625.41.2.tar.gz

Update #3522.

Location:
mDNSResponder
Files:
5 added
21 deleted
90 edited
4 moved

Legend:

Unmodified
Added
Removed
  • mDNSResponder/Clients/ClientCommon.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2008 Apple Inc. All rights reserved.
     3 * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
    44 *
    5  * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
     5 * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
    66 * ("Apple") in consideration of your agreement to the following terms, and your
    77 * use, installation, modification or redistribution of this Apple software
     
    1717 * this notice and the following text and disclaimers in all such redistributions of
    1818 * the Apple Software.  Neither the name, trademarks, service marks or logos of
    19  * Apple Computer, Inc. may be used to endorse or promote products derived from the
     19 * Apple Inc. may be used to endorse or promote products derived from the
    2020 * Apple Software without specific prior written permission from Apple.  Except as
    2121 * expressly stated in this notice, no other rights or licenses, express or implied,
  • mDNSResponder/Clients/dns-sd.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2013 Apple Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    5  * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
     5 * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.
    66 * ("Apple") in consideration of your agreement to the following terms, and your
    77 * use, installation, modification or redistribution of this Apple software
     
    1717 * this notice and the following text and disclaimers in all such redistributions of
    1818 * the Apple Software.  Neither the name, trademarks, service marks or logos of
    19  * Apple Computer, Inc. may be used to endorse or promote products derived from the
     19 * Apple Inc. may be used to endorse or promote products derived from the
    2020 * Apple Software without specific prior written permission from Apple.  Except as
    2121 * expressly stated in this notice, no other rights or licenses, express or implied,
     
    5858//#define TEST_NEW_CLIENTSTUB 1
    5959
    60 // When building mDNSResponder for Mac OS X 10.4 and earlier, /usr/lib/libSystem.dylib is built using its own private
    61 // copy of dnssd_clientstub.c, which is old and doesn't have all the entry points defined in the latest version, so
    62 // when we're building dns-sd.c on Mac OS X 10.4 or earlier, we automatically set TEST_NEW_CLIENTSTUB so that we'll
    63 // embed a copy of the latest dnssd_clientstub.c instead of trying to link to the incomplete version in libSystem.dylib
    64 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1040
    65 #define TEST_NEW_CLIENTSTUB 1
    66 #endif
    67 
    6860#include <ctype.h>
    6961#include <stdio.h>          // For stdout, stderr
     
    184176#if _DNS_SD_LIBDISPATCH
    185177#include <dispatch/private.h>
    186 #endif
    187 
    188 // The "+0" is to cope with the case where _DNS_SD_H is defined but empty (e.g. on Mac OS X 10.4 and earlier)
    189 #if _DNS_SD_H+0 >= 116
    190 #define HAS_NAT_PMP_API 1
    191 #define HAS_ADDRINFO_API 1
    192 #else
    193 #define kDNSServiceFlagsReturnIntermediates 0
    194178#endif
    195179
     
    422406}
    423407
    424 #if HAS_NAT_PMP_API | HAS_ADDRINFO_API
    425408static DNSServiceProtocol GetProtocol(const char *s)
    426409{
     
    435418    else return(atoi(s));
    436419}
    437 #endif
    438420
    439421
     
    495477    fprintf(stderr, "%s -D <name> <rrtype> <rrclass>(Validate query for any record type with DNSSEC)\n", arg0);
    496478    fprintf(stderr, "%s -Z        <Type> <Domain>               (Output results in Zone File format)\n", arg0);
    497 #if HAS_ADDRINFO_API
    498479    fprintf(stderr, "%s -G     v4/v6/v4v6 <name>              (Get address information for hostname)\n", arg0);
    499480    fprintf(stderr, "%s -g v4/v6/v4v6 <name>        (Validate address info for hostname with DNSSEC)\n", arg0);
    500 #endif
    501481    fprintf(stderr, "%s -V                (Get version of currently running daemon / system service)\n", arg0);
    502482
     
    504484    {
    505485        fprintf(stderr, "%s -C <FQDN> <rrtype> <rrclass>               (Query; reconfirming each result)\n", arg0);
    506 #if HAS_NAT_PMP_API
    507486        fprintf(stderr, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL>               (NAT Port Mapping)\n", arg0);
    508 #endif
    509487        fprintf(stderr, "%s -A                                  (Test Adding/Updating/Deleting a record)\n", arg0);
    510488        fprintf(stderr, "%s -U                                              (Test updating a TXT record)\n", arg0);
     
    10421020                case kDNSServiceType_PTR:
    10431021                case kDNSServiceType_DNAME:
    1044                     p += snprintd(p, sizeof(rdb), &rd);
     1022                    snprintd(p, sizeof(rdb), &rd);
    10451023                    break;
    10461024
     
    10491027                    p += snprintf(p, rdb + sizeof(rdb) - p, " ");
    10501028                    p += snprintd(p, rdb + sizeof(rdb) - p, &rd);           // rname
    1051                     p += snprintf(p, rdb + sizeof(rdb) - p, " Ser %d Ref %d Ret %d Exp %d Min %d",
    1052                           ntohl(((uint32_t*)rd)[0]), ntohl(((uint32_t*)rd)[1]), ntohl(((uint32_t*)rd)[2]), ntohl(((uint32_t*)rd)[3]), ntohl(((uint32_t*)rd)[4]));
     1029                        snprintf(p, rdb + sizeof(rdb) - p, " Ser %d Ref %d Ret %d Exp %d Min %d",
     1030                             ntohl(((uint32_t*)rd)[0]), ntohl(((uint32_t*)rd)[1]), ntohl(((uint32_t*)rd)[2]), ntohl(((uint32_t*)rd)[3]), ntohl(((uint32_t*)rd)[4]));
    10531031                    break;
    10541032
     
    10611039                case kDNSServiceType_SRV:
    10621040                    p += snprintf(p, rdb + sizeof(rdb) - p, "%d %d %d ",        // priority, weight, port
    1063                           ntohs(*(unsigned short*)rd), ntohs(*(unsigned short*)(rd+2)), ntohs(*(unsigned short*)(rd+4)));
     1041                             ntohs(*(unsigned short*)rd), ntohs(*(unsigned short*)(rd+2)), ntohs(*(unsigned short*)(rd+4)));
    10641042                    rd += 6;
    1065                     p += snprintd(p, rdb + sizeof(rdb) - p, &rd);               // target host
     1043                        snprintd(p, rdb + sizeof(rdb) - p, &rd);               // target host
    10661044                    break;
    10671045
     
    11251103}
    11261104
    1127 #if HAS_NAT_PMP_API
    11281105static void DNSSD_API port_mapping_create_reply(DNSServiceRef sdref, DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode, uint32_t publicAddress, uint32_t protocol, uint16_t privatePort, uint16_t publicPort, uint32_t ttl, void *context)
    11291106{
     
    11471124    if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
    11481125}
    1149 #endif
    1150 
    1151 #if HAS_ADDRINFO_API
     1126
    11521127static void DNSSD_API addrinfo_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context)
    11531128{
     
    12191194        fflush(stdout);
    12201195}
    1221 #endif
    12221196
    12231197//*************************************************************************************************************
     
    13631337    // DNSServiceCreateConnection() is called before getip() is.
    13641338    struct sockaddr_storage hostaddr;
     1339    memset(&hostaddr, 0, sizeof(hostaddr));
    13651340    getip(ip, &hostaddr);
    13661341    flags |= kDNSServiceFlagsUnique;
     
    15541529    if (argc < 2) goto Fail;        // Minimum command line is the command name and one argument
    15551530    operation = getfirstoption(argc, argv, "EFBZLlRPQqCAUNTMISVHhD"
    1556                                 #if HAS_NAT_PMP_API
    15571531                               "X"
    1558                                 #endif
    1559                                 #if HAS_ADDRINFO_API
    15601532                               "Gg"
    1561                                 #endif
    15621533                               , &opi);
    15631534    if (operation == -1) goto Fail;
     
    15931564        printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
    15941565        err = DNSServiceCreateConnection(&client);
     1566        if (err) { fprintf(stderr, "DNSServiceCreateConnection returned %d\n", err); return(err); }
    15951567        sc1 = client;
    15961568        err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, typ, dom, zonedata_browse, NULL);
     
    16951667    }
    16961668
    1697 #if HAS_NAT_PMP_API
    16981669    case 'X':   {
    16991670        if (argc == opi)                // If no arguments, just fetch IP address
     
    17121683        break;
    17131684    }
    1714 #endif
    1715 
    1716 #if HAS_ADDRINFO_API
     1685
    17171686    case 'g':
    17181687    case 'G':   {
     
    17321701        break;
    17331702    }
    1734 #endif
    17351703
    17361704    case 'S':   {
  • mDNSResponder/Clients/dnsctl.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Inc. All rights reserved.
     3 * Copyright (c) 2012-2015 Apple Inc. All rights reserved.
    44 *
    55 * dnsctl.c
     
    3232//*************************************************************************************************************
    3333
    34 static void printtimestamp(void) 
     34static void printtimestamp(void)
    3535{
    36     struct tm tm; 
    37     int ms; 
     36    struct tm tm;
     37    int ms;
    3838    static char date[16];
    3939    static char new_date[16];
    40     struct timeval tv; 
     40    struct timeval tv;
    4141    gettimeofday(&tv, NULL);
    4242    localtime_r((time_t*)&tv.tv_sec, &tm);
     
    4545    //display date only if it has changed
    4646    if (strncmp(date, new_date, sizeof(new_date)))
    47     {       
     47    {
    4848        printf("DATE: ---%s---\n", new_date);
    49         strncpy(date, new_date, sizeof(date));
    50     }       
    51     printf("%2d:%02d:%02d.%03d  ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms); 
     49        strlcpy(date, new_date, sizeof(date));
     50    }
     51    printf("%2d:%02d:%02d.%03d  ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms);
    5252}
    5353
     
    7070    switch (errCode)
    7171    {
    72         case kDNSX_NoError          :  printf("  SUCCESS   \n");     break;
    73         case kDNSX_DictError        :  printf(" DICT ERROR \n");     break;
     72        case kDNSX_NoError          :  printf("  SUCCESS   \n");
     73            break;
    7474        case kDNSX_DaemonNotRunning :  printf(" NO DAEMON  \n");
    75                                        DNSXRefDeAlloc(ClientRef);    break;
    76         case kDNSX_Engaged          :  printf(" ENGAGED    \n");
    77                                        DNSXRefDeAlloc(ClientRef);    break;
     75            DNSXRefDeAlloc(ClientRef);    break;
     76        case kDNSX_BadParam          :  printf(" BAD PARAMETER \n");
     77            DNSXRefDeAlloc(ClientRef);    break;
    7878        case kDNSX_UnknownErr       :
    79         default                     :  printf("UNKNOWN ERR \n");
    80                                        DNSXRefDeAlloc(ClientRef);    break;
     79        default                     :  printf(" UNKNOWN ERR \n");
     80            DNSXRefDeAlloc(ClientRef);    break;
    8181    }
    8282    fflush(NULL);
    83 
     83   
    8484}
    8585
     
    8989{
    9090    DNSXErrorType err;
    91 
     91   
    9292    // Default i/p intf is lo0 and o/p intf is primary interface
    9393    IfIndex Ipintfs[MaxInputIf] =  {1, 0, 0, 0, 0};
    9494    IfIndex Opintf = kDNSIfindexAny;
    95 
     95   
    9696    // Extract program name from argv[0], which by convention contains the path to this executable
    97     const char *a0 = strrchr(argv[0], kFilePathSep) + 1; 
     97    const char *a0 = strrchr(argv[0], kFilePathSep) + 1;
    9898    if (a0 == (const char *)1)
    9999        a0 = argv[0];
    100 
     100   
    101101    // Must run as root
    102     if (0 != geteuid()) 
    103     {       
    104         fprintf(stderr, "%s MUST run as root!!\n", a0); 
    105         exit(-1); 
     102    if (0 != geteuid())
     103    {
     104        fprintf(stderr, "%s MUST run as root!!\n", a0);
     105        exit(-1);
    106106    }
    107107    if ((sizeof(argv) == 8))
     
    109109    else if ((sizeof(argv) == 4))
    110110        printf("dnsctl running in 32-bit mode\n");
    111 
     111   
    112112    // expects atleast one argument
    113113    if (argc < 2)
    114114        goto Usage;
    115 
     115   
    116116    if ( !strcmp(argv[1], "-DP") || !strcmp(argv[1], "-dp") )
    117117    {
     
    119119        {
    120120            printtimestamp();
    121             printf("Proceeding to Enable DNSProxy on mDNSResponder with Default Parameters\n");
     121            printf("Enabling DNSProxy on mDNSResponder with Default Parameters\n");
    122122            dispatch_queue_t my_Q = dispatch_queue_create("com.apple.dnsctl.callback_queue", NULL);
    123123            err = DNSXEnableProxy(&ClientRef, kDNSProxyEnable, Ipintfs, Opintf, my_Q, dnsproxy_reply);
    124         }           
     124            if (err) fprintf(stderr, "DNSXEnableProxy returned %d\n", err);
     125        }
    125126        else if (argc > 2)
    126127        {
     
    130131            {
    131132                Opintf = if_nametoindex(argv[2]);
    132                 if (!Opintf) 
     133                if (!Opintf)
    133134                    Opintf = atoi(argv[2]);
    134                 if (!Opintf) 
    135                 { 
    136                     fprintf(stderr, "Could not parse o/p interface [%s]: Passing default primary \n", argv[2]); 
     135                if (!Opintf)
     136                {
     137                    fprintf(stderr, "Could not parse o/p interface [%s]: Passing default primary \n", argv[2]);
    137138                    Opintf = kDNSIfindexAny;
    138139                }
     
    140141                argv += 2;
    141142            }
    142             if (argc > 2 && !strcmp(argv[1], "-i")) 
     143            if (argc > 2 && !strcmp(argv[1], "-i"))
    143144            {
    144145                int i;
     
    149150                    Ipintfs[i] = if_nametoindex(argv[1]);
    150151                    if (!Ipintfs[i])
    151                         Ipintfs[i] = atoi(argv[1]); 
     152                        Ipintfs[i] = atoi(argv[1]);
    152153                    if (!Ipintfs[i])
    153154                    {
    154                         fprintf(stderr, "Could not parse i/p interface [%s]: Passing default lo0 \n", argv[2]); 
     155                        fprintf(stderr, "Could not parse i/p interface [%s]: Passing default lo0 \n", argv[2]);
    155156                        Ipintfs[i] = 1;
    156157                    }
     
    158159                    argv++;
    159160                }
    160             } 
     161            }
    161162            printtimestamp();
    162             printf("Proceeding to Enable DNSProxy on mDNSResponder \n");
     163            printf("Enabling DNSProxy on mDNSResponder \n");
    163164            dispatch_queue_t my_Q = dispatch_queue_create("com.apple.dnsctl.callback_queue", NULL);
    164             err = DNSXEnableProxy(&ClientRef, kDNSProxyEnable, Ipintfs, Opintf, my_Q, dnsproxy_reply);               
     165            err = DNSXEnableProxy(&ClientRef, kDNSProxyEnable, Ipintfs, Opintf, my_Q, dnsproxy_reply);
     166            if (err) fprintf(stderr, "DNSXEnableProxy returned %d\n", err);
    165167        }
    166168    }
     
    169171        goto Usage;
    170172    }
    171 
    172     dispatch_main(); 
    173 
     173   
     174    dispatch_main();
     175   
    174176Usage:
    175177    print_usage(a0);
  • mDNSResponder/Makefile

    r49ebc73 rf761b29  
    1717include $(MAKEFILEPATH)/pb_makefiles/platform.make
    1818
    19 MVERS = "mDNSResponder-576.30.4"
     19MVERS = "mDNSResponder-625.41.2"
    2020
    2121DDNSWRITECONFIG = "$(DSTROOT)/Library/Application Support/Bonjour/ddnswriteconfig"
  • mDNSResponder/mDNSCore/CryptoAlg.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSCore/CryptoAlg.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#ifndef __CRYPTO_ALG_H
    1819#define __CRYPTO_ALG_H
  • mDNSResponder/mDNSCore/DNSCommon.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2013 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    514514
    515515        len = DomainNameLength((domainname *)&rrsig->signerName);
    516         length += baseEncode(buffer + length, RemSpc, (const mDNSu8 *)(rd->data + len + RRSIG_FIXED_SIZE),
     516        baseEncode(buffer + length, RemSpc, (const mDNSu8 *)(rd->data + len + RRSIG_FIXED_SIZE),
    517517                               rr->rdlength - (len + RRSIG_FIXED_SIZE), ENC_BASE64);
    518518    }
     
    522522        length += mDNS_snprintf(buffer+length, RemSpc, "\t%d  %d  %s  %u ", swap16(rrkey->flags), rrkey->proto,
    523523                                DNSSECAlgName(rrkey->alg), (unsigned int)keytag((mDNSu8 *)rrkey, rr->rdlength));
    524         length += baseEncode(buffer + length, RemSpc, (const mDNSu8 *)(rd->data + DNSKEY_FIXED_SIZE),
     524        baseEncode(buffer + length, RemSpc, (const mDNSu8 *)(rd->data + DNSKEY_FIXED_SIZE),
    525525                               rr->rdlength - DNSKEY_FIXED_SIZE, ENC_BASE64);
    526526    }
     
    14821482    q->AnonInfo            = mDNSNULL;
    14831483    q->pid                 = mDNSPlatformGetPID();
     1484    q->euid                = 0;
    14841485    q->DisallowPID         = mDNSfalse;
    14851486    q->ServiceID           = -1;
     
    23582359        // For NSEC records, rdlength represents the exact number of bytes
    23592360        // of in memory storage.
    2360         int len = rr->rdlength;
    23612361        mDNSu8 *nsec = (mDNSu8 *)rdb->data;
    23622362        domainname *name = (domainname *)nsec;
    2363         int dlen;
    2364 
    2365         dlen = DomainNameLength(name);
    2366         len -= dlen;
     2363        const int dlen = DomainNameLength(name);
    23672364        nsec += dlen;
    23682365        // This function is called when we are sending a NSEC record as part of mDNS,
     
    23772374            wlen = *(nsec + 1);
    23782375            nsec += 2;                     // Skip the window number and len
    2379             len -= 2;
    23802376
    23812377            // For our simplified use of NSEC synthetic records:
     
    24072403        {
    24082404            int win, wlen;
     2405            int len = rr->rdlength - dlen;
    24092406
    24102407            // Sanity check whether the bitmap is good
     
    26082605
    26092606// for dynamic updates
    2610 mDNSexport mDNSu8 *putUpdateLease(DNSMessage *msg, mDNSu8 *end, mDNSu32 lease)
     2607mDNSexport mDNSu8 *putUpdateLease(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease)
    26112608{
    26122609    AuthRecord rr;
     
    26172614    rr.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
    26182615    rr.resrec.rdata->u.opt[0].u.updatelease = lease;
    2619     end = PutResourceRecordTTLJumbo(msg, end, &msg->h.numAdditionals, &rr.resrec, 0);
    2620     if (!end) { LogMsg("ERROR: putUpdateLease - PutResourceRecordTTL"); return mDNSNULL; }
    2621     return end;
     2616    ptr = PutResourceRecordTTLJumbo(msg, ptr, &msg->h.numAdditionals, &rr.resrec, 0);
     2617    if (!ptr) { LogMsg("ERROR: putUpdateLease - PutResourceRecordTTL"); return mDNSNULL; }
     2618    return ptr;
    26222619}
    26232620
    26242621// for dynamic updates
    2625 mDNSexport mDNSu8 *putUpdateLeaseWithLimit(DNSMessage *msg, mDNSu8 *end, mDNSu32 lease, mDNSu8 *limit)
     2622mDNSexport mDNSu8 *putUpdateLeaseWithLimit(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease, mDNSu8 *limit)
    26262623{
    26272624    AuthRecord rr;
     
    26322629    rr.resrec.rdata->u.opt[0].opt           = kDNSOpt_Lease;
    26332630    rr.resrec.rdata->u.opt[0].u.updatelease = lease;
    2634     end = PutResourceRecordTTLWithLimit(msg, end, &msg->h.numAdditionals, &rr.resrec, 0, limit);
    2635     if (!end) { LogMsg("ERROR: putUpdateLease - PutResourceRecordTTLWithLimit"); return mDNSNULL; }
    2636     return end;
     2631    ptr = PutResourceRecordTTLWithLimit(msg, ptr, &msg->h.numAdditionals, &rr.resrec, 0, limit);
     2632    if (!ptr) { LogMsg("ERROR: putUpdateLeaseWithLimit - PutResourceRecordTTLWithLimit"); return mDNSNULL; }
     2633    return ptr;
    26372634}
    26382635
     
    26512648    ttl |= 0x8000;
    26522649    end = PutResourceRecordTTLWithLimit(msg, end, &msg->h.numAdditionals, &rr.resrec, ttl, limit);
    2653     if (!end) { LogMsg("ERROR: putUpdateLease - PutResourceRecordTTLWithLimit"); return mDNSNULL; }
     2650    if (!end) { LogMsg("ERROR: putDNSSECOption - PutResourceRecordTTLWithLimit"); return mDNSNULL; }
    26542651    return end;
    26552652}
     
    34423439
    34433440    if (largecr == &m->rec && m->rec.r.resrec.RecordType)
    3444     {
    3445         LogMsg("GetLargeResourceRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
    3446 #if ForceAlerts
    3447         *(long*)0 = 0;
    3448 #endif
    3449     }
     3441        LogFatalError("GetLargeResourceRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
    34503442
    34513443    rr->next              = mDNSNULL;
     
    37143706    ptr = DumpRecords(m, msg, ptr, end, msg->h.numAnswers,     IsUpdate ? "Prerequisites" : "Answers");
    37153707    ptr = DumpRecords(m, msg, ptr, end, msg->h.numAuthorities, IsUpdate ? "Updates"       : "Authorities");
    3716     ptr = DumpRecords(m, msg, ptr, end, msg->h.numAdditionals, "Additionals");
     3708          DumpRecords(m, msg, ptr, end, msg->h.numAdditionals, "Additionals");
    37173709    LogMsg("--------------");
    37183710}
     
    37263718// Stub definition of TCPSocket_struct so we can access flags field. (Rest of TCPSocket_struct is platform-dependent.)
    37273719struct TCPSocket_struct { TCPSocketFlags flags; /* ... */ };
    3728 
    3729 struct UDPSocket_struct
    3730 {
    3731     mDNSIPPort port; // MUST BE FIRST FIELD -- mDNSCoreReceive expects every UDPSocket_struct to begin with mDNSIPPort port
    3732 };
     3720// Stub definition of UDPSocket_struct so we can access port field. (Rest of UDPSocket_struct is platform-dependent.)
     3721struct UDPSocket_struct { mDNSIPPort     port;  /* ... */ };
    37333722
    37343723// Note: When we sign a DNS message using DNSDigest_SignMessage(), the current real-time clock value is used, which
     
    38453834    // If mDNS_busy != mDNS_reentrancy that's a bad sign
    38463835    if (m->mDNS_busy != m->mDNS_reentrancy)
    3847     {
    3848         LogMsg("%s: mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", functionname, m->mDNS_busy, m->mDNS_reentrancy);
    3849 #if ForceAlerts
    3850         *(long*)0 = 0;
    3851 #endif
    3852     }
     3836        LogFatalError("%s: mDNS_Lock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", functionname, m->mDNS_busy, m->mDNS_reentrancy);
    38533837
    38543838    // If this is an initial entry into the mDNSCore code, set m->timenow
     
    39313915}
    39323916
     3917#define LogTSE TSE++,LogMsg
     3918
    39333919mDNSexport void ShowTaskSchedulingError(mDNS *const m)
    39343920{
     3921    int TSE = 0;
    39353922    AuthRecord *rr;
    39363923    mDNS_Lock(m);
    39373924
    3938     LogMsg("Task Scheduling Error: Continuously busy for more than a second");
     3925    LogMsg("Task Scheduling Error: *** Continuously busy for more than a second");
    39393926
    39403927    // Note: To accurately diagnose *why* we're busy, the debugging code here needs to mirror the logic in GetNextScheduledEvent above
    39413928
    39423929    if (m->NewQuestions && (!m->NewQuestions->DelayAnswering || m->timenow - m->NewQuestions->DelayAnswering >= 0))
    3943         LogMsg("Task Scheduling Error: NewQuestion %##s (%s)",
     3930        LogTSE("Task Scheduling Error: NewQuestion %##s (%s)",
    39443931               m->NewQuestions->qname.c, DNSTypeName(m->NewQuestions->qtype));
    39453932
    39463933    if (m->NewLocalOnlyQuestions)
    3947         LogMsg("Task Scheduling Error: NewLocalOnlyQuestions %##s (%s)",
     3934        LogTSE("Task Scheduling Error: NewLocalOnlyQuestions %##s (%s)",
    39483935               m->NewLocalOnlyQuestions->qname.c, DNSTypeName(m->NewLocalOnlyQuestions->qtype));
    39493936
     
    39513938    {
    39523939        rr = AnyLocalRecordReady(m);
    3953         if (rr) LogMsg("Task Scheduling Error: NewLocalRecords %s", ARDisplayString(m, rr));
    3954     }
    3955 
    3956     if (m->NewLocalOnlyRecords) LogMsg("Task Scheduling Error: NewLocalOnlyRecords");
    3957 
    3958     if (m->SPSProxyListChanged) LogMsg("Task Scheduling Error: SPSProxyListChanged");
    3959     if (m->LocalRemoveEvents) LogMsg("Task Scheduling Error: LocalRemoveEvents");
    3960 
    3961     if (m->timenow - m->NextScheduledEvent    >= 0)
    3962         LogMsg("Task Scheduling Error: m->NextScheduledEvent %d",    m->timenow - m->NextScheduledEvent);
     3940        if (rr) LogTSE("Task Scheduling Error: NewLocalRecords %s", ARDisplayString(m, rr));
     3941    }
     3942
     3943    if (m->NewLocalOnlyRecords) LogTSE("Task Scheduling Error: NewLocalOnlyRecords");
     3944
     3945    if (m->SPSProxyListChanged) LogTSE("Task Scheduling Error: SPSProxyListChanged");
     3946
     3947    if (m->LocalRemoveEvents) LogTSE("Task Scheduling Error: LocalRemoveEvents");
    39633948
    39643949#ifndef UNICAST_DISABLED
    39653950    if (m->timenow - m->NextuDNSEvent         >= 0)
    3966         LogMsg("Task Scheduling Error: m->NextuDNSEvent %d",         m->timenow - m->NextuDNSEvent);
     3951        LogTSE("Task Scheduling Error: m->NextuDNSEvent %d",         m->timenow - m->NextuDNSEvent);
    39673952    if (m->timenow - m->NextScheduledNATOp    >= 0)
    3968         LogMsg("Task Scheduling Error: m->NextScheduledNATOp %d",    m->timenow - m->NextScheduledNATOp);
     3953        LogTSE("Task Scheduling Error: m->NextScheduledNATOp %d",    m->timenow - m->NextScheduledNATOp);
    39693954    if (m->NextSRVUpdate && m->timenow - m->NextSRVUpdate >= 0)
    3970         LogMsg("Task Scheduling Error: m->NextSRVUpdate %d",         m->timenow - m->NextSRVUpdate);
     3955        LogTSE("Task Scheduling Error: m->NextSRVUpdate %d",         m->timenow - m->NextSRVUpdate);
    39713956#endif
    39723957
    39733958    if (m->timenow - m->NextCacheCheck        >= 0)
    3974         LogMsg("Task Scheduling Error: m->NextCacheCheck %d",        m->timenow - m->NextCacheCheck);
     3959        LogTSE("Task Scheduling Error: m->NextCacheCheck %d",        m->timenow - m->NextCacheCheck);
    39753960    if (m->timenow - m->NextScheduledSPS      >= 0)
    3976         LogMsg("Task Scheduling Error: m->NextScheduledSPS %d",      m->timenow - m->NextScheduledSPS);
     3961        LogTSE("Task Scheduling Error: m->NextScheduledSPS %d",      m->timenow - m->NextScheduledSPS);
    39773962    if (m->timenow - m->NextScheduledKA       >= 0)
    3978         LogMsg("Task Scheduling Error: m->NextScheduledKA %d",      m->timenow - m->NextScheduledKA);
     3963        LogTSE("Task Scheduling Error: m->NextScheduledKA %d",      m->timenow - m->NextScheduledKA);
    39793964    if (!m->DelaySleep && m->SleepLimit && m->timenow - m->NextScheduledSPRetry >= 0)
    3980         LogMsg("Task Scheduling Error: m->NextScheduledSPRetry %d",  m->timenow - m->NextScheduledSPRetry);
     3965        LogTSE("Task Scheduling Error: m->NextScheduledSPRetry %d",  m->timenow - m->NextScheduledSPRetry);
    39813966    if (m->DelaySleep && m->timenow - m->DelaySleep >= 0)
    3982         LogMsg("Task Scheduling Error: m->DelaySleep %d",            m->timenow - m->DelaySleep);
     3967        LogTSE("Task Scheduling Error: m->DelaySleep %d",            m->timenow - m->DelaySleep);
    39833968
    39843969    if (m->SuppressSending && m->timenow - m->SuppressSending >= 0)
    3985         LogMsg("Task Scheduling Error: m->SuppressSending %d",       m->timenow - m->SuppressSending);
     3970        LogTSE("Task Scheduling Error: m->SuppressSending %d",       m->timenow - m->SuppressSending);
    39863971    if (m->timenow - m->NextScheduledQuery    >= 0)
    3987         LogMsg("Task Scheduling Error: m->NextScheduledQuery %d",    m->timenow - m->NextScheduledQuery);
     3972        LogTSE("Task Scheduling Error: m->NextScheduledQuery %d",    m->timenow - m->NextScheduledQuery);
    39883973    if (m->timenow - m->NextScheduledProbe    >= 0)
    3989         LogMsg("Task Scheduling Error: m->NextScheduledProbe %d",    m->timenow - m->NextScheduledProbe);
     3974        LogTSE("Task Scheduling Error: m->NextScheduledProbe %d",    m->timenow - m->NextScheduledProbe);
    39903975    if (m->timenow - m->NextScheduledResponse >= 0)
    3991         LogMsg("Task Scheduling Error: m->NextScheduledResponse %d", m->timenow - m->NextScheduledResponse);
     3976        LogTSE("Task Scheduling Error: m->NextScheduledResponse %d", m->timenow - m->NextScheduledResponse);
     3977    if (m->timenow - m->NextScheduledStopTime >= 0)
     3978        LogTSE("Task Scheduling Error: m->NextScheduledStopTime %d", m->timenow - m->NextScheduledStopTime);
     3979
     3980    if (m->timenow - m->NextScheduledEvent    >= 0)
     3981        LogTSE("Task Scheduling Error: m->NextScheduledEvent %d",    m->timenow - m->NextScheduledEvent);
     3982
     3983    if (m->NetworkChanged && m->timenow - m->NetworkChanged >= 0)
     3984        LogTSE("Task Scheduling Error: NetworkChanged %d",           m->timenow - m->NetworkChanged);
     3985
     3986    if (!TSE) LogMsg("Task Scheduling Error: *** No likely causes identified");
     3987    else LogMsg("Task Scheduling Error: *** %d potential cause%s identified (significant only if the same cause consistently appears)", TSE, TSE > 1 ? "s" : "");
    39923988
    39933989    mDNS_Unlock(m);
    39943990}
    39953991
    3996 mDNSexport void mDNS_Unlock_(mDNS *const m, const char * const functionname)
     3992mDNSexport void mDNS_Unlock_(mDNS *const m, const char *const functionname)
    39973993{
    39983994    // Decrement mDNS_busy
     
    40013997    // Check for locking failures
    40023998    if (m->mDNS_busy != m->mDNS_reentrancy)
    4003     {
    4004         LogMsg("%s: mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", functionname, m->mDNS_busy, m->mDNS_reentrancy);
    4005 #if ForceAlerts
    4006         *(long*)0 = 0;
    4007 #endif
    4008     }
     3999        LogFatalError("%s: mDNS_Unlock: Locking failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", functionname, m->mDNS_busy, m->mDNS_reentrancy);
    40094000
    40104001    // If this is a final exit from the mDNSCore code, set m->NextScheduledEvent and clear m->timenow
  • mDNSResponder/mDNSCore/DNSCommon.h

    r49ebc73 rf761b29  
    221221extern mDNSu8 *putDeleteRRSetWithLimit(DNSMessage *msg, mDNSu8 *ptr, const domainname *name, mDNSu16 rrtype, mDNSu8 *limit);
    222222extern mDNSu8 *putDeleteAllRRSets(DNSMessage *msg, mDNSu8 *ptr, const domainname *name);
    223 extern mDNSu8 *putUpdateLease(DNSMessage *msg, mDNSu8 *end, mDNSu32 lease);
     223extern mDNSu8 *putUpdateLease(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease);
    224224extern mDNSu8 *putUpdateLeaseWithLimit(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease, mDNSu8 *limit);
    225225
     
    298298#define mDNS_Unlock(X) mDNS_Unlock_((X), __func__)
    299299
    300 #define mDNS_CheckLock(X) { if ((X)->mDNS_busy != (X)->mDNS_reentrancy+1) \
    301                             LogMsg("%s: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", __func__, (X)->mDNS_busy, (X)->mDNS_reentrancy); }
     300#define mDNS_CheckLock(X) \
     301    if ((X)->mDNS_busy != (X)->mDNS_reentrancy+1) LogMsg("%s: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", __func__, (X)->mDNS_busy, (X)->mDNS_reentrancy)
    302302
    303303#define mDNS_DropLockBeforeCallback() do { m->mDNS_reentrancy++; \
    304                                            if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Locking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy);                                                                                                                                                                  \
    305 } while (0)
     304    if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Locking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy); \
     305    } while (0)
    306306
    307307#define mDNS_ReclaimLockAfterCallback() do { \
    308         if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Unlocking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy);                                                                                                                                                                    \
    309         m->mDNS_reentrancy--; } while (0)
     308    if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Unlocking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy); \
     309    m->mDNS_reentrancy--; } while (0)
    310310
    311311#ifdef  __cplusplus
  • mDNSResponder/mDNSCore/DNSDigest.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2011 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
    17 
    1817
    1918#ifdef __cplusplus
  • mDNSResponder/mDNSCore/anonymous.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2012-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    2828#define ANON_NSEC3_ITERATIONS        1
    2929
     30struct AnonInfoResourceRecord_struct
     31{
     32    ResourceRecord resrec;
     33    RData          rdatastorage;
     34};
     35
     36typedef struct AnonInfoResourceRecord_struct AnonInfoResourceRecord;
     37
    3038mDNSlocal mDNSBool InitializeNSEC3Record(ResourceRecord *rr, const mDNSu8 *AnonData, int len, mDNSu32 salt)
    3139{
     
    119127mDNSlocal ResourceRecord *CopyNSEC3ResourceRecord(AnonymousInfo *si, const ResourceRecord *rr)
    120128{
    121     int len;
     129    AnonInfoResourceRecord *anonRR;
    122130    domainname *name;
    123     ResourceRecord *nsec3rr;
     131    mDNSu32 neededLen;
     132    mDNSu32 extraLen;
    124133
    125134    if (rr->rdlength < MCAST_NSEC3_RDLENGTH)
     
    129138    }
    130139    // Allocate space for the name and the rdata along with the ResourceRecord
    131     len = DomainNameLength(rr->name);
    132     nsec3rr = mDNSPlatformMemAllocate(sizeof(ResourceRecord) + len + sizeof(RData));
    133     if (!nsec3rr)
    134         return mDNSNULL;
    135 
    136     *nsec3rr = *rr;
    137     name = (domainname *)((mDNSu8 *)nsec3rr + sizeof(ResourceRecord));
    138     nsec3rr->name = (const domainname *)name;
     140    neededLen = rr->rdlength + DomainNameLength(rr->name);
     141    extraLen = (neededLen > sizeof(RDataBody)) ? (neededLen - sizeof(RDataBody)) : 0;
     142    anonRR = (AnonInfoResourceRecord *)mDNSPlatformMemAllocate(sizeof(AnonInfoResourceRecord) + extraLen);
     143    if (!anonRR)
     144        return mDNSNULL;
     145
     146    anonRR->resrec = *rr;
     147
     148    anonRR->rdatastorage.MaxRDLength = rr->rdlength;
     149    mDNSPlatformMemCopy(anonRR->rdatastorage.u.data, rr->rdata->u.data, rr->rdlength);
     150
     151    name = (domainname *)(anonRR->rdatastorage.u.data + rr->rdlength);
    139152    AssignDomainName(name, rr->name);
    140153
    141     nsec3rr->rdata = (RData *)((mDNSu8 *)nsec3rr->name + len);
    142     mDNSPlatformMemCopy(nsec3rr->rdata->u.data, rr->rdata->u.data, rr->rdlength);
    143 
    144     si->nsec3RR = nsec3rr;
    145 
    146     return nsec3rr;
     154    anonRR->resrec.name = name;
     155    anonRR->resrec.rdata = &anonRR->rdatastorage;
     156
     157    si->nsec3RR = (ResourceRecord *)anonRR;
     158
     159    return si->nsec3RR;
    147160}
    148161
  • mDNSResponder/mDNSCore/anonymous.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSCore/dnsproxy.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    8484mDNSlocal mDNSBool ParseEDNS0(DNSProxyClient *pc, const mDNSu8 *ptr, int length, const mDNSu8 *limit)
    8585{
    86     mDNSu16 rrtype, rrclass;
    87     mDNSu8 rcode, version;
    88     mDNSu16 flag;
    89  
    9086    if (ptr + length > limit)
    9187    {
     
    9591    // Skip the root label
    9692    ptr++;
    97     rrtype  = (mDNSu16) ((mDNSu16)ptr[0] <<  8 | ptr[1]);
     93    mDNSu16 rrtype  = (mDNSu16) ((mDNSu16)ptr[0] <<  8 | ptr[1]);
    9894    if (rrtype != kDNSType_OPT)
    9995    {
     
    10197        return mDNSfalse;
    10298    }
    103     rrclass = (mDNSu16) ((mDNSu16)ptr[2] <<  8 | ptr[3]);
    104     rcode   = ptr[4];
    105     version = ptr[5];
    106     flag    = (mDNSu16) ((mDNSu16)ptr[6] << 8 | ptr[7]);
    107 
     99    mDNSu16 rrclass = (mDNSu16) ((mDNSu16)ptr[2] <<  8 | ptr[3]);
     100#if MDNS_DEBUGMSGS
     101    mDNSu8  rcode   = ptr[4];
     102    mDNSu8  version = ptr[5];
     103    mDNSu16 flag    = (mDNSu16) ((mDNSu16)ptr[6] <<  8 | ptr[7]);
    108104    debugf("rrtype is %s, length is %d, rcode %d, version %d, flag 0x%x", DNSTypeName(rrtype), rrclass, rcode, version, flag);
     105#endif
    109106    pc->rcvBufSize = rrclass;
    110107    pc->DNSSECOK = ptr[6] & 0x80;
     
    367364        }
    368365        len += (ptr - orig);
    369         orig = ptr;
     366        // orig = ptr; Commented out to avoid ‘value never read’ error message
    370367    }
    371368    LogInfo("AddResourceRecord: Added %d bytes to the packet", len);
     
    472469        }
    473470    }
     471   
     472    debugf("ProxyClientCallback: InterfaceID is %p for response to client", pc->interfaceID);
    474473
    475474    if (!pc->tcp)
    476475    {
    477         mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, (UDPSocket *)pc->socket, &pc->addr, pc->port, mDNSNULL, mDNSNULL, mDNSfalse);
     476        mDNSSendDNSMessage(m, &m->omsg, ptr, pc->interfaceID, (UDPSocket *)pc->socket, &pc->addr, pc->port, mDNSNULL, mDNSNULL, mDNSfalse);
    478477    }
    479478    else
    480479    {
    481         mDNSSendDNSMessage(m, &m->omsg, ptr, mDNSInterface_Any, mDNSNULL, &pc->addr, pc->port, (TCPSocket *)pc->socket, mDNSNULL, mDNSfalse);
     480        mDNSSendDNSMessage(m, &m->omsg, ptr, pc->interfaceID, mDNSNULL, &pc->addr, pc->port, (TCPSocket *)pc->socket, mDNSNULL, mDNSfalse);
    482481    }
    483482
     
    502501    int pktlen = (int)(end - (mDNSu8 *)pkt);
    503502    DNSMessage  *msg  = (DNSMessage *)pkt;
    504 
    505     (void) InterfaceID;
    506503
    507504    // RFC 1035 requires that we copy the question back and RFC 2136 is okay with sending nothing
     
    518515    if (!tcp)
    519516    {
    520         mDNSSendDNSMessage(m, &m->omsg, (mDNSu8 *)&m->omsg + pktlen, mDNSInterface_Any, socket, dstaddr, dstport, mDNSNULL, mDNSNULL,
     517        mDNSSendDNSMessage(m, &m->omsg, (mDNSu8 *)&m->omsg + pktlen, InterfaceID, socket, dstaddr, dstport, mDNSNULL, mDNSNULL,
    521518            mDNSfalse);
    522519    }
    523520    else
    524521    {
    525         mDNSSendDNSMessage(m, &m->omsg, (mDNSu8 *)&m->omsg + pktlen, mDNSInterface_Any, mDNSNULL, dstaddr, dstport, (TCPSocket *)socket,
     522        mDNSSendDNSMessage(m, &m->omsg, (mDNSu8 *)&m->omsg + pktlen, InterfaceID, mDNSNULL, dstaddr, dstport, (TCPSocket *)socket,
    526523            mDNSNULL, mDNSfalse);
    527524    }
     
    577574    DNSQuestion q, *qptr;
    578575    DNSProxyClient *pc;
    579     const mDNSu8 *optRR;
     576    const mDNSu8 *optRR = mDNSNULL;
    580577    int optLen = 0;
    581578    DNSProxyClient **ppc = &DNSProxyClients;
  • mDNSResponder/mDNSCore/dnsproxy.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#ifndef __DNS_PROXY_H
    1819#define __DNS_PROXY_H
  • mDNSResponder/mDNSCore/dnssec.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#include "mDNSEmbeddedAPI.h"
    1819#include "DNSSECSupport.h"
     
    310311        rvfrom = ae->rrset;
    311312        rvto = &ac->rrset;
    312         while (rvfrom)
     313        while (rvfrom && rvto)
    313314        {
    314315            *rvto = CopyRRVerifier(rvfrom);
     
    319320        rvfrom = ae->rrsig;
    320321        rvto = &ac->rrsig;
    321         while (rvfrom)
     322        while (rvfrom && rvto)
    322323        {
    323324            *rvto = CopyRRVerifier(rvfrom);
     
    328329        rvfrom = ae->key;
    329330        rvto = &ac->key;
    330         while (rvfrom)
     331        while (rvfrom && rvto)
    331332        {
    332333            *rvto = CopyRRVerifier(rvfrom);
     
    10661067    else
    10671068        return mStatus_NoSuchRecord;
    1068     return (dv->ds ? mStatus_NoError : mStatus_NoSuchRecord);
    10691069}
    10701070
     
    23362336    mDNSu32 slot;
    23372337    CacheGroup *cg;
    2338     int sigNameLen, len;
    2339     mDNSu8 *ptr;
    23402338    mDNSu32 rrTTL, rrsigTTL, rrsigOrigTTL, rrsigTimeTTL;
    23412339    domainname *qname;
     
    24012399        rrsigv = dv->ac->rrsig;
    24022400        rrsig = (rdataRRSig *)rrsigv->rdata;
    2403         sigNameLen = DomainNameLength((domainname *)&rrsig->signerName);
    2404         // pointer to signature and the length
    2405         ptr = (mDNSu8 *)(rrsigv->rdata + sigNameLen + RRSIG_FIXED_SIZE);
    2406         len = rrsigv->rdlength - RRSIG_FIXED_SIZE - sigNameLen;
    24072401    }
    24082402    else
     
    24102404        rrsigv = mDNSNULL;
    24112405        rrsig = mDNSNULL;
    2412         ptr = mDNSNULL;
    2413         sigNameLen = len = 0;
    24142406    }
    24152407
     
    31883180mDNSlocal mDNSBool TrustedKeyPresent(mDNS *const m, DNSSECVerifier *dv)
    31893181{
    3190     rdataRRSig *rrsig;
    31913182    rdataDS *ds;
    31923183    rdataDNSKey *key;
    31933184    TrustAnchor *ta;
    31943185    RRVerifier *keyv;
    3195 
    3196     rrsig = (rdataRRSig *)dv->rrsig->rdata;
    31973186
    31983187    // Walk all our trusted DS Records to see if we have a matching DNS KEY record that verifies
  • mDNSResponder/mDNSCore/dnssec.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#ifndef __DNSSEC_H
    1819#define __DNSSEC_H
  • mDNSResponder/mDNSCore/mDNS.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2013 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    4848
    4949#if APPLE_OSX_mDNSResponder
    50 
    5150#include <WebFilterDNS/WebFilterDNS.h>
    5251
     
    6362#define NO_WCF 1
    6463#endif // APPLE_OSX_mDNSResponder
     64
     65#if TARGET_OS_EMBEDDED
     66#include "Metrics.h"
     67#endif
    6568
    6669// Forward declarations
     
    8184mDNSlocal void mDNSParseNSEC3Records(mDNS *const m, const DNSMessage *const response, const mDNSu8 *end,
    8285                                        const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records);
     86mDNSlocal mDNSu8 *GetValueForMACAddr(mDNSu8 *ptr, mDNSu8 *limit, mDNSEthAddr *eth);
    8387
    8488
     
    147151    mDNS_CheckLock(m);
    148152
    149 #if ForceAlerts
    150     if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
    151 #endif
    152 
    153153    if (m->NextScheduledStopTime - q->StopTime > 0)
    154154        m->NextScheduledStopTime = q->StopTime;
     
    158158{
    159159    mDNS_CheckLock(m);
    160 
    161 #if ForceAlerts
    162     if (m->mDNS_busy != m->mDNS_reentrancy+1) *(long*)0 = 0;
    163 #endif
    164160
    165161    if (ActiveQuestion(q))
     
    353349}
    354350
    355 mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr, mDNSBool *myself)
     351mDNSexport mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr)
    356352{
    357353    NetworkInterfaceInfo *intf;
     
    364360            if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
    365361                if (((intf->ip.ip.v4.NotAnInteger ^ addr->ip.v4.NotAnInteger) & intf->mask.ip.v4.NotAnInteger) == 0)
    366                 {
    367                     if (myself)
    368                     {
    369                         if (mDNSSameIPv4Address(intf->ip.ip.v4, addr->ip.v4))
    370                             *myself = mDNStrue;
    371                         else
    372                             *myself = mDNSfalse;
    373                         if (*myself)
    374                             debugf("mDNS_AddressIsLocalSubnet: IPv4 %#a returning true", addr);
    375                         else
    376                             debugf("mDNS_AddressIsLocalSubnet: IPv4 %#a returning false", addr);
    377                     }
    378362                    return(mDNStrue);
    379                 }
    380363    }
    381364
    382365    if (addr->type == mDNSAddrType_IPv6)
    383366    {
     367        if (mDNSv6AddressIsLinkLocal(&addr->ip.v6)) return(mDNStrue);
    384368        for (intf = m->HostInterfaces; intf; intf = intf->next)
    385369            if (intf->ip.type == addr->type && intf->InterfaceID == InterfaceID && intf->McastTxRx)
     
    388372                    (((intf->ip.ip.v6.l[2] ^ addr->ip.v6.l[2]) & intf->mask.ip.v6.l[2]) == 0) &&
    389373                    (((intf->ip.ip.v6.l[3] ^ addr->ip.v6.l[3]) & intf->mask.ip.v6.l[3]) == 0))
    390                     {
    391                         if (myself)
    392                         {
    393                             if (mDNSSameIPv6Address(intf->ip.ip.v6, addr->ip.v6))
    394                                 *myself = mDNStrue;
    395                             else
    396                                 *myself = mDNSfalse;
    397                             if (*myself)
    398                                 debugf("mDNS_AddressIsLocalSubnet: IPv6 %#a returning true", addr);
    399                             else
    400                                 debugf("mDNS_AddressIsLocalSubnet: IPv6 %#a returning false", addr);
    401                         }
    402374                        return(mDNStrue);
    403                     }
    404375    }
    405376
     
    476447        UDPSocket *sock = q->LocalSocket;
    477448        mDNSOpaque16 id = q->TargetQID;
     449#if TARGET_OS_EMBEDDED
     450        domainname *originalQName;
     451#endif
    478452
    479453        // if there is a message waiting at the socket, we want to process that instead
     
    481455        // both A and AAAA question and while answering it we don't want to throw
    482456        // away the response where the actual addresses are present.
     457        // This is a stupid hack and we should get rid of it.
     458        // The chance of there being a second unicast UDP packet already waiting in the kernel before we’ve
     459        // finished processing the previous one is virtually nil, and will only happen by luck on very rare
     460        // occasions when running on a machine with a fast network connection and a slow or busy processor.
     461        // The idea that we’d rely for correctness on this random chance event occurring is ridiculous.
     462        // -- SC
    483463        if (mDNSPlatformPeekUDP(m, q->LocalSocket))
    484464        {
     
    509489                q, q->qname.c, DNSTypeName(q->qtype), q->CNAMEReferrals, RRDisplayString(m, rr));
    510490
     491#if TARGET_OS_EMBEDDED
     492        if (q->metrics.originalQName)
     493        {
     494            originalQName            = q->metrics.originalQName;
     495            q->metrics.originalQName = mDNSNULL;
     496        }
     497        else
     498        {
     499            mDNSu16 qNameLen;
     500
     501            qNameLen = DomainNameLength(&q->qname);
     502            if ((qNameLen > 0) && (qNameLen <= MAX_DOMAIN_NAME))
     503            {
     504                originalQName = mDNSPlatformMemAllocate(qNameLen);
     505                if (originalQName)
     506                {
     507                    mDNSPlatformMemCopy(originalQName->c, q->qname.c, qNameLen);
     508                }
     509            }
     510            else
     511            {
     512                originalQName = mDNSNULL;
     513            }
     514        }
     515#endif
    511516        mDNS_StopQuery_internal(m, q);                              // Stop old query
    512517        AssignDomainName(&q->qname, &rr->rdata->u.name);            // Update qname
     
    525530        // because mDNS_StartQuery_internal re-initializes CNAMEReferrals to zero
    526531        q->CNAMEReferrals = c;
     532#if TARGET_OS_EMBEDDED
     533        q->metrics.originalQName = originalQName;
     534#endif
    527535        if (sock)
    528536        {
     
    934942        const domainname *const n = SetUnicastTargetToHostName(m, rr);
    935943        if (n) newname = n;
    936         else { target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
     944        else { if (target) target->c[0] = 0; SetNewRData(&rr->resrec, mDNSNULL, 0); return; }
    937945    }
    938946
     
    11341142mDNSlocal void DecrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
    11351143{
     1144    if (RRLocalOnly(rr))
     1145    {
     1146        // A sanity check, this should be prevented in calling code.
     1147        LogInfo("DecrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
     1148        return;
     1149    }
     1150
    11361151    if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
    11371152    {
     1153        // If about to get rid of the last advertised service
     1154        if (m->AutoTargetServices == 1)
     1155            DeadvertiseAllInterfaceRecords(m);
     1156
    11381157        m->AutoTargetServices--;
    1139         LogInfo("DecrementAutoTargetServices: AutoService Record %s, AutoTargetServices %d", ARDisplayString(m, rr), m->AutoTargetServices);
    1140         if (!m->AutoTargetServices)
    1141             DeadvertiseAllInterfaceRecords(m);
    1142     }
     1158        LogInfo("DecrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
     1159    }
     1160
     1161#if TARGET_OS_WATCH
     1162    if (!AuthRecord_uDNS(rr))
     1163    {
     1164        if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
     1165            m->NetworkChanged = m->timenow;
     1166        m->NumAllInterfaceRecords--;
     1167        LogInfo("DecrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
     1168            m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
     1169    }
     1170#endif
    11431171}
    11441172
    11451173mDNSlocal void IncrementAutoTargetServices(mDNS *const m, AuthRecord *const rr)
    11461174{
     1175    if (RRLocalOnly(rr))
     1176    {
     1177        // A sanity check, this should be prevented in calling code.
     1178        LogInfo("IncrementAutoTargetServices: called for RRLocalOnly() record: %s", ARDisplayString(m, rr));
     1179        return;
     1180    }
     1181
     1182#if TARGET_OS_WATCH
     1183    if (!AuthRecord_uDNS(rr))
     1184    {
     1185        m->NumAllInterfaceRecords++;
     1186        LogInfo("IncrementAutoTargetServices: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %s",
     1187            m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, ARDisplayString(m, rr));
     1188        if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
     1189            m->NetworkChanged = m->timenow;
     1190    }
     1191#endif
     1192
    11471193    if (!AuthRecord_uDNS(rr) && rr->resrec.rrtype == kDNSType_SRV && rr->AutoTarget == Target_AutoHost)
    11481194    {
    1149         int count = m->AutoTargetServices;
    1150 
    1151         // Bump up before calling AdvertiseAllInterfaceRecords. AdvertiseInterface
    1152         // returns without doing anything if the count is zero.
    11531195        m->AutoTargetServices++;
    1154         LogInfo("IncrementAutoTargetServices: AutoService Record %s, AutoTargetServices %d", ARDisplayString(m, rr), m->AutoTargetServices);
    1155         if (!count)
     1196        LogInfo("IncrementAutoTargetServices: AutoTargetServices %d Record %s", m->AutoTargetServices, ARDisplayString(m, rr));
     1197        // If this is the first advertised service
     1198        if (m->AutoTargetServices == 1)
    11561199            AdvertiseAllInterfaceRecords(m);
    11571200    }
     
    13791422        // complications and not clear whether there are any benefits. See rdar:9304275 for details.
    13801423        // Hence, just bail out.
     1424        // This comment is doesn’t make any sense. -- SC
    13811425        if (rr->resrec.RecordType & kDNSRecordTypeUniqueMask)
    13821426        {
     
    14441488            AuthGroup *ag;
    14451489            ag = InsertAuthRecord(m, &m->rrauth, rr);
    1446             if (ag && !ag->NewLocalOnlyRecords) {
     1490            if (ag && !ag->NewLocalOnlyRecords)
     1491            {
    14471492                m->NewLocalOnlyRecords = mDNStrue;
    14481493                ag->NewLocalOnlyRecords = rr;
    14491494            }
    1450             // No probing for LocalOnly records, Acknowledge them right away
     1495            // No probing for LocalOnly records; acknowledge them right away
    14511496            if (rr->resrec.RecordType == kDNSRecordTypeUnique) rr->resrec.RecordType = kDNSRecordTypeVerified;
    14521497            AcknowledgeRecord(m, rr);
     
    14601505    }
    14611506
    1462     // If this is a keepalive record, fetch the MAC address of the remote host.
     1507    // If this is a non-sleep proxy keepalive record, fetch the MAC address of the remote host.
    14631508    // This is used by the in-NIC proxy to send the keepalive packets.
    1464     if (mDNS_KeepaliveRecord(&rr->resrec))
    1465     {
     1509    if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
     1510    {
     1511        mDNSAddr raddr;
    14661512        // Set the record type to known unique to prevent probing keep alive records.
    14671513        // Also make sure we do not announce the keepalive records.
    14681514       rr->resrec.RecordType = kDNSRecordTypeKnownUnique;
    14691515       rr->AnnounceCount     = 0;
    1470        mDNSAddr   raddr;
    14711516       getKeepaliveRaddr(m, rr, &raddr);
    14721517       // This is an asynchronous call. Once the remote MAC address is available, helper will schedule an
     
    14771522    if (!AuthRecord_uDNS(rr))   // This check is superfluous, given that for unicast records we (currently) bail out above
    14781523    {
    1479         // We have inserted the record in the list. See if we have to advertise the A/AAAA,HINFO,PTR records.
     1524        // We have inserted the record in the list. See if we have to advertise the A/AAAA, HINFO, PTR records.
    14801525        IncrementAutoTargetServices(m, rr);
     1526
    14811527        // For records that are not going to probe, acknowledge them right away
    14821528        if (rr->resrec.RecordType != kDNSRecordTypeUnique && rr->resrec.RecordType != kDNSRecordTypeDeregistering)
     
    23622408                    SendWakeup(m, rr->resrec.InterfaceID, &rr->WakeUp.IMAC, &rr->WakeUp.password);
    23632409                    for (r2 = rr; r2; r2=r2->next)
    2364                         if (r2->AnnounceCount && r2->resrec.InterfaceID == rr->resrec.InterfaceID && mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) &&
    2365                                 !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
     2410                        if ((r2->resrec.RecordType == kDNSRecordTypeDeregistering) && r2->AnnounceCount && (r2->resrec.InterfaceID == rr->resrec.InterfaceID) &&
     2411                            mDNSSameEthAddress(&r2->WakeUp.IMAC, &rr->WakeUp.IMAC) && !mDNSSameEthAddress(&zeroEthAddr, &r2->WakeUp.HMAC))
    23662412                        {
    23672413                            // For now we only want to send a single Unsolicited Neighbor Advertisement restoring the address to the original
     
    25332579                ((rr->resrec.InterfaceID == mDNSInterface_Any) && !mDNSPlatformValidRecordForInterface(rr, intf)))
    25342580            {
    2535                 LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
     2581                //  LogInfo("SendResponses: Not sending %s, on %s", ARDisplayString(m, rr), InterfaceNameForID(m, rr->SendRNow));
    25362582                rr->SendRNow = GetNextActiveInterfaceID(intf);
    25372583            }
     
    29182964// It also appends to the list of known answer records that need to be included,
    29192965// and updates the forcast for the size of the known answer section.
    2920 mDNSlocal mDNSBool BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
    2921                                  CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
    2922 {
    2923     mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353;
     2966mDNSlocal mDNSBool BuildQuestion(mDNS *const m, const NetworkInterfaceInfo *intf, DNSMessage *query, mDNSu8 **queryptr,
     2967                                 DNSQuestion *q, CacheRecord ***kalistptrptr, mDNSu32 *answerforecast)
     2968{
     2969    mDNSBool ucast = (q->LargeAnswers || q->RequestUnicast) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
    29242970    mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
    29252971    const mDNSu8 *const limit = query->data + NormalMaxDNSMessageData;
     
    30613107}
    30623108
    3063 mDNSlocal void CheckAndSwapSPS(const CacheRecord *sps1, const CacheRecord *sps2)
     3109mDNSlocal void CheckAndSwapSPS(const CacheRecord **sps1, const CacheRecord **sps2)
    30643110{
    30653111    const CacheRecord *swap_sps;
    30663112    mDNSu32 metric1, metric2;
    30673113
    3068     if (!sps1 || !sps2) return;
    3069     metric1 = SPSMetric(sps1->resrec.rdata->u.name.c);
    3070     metric2 = SPSMetric(sps2->resrec.rdata->u.name.c);
    3071     if (!SPSFeatures(sps1->resrec.rdata->u.name.c) && SPSFeatures(sps2->resrec.rdata->u.name.c) && (metric2 >= metric1))
    3072     {
    3073         swap_sps = sps1;
    3074         sps1     = sps2;
    3075         sps2     = swap_sps;
     3114    if (!(*sps1) || !(*sps2)) return;
     3115    metric1 = SPSMetric((*sps1)->resrec.rdata->u.name.c);
     3116    metric2 = SPSMetric((*sps2)->resrec.rdata->u.name.c);
     3117    if (!SPSFeatures((*sps1)->resrec.rdata->u.name.c) && SPSFeatures((*sps2)->resrec.rdata->u.name.c) && (metric2 >= metric1))
     3118    {
     3119        swap_sps = *sps1;
     3120        *sps1    = *sps2;
     3121        *sps2    = swap_sps;
    30763122    }
    30773123}
     
    30793125mDNSlocal void ReorderSPSByFeature(const CacheRecord *sps[3])
    30803126{
    3081     CheckAndSwapSPS(sps[0], sps[1]);
    3082     CheckAndSwapSPS(sps[0], sps[2]);
    3083     CheckAndSwapSPS(sps[1], sps[2]);
     3127    CheckAndSwapSPS(&sps[0], &sps[1]);
     3128    CheckAndSwapSPS(&sps[0], &sps[2]);
     3129    CheckAndSwapSPS(&sps[1], &sps[2]);
    30843130}
    30853131
     
    31253171}
    31263172
    3127 mDNSlocal int RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
     3173mDNSlocal void RecordDupSuppressInfo(DupSuppressInfo ds[DupSuppressInfoSize], mDNSs32 Time, mDNSInterfaceID InterfaceID, mDNSs32 Type)
    31283174{
    31293175    int i, j;
     
    31453191    ds[i].InterfaceID = InterfaceID;
    31463192    ds[i].Type        = Type;
    3147 
    3148     return(i);
    31493193}
    31503194
     
    31643208    // Split MAC@IPAddress and pass them separately
    31653209    len = d->c[0];
    3166     i = 1;
    31673210    cnt = 0;
    31683211    for (i = 1; i < len; i++)
     
    35593602                    // If we're suppressing this question, or we successfully put it, update its SendQNow state
    35603603                    else if ((Suppress = SuppressOnThisInterface(q->DupSuppress, intf)) ||
    3561                         BuildQuestion(m, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
     3604                        BuildQuestion(m, intf, &m->omsg, &queryptr, q, &kalistptr, &answerforecast))
    35623605                    {
    35633606                        // We successfully added the question to the packet. Make sure that
     
    35833626                        }
    35843627
    3585                         // use brackground traffic class if any included question requires it
     3628                        // use background traffic class if any included question requires it
    35863629                        if (q->UseBackgroundTrafficClass)
    35873630                        {
     
    35963639                if (ar->SendRNow == intf->InterfaceID)
    35973640                {
    3598                     mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353;
     3641                    mDNSBool ucast = (ar->ProbeCount >= DefaultProbeCountForTypeUnique-1) && m->CanReceiveUnicastOn5353 && intf->SupportsUnicastMDNSResponse;
    35993642                    mDNSu16 ucbit = (mDNSu16)(ucast ? kDNSQClass_UnicastResponse : 0);
    36003643                    const mDNSu8 *const limit = m->omsg.data + (m->omsg.h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
     
    38943937    }
    38953938
     3939#if TARGET_OS_EMBEDDED
     3940    if ((AddRecord == QC_add) && Question_uDNS(q) && (!q->metrics.answered || (q->metrics.querySendCount > 0)))
     3941    {
     3942        uDNSMetrics *       metrics;
     3943        const domainname *  queryName;
     3944        mDNSu32             responseLatencyMs;
     3945        mDNSBool            isForCellular;
     3946
     3947        metrics   = &q->metrics;
     3948        queryName = metrics->originalQName ? metrics->originalQName : &q->qname;
     3949        if (metrics->querySendCount > 0)
     3950        {
     3951            responseLatencyMs = ((m->timenow - metrics->firstQueryTime) * 1000) / mDNSPlatformOneSecond;
     3952        }
     3953        else
     3954        {
     3955            responseLatencyMs = 0;
     3956        }
     3957        isForCellular = (q->qDNSServer && q->qDNSServer->cellIntf);
     3958
     3959        MetricsUpdateUDNSStats(queryName, mDNStrue, metrics->querySendCount, responseLatencyMs, isForCellular);
     3960        metrics->answered       = mDNStrue;
     3961        metrics->querySendCount = 0;
     3962    }
     3963#endif
    38963964    // Note: Use caution here. In the case of records with rr->DelayDelivery set, AnswerCurrentQuestionWithResourceRecord(... mDNStrue)
    38973965    // may be called twice, once when the record is received, and again when it's time to notify local clients.
     
    48854953// (GetNextScheduledEvent() returns "now" when m->SPSProxyListChanged is set)
    48864954#define SetSPSProxyListChanged(X) do { \
    4887         if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged);                                                                                                                          \
     4955        if (m->SPSProxyListChanged && m->SPSProxyListChanged != (X)) mDNSPlatformUpdateProxyList(m, m->SPSProxyListChanged); \
    48884956        m->SPSProxyListChanged = (X); } while(0)
    48894957
     
    55595627                    }
    55605628
    5561                     // Disallow sleep if there is no sleep proxy server
    5562                     const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
    5563                     if ( cr == mDNSNULL)
     5629                    // If the interface can be an in-NIC Proxy, we should check if it can accomodate all the records
     5630                    // that will be offloaded. If not, we should prevent sleep.
     5631                    // This check will be possible once the lower layers provide an API to query the space available for offloads on the NIC.
     5632#if APPLE_OSX_mDNSResponder
     5633                    if (!SupportsInNICProxy(intf))
     5634#endif
    55645635                    {
    5565                         allowSleep = mDNSfalse;
    5566                         mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
    5567                         LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
    5568                         break;
    5569                     }
    5570                     else if (m->SPSType != 0)
    5571                     {
    5572                         mDNSu32 mymetric = LocalSPSMetric(m);
    5573                         mDNSu32 metric   = SPSMetric(cr->resrec.rdata->u.name.c);
    5574                         if (metric >= mymetric)
     5636                        // Disallow sleep if there is no sleep proxy server
     5637                        const CacheRecord *cr = FindSPSInCache1(m, &intf->NetWakeBrowse, mDNSNULL, mDNSNULL);
     5638                        if ( cr == mDNSNULL)
    55755639                        {
    55765640                            allowSleep = mDNSfalse;
    5577                             mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
    5578                             LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
     5641                            mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server on %s", intf->ifname);
     5642                            LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server", intf->ifname);
    55795643                            break;
     5644                        }
     5645                        else if (m->SPSType != 0)
     5646                        {
     5647                            mDNSu32 mymetric = LocalSPSMetric(m);
     5648                            mDNSu32 metric   = SPSMetric(cr->resrec.rdata->u.name.c);
     5649                            if (metric >= mymetric)
     5650                            {
     5651                                allowSleep = mDNSfalse;
     5652                                mDNS_snprintf(reason, sizeof(reason), "No sleep proxy server with better metric on %s", intf->ifname);
     5653                                LogInfo("mDNS_UpdateAllowSleep: Sleep disabled because %s has no sleep proxy server with a better metric", intf->ifname);
     5654                                break;
     5655                            }
    55805656                        }
    55815657                    }
     
    56095685    //
    56105686    // Note: scopeid is the same as intf->InterfaceID. It is passed in so that we don't have to call the
    5611     // platform function to extract the value from "intf" everytime.
     5687    // platform function to extract the value from "intf" every time.
    56125688
    56135689    if ((scopeid >= (sizeof(rr->updateIntID) * mDNSNBBY) || bit_get_opaque64(rr->updateIntID, scopeid)) &&
     
    56205696mDNSexport void UpdateRMACCallback(mDNS *const m, void *context)
    56215697{
    5622     IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
    5623     m->CurrentRecord = m->ResourceRecords;
    5624 
    5625     if (!addrmap)
    5626     {
    5627         LogMsg("UpdateRMACCallback: Address mapping is NULL");
    5628         return;
    5629     }
    5630 
    5631     while (m->CurrentRecord)
    5632     {
    5633         AuthRecord *rr = m->CurrentRecord;
    5634         // If this is a keepalive record and the remote IP address matches, update the RData
    5635         if (mDNS_KeepaliveRecord(&rr->resrec))
    5636         {
    5637             mDNSAddr raddr;
    5638             getKeepaliveRaddr(m, rr, &raddr);
    5639             if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
    5640             {
    5641                 UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
    5642             }
    5643         }
    5644         m->CurrentRecord = rr->next;
    5645     }
    5646 
    5647     if (addrmap)
    5648     {
    5649         mDNSPlatformMemFree(addrmap);
    5650     }
     5698        IPAddressMACMapping *addrmap = (IPAddressMACMapping *)context ;
     5699        m->CurrentRecord = m->ResourceRecords;
     5700
     5701        if (!addrmap)
     5702        {
     5703                LogMsg("UpdateRMACCallback: Address mapping is NULL");
     5704                return;
     5705        }
     5706
     5707        while (m->CurrentRecord)
     5708        {
     5709                AuthRecord *rr = m->CurrentRecord;
     5710                // If this is a non-sleep proxy keepalive record and the remote IP address matches, update the RData
     5711                if (!rr->WakeUp.HMAC.l[0] && mDNS_KeepaliveRecord(&rr->resrec))
     5712                {
     5713                        mDNSAddr raddr;
     5714                        getKeepaliveRaddr(m, rr, &raddr);
     5715                        if (mDNSSameAddress(&raddr, &addrmap->ipaddr))
     5716                        {
     5717                                // Update the MAC address only if it is not a zero MAC address
     5718                                mDNSEthAddr macAddr;
     5719                                mDNSu8 *ptr = GetValueForMACAddr((mDNSu8 *)(addrmap->ethaddr), (mDNSu8 *) (addrmap->ethaddr + sizeof(addrmap->ethaddr)), &macAddr);
     5720                                if (ptr != mDNSNULL && !mDNSEthAddressIsZero(macAddr))
     5721                                {
     5722                                        UpdateKeepaliveRData(m, rr, mDNSNULL, mDNStrue, (char *)(addrmap->ethaddr));
     5723                                }
     5724                        }
     5725                }
     5726                m->CurrentRecord = rr->next;
     5727        }
     5728
     5729        if (addrmap)
     5730        {
     5731                mDNSPlatformMemFree(addrmap);
     5732        }
    56515733}
    56525734
     
    61156197}
    61166198
     6199#define WAKE_ONLY_SERVICE 1
     6200#define AC_ONLY_SERVICE   2
     6201
     6202#ifdef APPLE_OSX_mDNSResponder
     6203mDNSlocal void SendGoodbyesForSelectServices(mDNS *const m, mDNSBool *servicePresent, mDNSu32 serviceType)
     6204{
     6205    AuthRecord *rr;
     6206    *servicePresent = mDNSfalse;
     6207
     6208    // Mark all the records we need to deregister and send them
     6209    for (rr = m->ResourceRecords; rr; rr=rr->next)
     6210    {
     6211        // If the service type is wake only service and the auth flags match and requires a goodbye
     6212        // OR if the service type is AC only and it is not a keepalive record,
     6213        // mark the records we need to deregister and send them
     6214        if ((serviceType == WAKE_ONLY_SERVICE && (rr->AuthFlags & AuthFlagsWakeOnly) &&
     6215                rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye) ||
     6216            (serviceType == AC_ONLY_SERVICE && !mDNS_KeepaliveRecord(&rr->resrec)))
     6217        {
     6218            rr->ImmedAnswer = mDNSInterfaceMark;
     6219            *servicePresent = mDNStrue;
     6220        }
     6221    }
     6222}
     6223#endif
     6224
    61176225#ifdef APPLE_OSX_mDNSResponder
    61186226// This function is used only in the case of local NIC proxy. For external
     
    61216229mDNSlocal void SendGoodbyesForWakeOnlyService(mDNS *const m, mDNSBool *WakeOnlyService)
    61226230{
    6123     AuthRecord *rr;
    6124 
    6125     *WakeOnlyService = mDNSfalse;
    6126 
    6127     // Mark all the records we need to deregister and send them
    6128     for (rr = m->ResourceRecords; rr; rr=rr->next)
    6129     {
    6130         if ((rr->AuthFlags & AuthFlagsWakeOnly) &&
    6131             rr->resrec.RecordType == kDNSRecordTypeShared && rr->RequireGoodbye)
    6132         {
    6133             rr->ImmedAnswer = mDNSInterfaceMark;
    6134             *WakeOnlyService = mDNStrue;
    6135         }
    6136     }
     6231    return SendGoodbyesForSelectServices(m, WakeOnlyService, WAKE_ONLY_SERVICE);
    61376232}
    61386233#endif // APPLE_OSx_mDNSResponder
     6234
     6235#ifdef APPLE_OSX_mDNSResponder
     6236mDNSlocal void SendGoodbyesForACOnlyServices(mDNS *const m, mDNSBool *acOnlyService)
     6237{
     6238    return SendGoodbyesForSelectServices(m, acOnlyService, AC_ONLY_SERVICE);
     6239}
     6240#endif
    61396241
    61406242mDNSlocal void SendSleepGoodbyes(mDNS *const m, mDNSBool AllInterfaces, mDNSBool unicast)
     
    62336335    mDNSBool SendGoodbyes = mDNStrue;
    62346336    mDNSBool WakeOnlyService  = mDNSfalse;
     6337    mDNSBool ACOnlyService  = mDNSfalse;
    62356338    mDNSBool invokeKACallback = mDNStrue;
    62366339    const CacheRecord *sps[3] = { mDNSNULL };
     
    62896392            else if (SupportsInNICProxy(intf))
    62906393            {
    6291                 if (ActivateLocalProxy(m, intf) == mStatus_NoError)
     6394                mDNSBool keepaliveOnly = mDNSfalse;
     6395                if (ActivateLocalProxy(m, intf, &keepaliveOnly) == mStatus_NoError)
    62926396                {
    62936397                    SendGoodbyesForWakeOnlyService(m, &WakeOnlyService);
     6398                    if (keepaliveOnly)
     6399                        SendGoodbyesForACOnlyServices(m, &ACOnlyService);
    62946400                    SendGoodbyes = mDNSfalse;
    62956401                    invokeKACallback  = mDNSfalse;
     
    63356441#if ForceAlerts
    63366442                        if (intf->SPSAddr[i].type)
    6337                         { LogMsg("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type); *(long*)0 = 0; }
     6443                            LogFatalError("BeginSleepProcessing: %s %d intf->SPSAddr[i].type %d", intf->ifname, i, intf->SPSAddr[i].type);
    63386444                        if (intf->NetWakeResolve[i].ThisQInterval >= 0)
    6339                         { LogMsg("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval); *(long*)0 = 0; }
     6445                            LogFatalError("BeginSleepProcessing: %s %d intf->NetWakeResolve[i].ThisQInterval %d", intf->ifname, i, intf->NetWakeResolve[i].ThisQInterval);
    63406446#endif
    63416447                        intf->SPSAddr[i].type = mDNSAddrType_None;
     
    63976503        SendSleepGoodbyes(m, mDNSfalse, mDNSfalse);
    63986504    }
    6399     else if (WakeOnlyService)
     6505    else if (WakeOnlyService || ACOnlyService)
    64006506    {
    64016507        // If we saw WakeOnly service above, send the goodbyes now.
    6402         LogSPS("BeginSleepProcessing: Sending goodbyes for WakeOnlyServices");
     6508        LogSPS("BeginSleepProcessing: Sending goodbyes for %s", WakeOnlyService? "WakeOnlyService" : "AC Only Service");
    64036509        SendResponses(m);
    64046510    }
     
    64746580            m->SleepState = SleepState_Awake;
    64756581            m->SleepSeqNum++;
    6476             // If the machine wakes and then immediately tries to sleep again (e.g. a maintenance wake)
    6477             // then we enforce a minimum delay of 16 seconds before we begin sleep processing.
    6478             // This is to allow time for the Ethernet link to come up, DHCP to get an address, mDNS to issue queries, etc.,
    6479             // before we make our determination of whether there's a Sleep Proxy out there we should register with.
    6480             m->DelaySleep = NonZeroTime(m->timenow + mDNSPlatformOneSecond * 16);
     6582                        m->DelaySleep = 0;
    64816583        }
    64826584
     
    71047206                               mDNSBool QueryWasLocalUnicast, DNSMessage *const response)
    71057207{
    7106     mDNSBool FromLocalSubnet    = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL);
     7208    mDNSBool FromLocalSubnet    = srcaddr && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
    71077209    AuthRecord   *ResponseRecords    = mDNSNULL;
    71087210    AuthRecord  **nrp                = &ResponseRecords;
     
    76547756        DupQuestions = q->NextInDQList;
    76557757        q->NextInDQList = mDNSNULL;
    7656         i = RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
    7657         debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s %d", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
    7658                srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6", i);
     7758        RecordDupSuppressInfo(q->DupSuppress, m->timenow, InterfaceID, srcaddr->type);
     7759        debugf("ProcessQuery: Recorded DSI for %##s (%s) on %p/%s", q->qname.c, DNSTypeName(q->qtype), InterfaceID,
     7760               srcaddr->type == mDNSAddrType_IPv4 ? "v4" : "v6");
    76597761    }
    76607762
     
    76747776    mDNSu8    *responseend = mDNSNULL;
    76757777    mDNSBool QueryWasLocalUnicast = srcaddr && dstaddr &&
    7676                                     !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL);
     7778                                    !mDNSAddrIsDNSMulticast(dstaddr) && mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
    76777779
    76787780    if (!InterfaceID && dstaddr && mDNSAddrIsDNSMulticast(dstaddr))
     
    77907892    }
    77917893    return(mDNSNULL);
    7792 }
    7793 
    7794 // Return a pointer to the primary service name, skipping subtype name if present.
    7795 mDNSlocal const domainname *getPrimaryServiceName(const domainname *domainName)
    7796 {
    7797     const domainname *primaryName = domainName;
    7798     const domainname *subName = SkipLeadingLabels(domainName, 1);
    7799    
    7800     if (SameDomainLabel(subName->c, (const mDNSu8 *)mDNSSubTypeLabel))
    7801     {
    7802         // skip "<sub type name>._sub" portion of name
    7803         primaryName = SkipLeadingLabels(domainName, 2);
    7804         debugf("getPrimaryServiceName: returning %##s for _sub type", primaryName);
    7805     }
    7806 
    7807     return primaryName;
    7808 }
    7809 
    7810 // This function is not called if the packet is from us, which implies that we accept all multicast packets coming from us.
    7811 mDNSlocal mDNSBool ExpectingMulticastResponseForRecord(mDNS *const m, CacheRecord *rr, const mDNSAddr *srcaddr, mDNSBool recordAccepted,
    7812     CacheRecord **McastNSEC3Records)
    7813 {
    7814     DNSQuestion *q;
    7815 
    7816     // Accept A and AAAA if we accepted something before in the same packet as most likely related to the
    7817     // service records that we may have accepted.
    7818     if (recordAccepted && (rr->resrec.rrtype == kDNSType_A || rr->resrec.rrtype == kDNSType_AAAA))
    7819     {
    7820         LogInfo("ExpectingMulticastResponseForRecord:A:AAAA: accepting %s, from %#a due to same packet %d", CRDisplayString(m, rr), srcaddr, m->PktNum);
    7821         return mDNStrue;
    7822     }
    7823     for (q = m->Questions; q; q=q->next)
    7824     {
    7825         if (!q->DuplicateOf && mDNSOpaque16IsZero(q->TargetQID))
    7826         {
    7827             mDNSBool ret;
    7828             // 1. If a resource record answers question, cache it. This also will cache NSECs if it asserts
    7829             //    non-existence of q->qtype. If we have any matching NSEC3 Records for the question, send
    7830             //    it along with the resource record. Do it only for questions that are expecting to
    7831             //    discover only its peers (q->AnonInfo not NULL)
    7832             if (q->AnonInfo && McastNSEC3Records && !rr->resrec.AnonInfo)
    7833             {
    7834                 InitializeAnonInfoForCR(m, McastNSEC3Records, rr);
    7835             }
    7836             ret = ResourceRecordAnswersQuestion(&rr->resrec, q);
    7837             if (ret)
    7838             {
    7839                 // The record and the question belong to the same subset. Set the
    7840                 // anonymous data in the cache record.
    7841                 if (q->AnonInfo && rr->resrec.AnonInfo)
    7842                 {
    7843                     SetAnonData(q, &rr->resrec, mDNSfalse);
    7844                 }
    7845                 LogInfo("ExpectingMulticastResponseForRecord: Name and Type match, accepting %s, from %#a", CRDisplayString(m, rr), srcaddr);
    7846                 if (rr->resrec.rrtype == kDNSType_NSEC)
    7847                     LogInfo("ExpectingMulticastResponseForRecord: record %s, question %##s (%s)", CRDisplayString(m, rr), q->qname.c, DNSTypeName(q->qtype));
    7848                 return mDNStrue;
    7849             }
    7850             if (rr->resrec.rrtype == kDNSType_SRV || rr->resrec.rrtype == kDNSType_TXT)
    7851             {
    7852                 // Point to the service type in the record name
    7853                 const domainname *name = SkipLeadingLabels(rr->resrec.name, 1);
    7854 
    7855                 // If question is for a sub type, just compare against the primary service type
    7856                 const domainname *primaryName = getPrimaryServiceName(&q->qname);
    7857 
    7858                 // 2. If the SRV or TXT record matches the service name, then cache it. If the TXT or SRV record is
    7859                 //    before the PTR record in the packet, PTR record may not be in the cache yet and hence the logic
    7860                 //    in (3) below will fail to cache it.
    7861                 if (q->qtype == kDNSType_PTR && name && SameDomainName(primaryName, name))
    7862                 {
    7863                     LogInfo("ExpectingMulticastResponseForRecord: Accepting %s due to PTR match, question %##s from %#a, pktnum %d",
    7864                         CRDisplayString(m, rr), q->qname.c, srcaddr, m->PktNum);
    7865                     return mDNStrue;
    7866                 }
    7867 
    7868                 if (name)
    7869                 {
    7870                     const mDNSu32 slot = HashSlot(name);
    7871                     const mDNSu32 namehash = DomainNameHashValue(name);
    7872                     CacheGroup *cg = CacheGroupForName(m, slot, namehash, name);
    7873                     CacheRecord *cr;
    7874      
    7875                     // 3. Same as in (2), but look in the cache in case we don't have the PTR question.
    7876 
    7877                     for (cr = cg ? cg->members : mDNSNULL; cr; cr=cr->next)
    7878                     {
    7879                         if (cr->resrec.rrtype == kDNSType_PTR)
    7880                         {
    7881                             primaryName = getPrimaryServiceName(cr->resrec.name);
    7882 
    7883                             if (SameDomainName(primaryName, name))
    7884                             {
    7885                                 LogInfo("ExpectingMulticastResponseForRecord: accepting %s, from %#a, pktnum %d",
    7886                                     CRDisplayString(m, rr), srcaddr, m->PktNum);
    7887                                 return mDNStrue;
    7888                             }
    7889                         }
    7890                     }
    7891                 }
    7892             }
    7893         }
    7894     }
    7895     debugf("ExpectingMulticastResponseForRecord: discarding %s, from %#a, pktnum %d", CRDisplayString(m, rr), srcaddr, m->PktNum);
    7896     return(mDNSfalse);
    78977894}
    78987895
     
    84428439                            hash = DomainNameHashValue(name);
    84438440                            slot = HashSlot(name);
    8444                             cg   = CacheGroupForName(m, slot, hash, name);
     8441                                                        // For now, we don't need to update cg here, because we'll do it again immediately, back up at the start of this loop
     8442                            //cg   = CacheGroupForName(m, slot, hash, name);
    84458443                        }
    84468444                }
     
    86448642    const mDNSInterfaceID InterfaceID, CacheRecord **NSEC3Records)
    86458643{
    8646     const mDNSu8 *ptr   = response->data;
     8644    const mDNSu8 *ptr;
    86478645    CacheRecord *rr;
    86488646    int i;
     
    86918689        m->rec.r.resrec.AnonInfo = mDNSNULL;
    86928690    }
    8693 }
    8694 
    8695 #define DEVICE_INFO_RECORD_LABELS 4
    8696 
    8697 // Determine if the record is an instance of _device-info._tcp.local.
    8698 mDNSlocal mDNSBool IsDeviceInfoRecord(const domainname *d)
    8699 {
    8700     const domainname *afterInstance;
    8701 
    8702     if (CountLabels(d) != DEVICE_INFO_RECORD_LABELS)
    8703         return mDNSfalse;
    8704 
    8705     // skip the instance name
    8706     afterInstance = SkipLeadingLabels(d, 1);
    8707     if (SameDomainName(afterInstance, &LocalDeviceInfoName))
    8708         return mDNStrue;
    8709 
    8710     return mDNSfalse;
    87118691}
    87128692
     
    87238703{
    87248704    int i;
    8725     mDNSBool myself;
    87268705    mDNSBool ResponseMCast    = dstaddr && mDNSAddrIsDNSMulticast(dstaddr);
    8727     mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, &myself);
     8706    mDNSBool ResponseSrcLocal = !srcaddr || mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr);
    87288707    DNSQuestion *llqMatch = mDNSNULL;
    87298708    DNSQuestion *unicastQuestion = mDNSNULL;
     
    87438722    mDNSBool rrsigsCreated = mDNSfalse;
    87448723    mDNSBool DNSSECQuestion = mDNSfalse;
    8745     mDNSBool recordAccepted = mDNSfalse;
    87468724    NetworkInterfaceInfo *llintf = FirstIPv4LLInterfaceForID(m, InterfaceID);
    87478725
    87488726    // All records in a DNS response packet are treated as equally valid statements of truth. If we want
    87498727    // to guard against spoof responses, then the only credible protection against that is cryptographic
    8750     // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
     8728    // security, e.g. DNSSEC., not worrying about which section in the spoof packet contained the record.
    87518729    int firstauthority  =                   response->h.numAnswers;
    87528730    int firstadditional = firstauthority  + response->h.numAuthorities;
     
    89848962                // we create.
    89858963
    8986                 if (!mDNSOpaque16IsZero(response->h.id))
    8987                 {
    8988                     DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
    8989 
    8990                     // Initialize the DNS server on the resource record which will now filter what questions we answer with
    8991                     // this record.
    8992                     //
    8993                     // We could potentially lookup the DNS server based on the source address, but that may not work always
    8994                     // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
    8995                     // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
    8996                     // on the "id" and "source port", then this response answers the question and assume the response
    8997                     // came from the same DNS server that we sent the query to.
    8998 
    8999                     if (q != mDNSNULL)
    9000                     {
    9001                         AcceptableResponse = mDNStrue;
    9002                         if (!InterfaceID)
    9003                         {
    9004                             debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
    9005                             m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
    9006                         }
    9007                         else
    9008                             LogInfo("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
    9009                     }
    9010                     else
    9011                     {
    9012                         // If we can't find a matching question, we need to see whether we have seen records earlier that matched
    9013                         // the question. The code below does that. So, make this record unacceptable for now
    9014                         if (!InterfaceID)
    9015                         {
    9016                             debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
    9017                             AcceptableResponse = mDNSfalse;
    9018                         }
    9019                     }
    9020                 }
    9021                 else if (ExpectingMulticastResponseForRecord(m, &m->rec.r, srcaddr, recordAccepted, &McastNSEC3Records))
    9022                 {
    9023                     recordAccepted = mDNStrue;
    9024                     AcceptableResponse = mDNStrue;
    9025                     LogInfo("mDNSCoreReceiveResponse: Accepting record in response to QU question %s, InterfaceID %p", CRDisplayString(m, &m->rec.r),
    9026                         InterfaceID);
    9027                 }
    9028                 else if (IsDeviceInfoRecord(m->rec.r.resrec.name))
    9029                 {
    9030                     recordAccepted = mDNStrue;
    9031                     AcceptableResponse = mDNStrue;
    9032                     LogInfo("mDNSCoreReceiveResponse: Accepting _device-info record %s, InterfaceID %p",
    9033                          CRDisplayString(m, &m->rec.r), InterfaceID);
    9034                 }
     8964                                DNSQuestion *q = ExpectingUnicastResponseForRecord(m, srcaddr, ResponseSrcLocal, dstport, response->h.id, &m->rec.r, !dstaddr);
     8965
     8966                                // Initialize the DNS server on the resource record which will now filter what questions we answer with
     8967                                // this record.
     8968                                //
     8969                                // We could potentially lookup the DNS server based on the source address, but that may not work always
     8970                                // and that's why ExpectingUnicastResponseForRecord does not try to verify whether the response came
     8971                                // from the DNS server that queried. We follow the same logic here. If we can find a matching quetion based
     8972                                // on the "id" and "source port", then this response answers the question and assume the response
     8973                                // came from the same DNS server that we sent the query to.
     8974
     8975                                if (q != mDNSNULL)
     8976                                {
     8977                                        AcceptableResponse = mDNStrue;
     8978                                        if (!InterfaceID)
     8979                                        {
     8980                                                debugf("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
     8981                                                m->rec.r.resrec.rDNSServer = uDNSServer = q->qDNSServer;
     8982                                        }
     8983                                        else
     8984                                                LogInfo("mDNSCoreReceiveResponse: InterfaceID %p %##s (%s)", q->InterfaceID, q->qname.c, DNSTypeName(q->qtype));
     8985                                }
     8986                                else
     8987                                {
     8988                                        // If we can't find a matching question, we need to see whether we have seen records earlier that matched
     8989                                        // the question. The code below does that. So, make this record unacceptable for now
     8990                                        if (!InterfaceID)
     8991                                        {
     8992                                                debugf("mDNSCoreReceiveResponse: Can't find question for record name %##s", m->rec.r.resrec.name->c);
     8993                                                AcceptableResponse = mDNSfalse;
     8994                                        }
     8995                                }
    90358996            }
    90368997        }
    90378998        else if (llintf && llintf->IgnoreIPv4LL && m->rec.r.resrec.rrtype == kDNSType_A)
    90388999        {
    9039             CacheRecord *const rr = &m->rec.r;
    9040             RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
    9041 
    9042             // If we are supposed to ignore link-local addresses on this interface, drop
    9043             // all "A" records that have link-local address in them.
     9000            // There are some routers (rare, thankfully) that generate bogus ARP responses for
     9001            // any IPv4 address they don’t recognize, including RFC 3927 IPv4 link-local addresses.
     9002            // To work with these broken routers, client devices need to blacklist these broken
     9003            // routers and ignore their bogus ARP responses. Some devices implement a technique
     9004            // such as the one described in US Patent 7436783, which lets clients detect and
     9005            // ignore these broken routers: <https://www.google.com/patents/US7436783>
     9006
     9007            // OS X and iOS do not implement this defensive mechanism, instead taking a simpler
     9008            // approach of just detecting these broken routers and completely disabling IPv4
     9009            // link-local communication on interfaces where a broken router is detected.
     9010            // OS X and iOS set the IFEF_ARPLL interface flag on interfaces
     9011            // that are deemed “safe” for IPv4 link-local communication;
     9012            // the flag is cleared on interfaces where a broken router is detected.
     9013
     9014            // OS X and iOS will not even try to communicate with an IPv4
     9015            // link-local destination on an interface without the IFEF_ARPLL flag set.
     9016            // This can cause some badly written applications to freeze for a long time if they
     9017            // attempt to connect to an IPv4 link-local destination address and then wait for
     9018            // that connection attempt to time out before trying other candidate addresses.
     9019           
     9020            // To mask this client bug, we suppress acceptance of IPv4 link-local address
     9021            // records on interfaces where we know the OS will be unwilling even to attempt
     9022            // communication with those IPv4 link-local destination addresses.
     9023            // <rdar://problem/9400639> kSuppress IPv4LL answers on interfaces without IFEF_ARPLL
     9024
     9025            const CacheRecord *const rr = &m->rec.r;
     9026            const RDataBody2 *const rdb = (RDataBody2 *)rr->smallrdatastorage.data;
    90449027            if (mDNSv4AddressIsLinkLocal(&rdb->ipv4))
    90459028            {
     
    91009083                            LogInfo("mDNSCoreReceiveResponse: Already reset to Probing: %s", ARDisplayString(m, rr));
    91019084                        else if (rr->ProbeCount == DefaultProbeCountForTypeUnique)
    9102                             LogMsg("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
     9085                            LogInfo("mDNSCoreReceiveResponse: Ignoring response received before we even began probing: %s", ARDisplayString(m, rr));
    91039086                        else
    91049087                        {
     
    91869169            }
    91879170
    9188             // If mDNSOppCaching is set (which affects only multicast), enable opportunistic caching in which case we cache
    9189             // everything that was received over multicast. Otherwise, we are selective about the caching.
    9190             //
    9191             // Cache everything that is from ourselves (that's how we answer any questions looking for them). Otherwise call
    9192             // ExpectingMulticastResponseForRecord which decides whether to cache this record or not.
    9193             //
    9194             if (!m->mDNSOppCaching && !rr && !myself && mDNSOpaque16IsZero(response->h.id))
    9195             {
    9196                 if (!ExpectingMulticastResponseForRecord(m, &m->rec.r, srcaddr, recordAccepted, &McastNSEC3Records))
    9197                 {
    9198                     //LogMsg("mDNSCoreReceiveResponse: discarding %s", CRDisplayString(m, &m->rec.r));
    9199                     mDNSCoreResetRecord(m);
    9200                     continue;
    9201                 }
    9202                 else
    9203                 {
    9204                     recordAccepted = mDNStrue;
    9205                 }
    9206             }
    9207 
    9208 
    92099171            // If packet resource record not in our cache, add it now
    92109172            // (unless it is just a deletion of a record we never had, in which case we don't care)
     
    93449306                    // which we treat as a goodbye followed by an addition) and in that case it would be
    93459307                    // inappropriate to synchronize all the other records to a TTL of 0 (or 1).
     9308
    93469309                    // We suppress the message for the specific case of correcting from 240 to 60 for type TXT,
    93479310                    // because certain early Bonjour devices are known to have this specific mismatch, and
     
    93509313                    // to give us an aged TTL to correct for how long it has held the record,
    93519314                    // so our received TTLs are expected to vary in that case
     9315
     9316                    // We also suppress log message in the case of SRV records that are recieved
     9317                    // with a TTL of 4500 that are already cached with a TTL of 120 seconds, since
     9318                    // this behavior was observed for a number of discoveryd based AppleTV's in iOS 8
     9319                    // GM builds.
    93529320                    if (r2->resrec.rroriginalttl != r1->resrec.rroriginalttl && r1->resrec.rroriginalttl > 1)
    93539321                    {
    93549322                        if (!(r2->resrec.rroriginalttl == 240 && r1->resrec.rroriginalttl == 60 && r2->resrec.rrtype == kDNSType_TXT) &&
     9323                            !(r2->resrec.rroriginalttl == 120 && r1->resrec.rroriginalttl == 4500 && r2->resrec.rrtype == kDNSType_SRV) &&
    93559324                            mDNSOpaque16IsZero(response->h.id))
    93569325                            LogInfo("Correcting TTL from %4d to %4d for %s",
     
    95519520        else if (*ptr == ':')
    95529521        {
     9522            if (colons >=5 || val > 255)
     9523            {
     9524                LogMsg("GetValueForMACAddr: Address malformed colons %d val %d", colons, val);
     9525                return mDNSNULL;
     9526            }
    95539527            eth->b[colons] = val;
    95549528            colons++;
     
    96829656        else if (*ptr == '.')
    96839657        {
     9658            if (val > 255 || dots >= 3)
     9659            {
     9660                LogMsg("GetValueForIPv4Addr: something wrong ptr(%p) %c, limit %p, dots %d", ptr, *ptr, limit, dots);
     9661                return mDNSNULL;
     9662            }
    96849663            v4->b[dots++] = val;
    96859664            val = 0;
     
    97239702    return ptr;
    97249703}
     9704
     9705mDNSexport mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr)
     9706{
     9707        mDNSAddr    laddr, raddr;
     9708        mDNSEthAddr eth;
     9709        mDNSIPPort  lport, rport;
     9710        mDNSu32     timeout, seq, ack;
     9711        mDNSu16     win;
     9712
     9713        if (!mDNS_KeepaliveRecord(&rr->resrec))
     9714        {
     9715                return mDNSfalse;
     9716        }
     9717
     9718        timeout = seq = ack = 0;
     9719        win = 0;
     9720        laddr = raddr = zeroAddr;
     9721        lport = rport = zeroIPPort;
     9722
     9723        mDNS_ExtractKeepaliveInfo(rr, &timeout, &laddr, &raddr, &eth, &seq, &ack, &lport, &rport, &win);
     9724
     9725        if (mDNSAddressIsZero(&laddr) || mDNSIPPortIsZero(lport) ||
     9726                mDNSAddressIsZero(&raddr) || mDNSIPPortIsZero(rport) ||
     9727                mDNSEthAddressIsZero(eth))
     9728        {
     9729                return mDNSfalse;
     9730        }
     9731
     9732        return mDNStrue;
     9733}
     9734
    97259735
    97269736mDNSlocal void mDNS_ExtractKeepaliveInfo(AuthRecord *ar, mDNSu32 *timeout, mDNSAddr *laddr, mDNSAddr *raddr, mDNSEthAddr *eth, mDNSu32 *seq,
     
    99009910mDNSlocal void mDNS_SendKeepaliveACK(mDNS *const m, AuthRecord *ar)
    99019911{
    9902     if (ar != mDNSNULL)
    9903     {
    9904         LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
    9905         return;
    9906     }
    9907     mDNSu32     timeout, seq, ack;
     9912    mDNSu32     timeout, seq, ack, seqInc;
    99089913    mDNSu16     win;
    99099914    mDNSAddr    laddr, raddr;
    99109915    mDNSEthAddr eth;
    99119916    mDNSIPPort  lport, rport;
     9917    mDNSu8      *ptr;
     9918
     9919    if (ar == mDNSNULL)
     9920    {
     9921        LogInfo("mDNS_SendKeepalivesACK: AuthRecord is NULL");
     9922        return;
     9923    }
    99129924
    99139925    timeout = seq = ack = 0;
     
    99249936        return;
    99259937    }
     9938
     9939    // To send a keepalive ACK, we need to add one to the sequence number from the keepalive
     9940    // record, which is the TCP connection's "next" sequence number minus one. Otherwise, the
     9941    // keepalive ACK also ends up being a keepalive probe. Also, seq is in network byte order, so
     9942    // it's converted to host byte order before incrementing it by one.
     9943    ptr = (mDNSu8 *)&seq;
     9944    seqInc = (mDNSu32)((ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]) + 1;
     9945    ptr[0] = (mDNSu8)((seqInc >> 24) & 0xFF);
     9946    ptr[1] = (mDNSu8)((seqInc >> 16) & 0xFF);
     9947    ptr[2] = (mDNSu8)((seqInc >>  8) & 0xFF);
     9948    ptr[3] = (mDNSu8)((seqInc      ) & 0xFF);
    99269949    LogMsg("mDNS_SendKeepaliveACK: laddr %#a raddr %#a lport %d rport %d", &laddr, &raddr, mDNSVal16(lport), mDNSVal16(rport));
    99279950    mDNSPlatformSendKeepalive(&laddr, &raddr, &lport, &rport, seq, ack, win);
     
    1009010113        mDNSu32 updatelease = 60 * 60;      // If SPS fails to indicate lease time, assume one hour
    1009110114        const mDNSu8 *ptr = LocateOptRR(msg, end, DNSOpt_LeaseData_Space);
     10115        mDNSAddr spsaddr;
     10116        char *ifname;
    1009210117        if (ptr)
    1009310118        {
     
    1013910164
    1014010165        // Update the dynamic store with the IP Address and MAC address of the sleep proxy
    10141         char *ifname = InterfaceNameForID(m, InterfaceID);
    10142         mDNSAddr spsaddr;
     10166        ifname = InterfaceNameForID(m, InterfaceID);
    1014310167        mDNSPlatformMemCopy(&spsaddr, srcaddr, sizeof (mDNSAddr));
    1014410168        mDNSPlatformStoreSPSMACAddr(&spsaddr, ifname);
     
    1015310177{
    1015410178    if (cr == &m->rec.r && m->rec.r.resrec.RecordType)
    10155     {
    10156         LogMsg("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
    10157 #if ForceAlerts
    10158         *(long*)0 = 0;
    10159 #endif
    10160     }
     10179        LogFatalError("MakeNegativeCacheRecord: m->rec appears to be already in use for %s", CRDisplayString(m, &m->rec.r));
    1016110180
    1016210181    // Create empty resource record
     
    1026610285        // Check the destination address to avoid accounting for spurious packets that
    1026710286        // comes in with message id zero.
    10268         if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr, mDNSNULL) &&
     10287        if (!mDNS_AddressIsLocalSubnet(m, InterfaceID, srcaddr) &&
    1026910288            mDNSAddressIsAllDNSLinkGroup(dstaddr))
    1027010289        {
     
    1047310492        if ((*p)->interface == interface && SameDomainName(&(*p)->domain, d))
    1047410493        {
    10475             if (!((*p)->flags & DNSServer_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
    10476             (*p)->flags &= ~DNSServer_FlagDelete;
     10494            if (!((*p)->flags & McastResolver_FlagDelete)) LogMsg("Note: Mcast Resolver domain %##s (%p) registered more than once", d->c, interface);
     10495            (*p)->flags &= ~McastResolver_FlagDelete;
    1047710496            tmp = *p;
    1047810497            *p = tmp->next;
     
    1049210511        {
    1049310512            (*p)->interface = interface;
    10494             (*p)->flags     = DNSServer_FlagNew;
     10513            (*p)->flags     = McastResolver_FlagNew;
    1049510514            (*p)->timeout   = timeout;
    1049610515            AssignDomainName(&(*p)->domain, d);
     
    1069710716        //
    1069810717        // Note: DNS configuration change will help pick the new dns servers but currently it does not affect the timeout
    10699 
    10700         if (curr->scoped && curr->interface == mDNSInterface_Any)
    10701         {
    10702             debugf("SetValidDNSServers: Scoped DNS server %#a (Domain %##s) with Interface Any", &curr->addr, curr->domain.c);
     10718       
     10719        // Skip DNSServers that are InterfaceID Scoped but have no valid interfaceid set OR DNSServers that are ServiceID Scoped but have no valid serviceid set
     10720        if ((curr->scoped == kScopeInterfaceID && curr->interface == mDNSInterface_Any) || (curr->scoped == kScopeServiceID && curr->serviceID <= 0))
     10721        {
     10722            LogInfo("SetValidDNSServers: ScopeType[%d] Skipping DNS server %#a (Domain %##s) Interface:[%p] Serviceid:[%d]", curr->scoped, &curr->addr, curr->domain.c, curr->interface, curr->serviceID);
    1070310723            continue;
    1070410724        }
     
    1135111371    question->noServerResponse    = 0; 
    1135211372    question->StopTime            = 0;
     11373#if TARGET_OS_EMBEDDED
     11374    mDNSPlatformMemZero(&question->metrics, sizeof(question->metrics));
     11375#endif
    1135311376
    1135411377    // Need not initialize the DNS Configuration for Local Only OR P2P Questions
     
    1139811421    mDNSBool purge;
    1139911422    int i;
     11423    mDNSBool isCellBlocked = mDNSfalse;
    1140011424
    1140111425    // Note: In the case where we already have the answer to this question in our cache, that may be all the client
     
    1144611470    question->FlappingInterface2 = mDNSNULL;
    1144711471       
    11448         // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetServiceID()
     11472        // if kDNSServiceFlagsServiceIndex flag is SET by the client, then do NOT call mDNSPlatformGetDNSRoutePolicy()
    1144911473        // since we would already have the question->ServiceID in that case.
    1145011474        if (!(question->flags & kDNSServiceFlagsServiceIndex))
    11451                 question->ServiceID = mDNSPlatformGetServiceID(m, question);
     11475                mDNSPlatformGetDNSRoutePolicy(m, question, &isCellBlocked);
    1145211476        else
    11453                 LogInfo("InitCommonState: Query for %##s (%s), PID[%d], ServiceID %d is already set by client", question->qname.c,
    11454                            DNSTypeName(question->qtype), question->pid, question->ServiceID);
     11477                LogInfo("InitCommonState: Query for %##s (%s), PID[%d], EUID[%d], ServiceID[%d] is already set by client", question->qname.c,
     11478                DNSTypeName(question->qtype), question->pid, question->euid, question->ServiceID);
    1145511479       
    1145611480    InitDNSConfig(m, question);
     
    1146311487    // If ServiceID is 0 or the policy disallows making DNS requests,
    1146411488    // set DisallowPID
    11465     question->DisallowPID       = (question->ServiceID == 0 || (mDNSPlatformAllowPID(m, question) == 0));
     11489    question->DisallowPID       = (question->ServiceID == 0 || (isCellBlocked && question->qDNSServer && question->qDNSServer->cellIntf));
    1146611490    if (question->DisallowPID)
    1146711491        LogInfo("InitCommonState: Query suppressed for %##s (%s), PID %d/ServiceID %d not allowed", question->qname.c,
    11468                                         DNSTypeName(question->qtype), question->pid, question->ServiceID);
     11492            DNSTypeName(question->qtype), question->pid, question->ServiceID);
    1146911493
    1147011494    question->NextInDQList      = mDNSNULL;
     
    1158511609        if (question->qDNSServer->cellIntf)
    1158611610        {
    11587             LogInfo("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
     11611            debugf("InitDNSSECProxyState: Turning off validation for %##s (%s); going over cell", question->qname.c, DNSTypeName(question->qtype));
    1158811612            question->ValidationRequired = mDNSfalse;
    1158911613        }
     
    1172011744        else
    1172111745        {
     11746#if TARGET_OS_WATCH
     11747                        m->NumAllInterfaceQuestions++;
     11748                        LogInfo("mDNS_StartQuery_internal: NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
     11749                                m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
     11750                        if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
     11751                                m->NetworkChanged = m->timenow;
     11752#endif
    1172211753            if (purge)
    1172311754            {
     
    1176411795        if (question->ThisQInterval >= 0)   // Only log error message if the query was supposed to be active
    1176511796#endif
    11766         LogMsg("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
    11767                question->qname.c, DNSTypeName(question->qtype));
    11768 #if ForceAlerts
    11769         *(long*)0 = 0;
     11797        LogFatalError("mDNS_StopQuery_internal: Question %##s (%s) not found in active list", question->qname.c, DNSTypeName(question->qtype));
     11798        return(mStatus_BadReferenceErr);
     11799    }
     11800
     11801#if TARGET_OS_WATCH
     11802    if (question->InterfaceID != mDNSInterface_LocalOnly && question->InterfaceID != mDNSInterface_P2P && mDNSOpaque16IsZero(question->TargetQID))
     11803    {
     11804        if (m->NumAllInterfaceRecords + m->NumAllInterfaceQuestions == 1)
     11805                m->NetworkChanged = m->timenow;
     11806        m->NumAllInterfaceQuestions--;
     11807        LogInfo("mDNS_StopQuery_internal:  NumAllInterfaceRecords %d NumAllInterfaceQuestions %d %##s (%s)",
     11808                m->NumAllInterfaceRecords, m->NumAllInterfaceQuestions, question->qname.c, DNSTypeName(question->qtype));
     11809    }
    1177011810#endif
    11771         return(mStatus_BadReferenceErr);
    11772     }
    11773 
     11811
     11812#if TARGET_OS_EMBEDDED
     11813    if (Question_uDNS(question) && !question->metrics.answered)
     11814    {
     11815        uDNSMetrics *       metrics;
     11816        const domainname *  queryName;
     11817        mDNSBool            isForCellular;
     11818
     11819        metrics       = &question->metrics;
     11820        queryName     = metrics->originalQName ? metrics->originalQName : &question->qname;
     11821        isForCellular = (question->qDNSServer && question->qDNSServer->cellIntf);
     11822
     11823        MetricsUpdateUDNSStats(queryName, mDNSfalse, metrics->querySendCount, 0, isForCellular);
     11824    }
     11825#endif
    1177411826    // Take care to cut question from list *before* calling UpdateQuestionDuplicates
    1177511827    UpdateQuestionDuplicates(m, question);
     
    1189411946        question->AnonInfo = mDNSNULL;
    1189511947    }
     11948#if TARGET_OS_EMBEDDED
     11949    if (question->metrics.originalQName)
     11950    {
     11951        mDNSPlatformMemFree(question->metrics.originalQName);
     11952        question->metrics.originalQName = mDNSNULL;
     11953    }
     11954#endif
    1189611955
    1189711956    return(mStatus_NoError);
     
    1234612405    question->AnonInfo         = mDNSNULL;
    1234712406    question->pid              = mDNSPlatformGetPID();
     12407    question->euid                         = 0;
    1234812408    question->QuestionCallback = Callback;
    1234912409    question->QuestionContext  = Context;
     
    1246212522    char buffer[MAX_REVERSE_MAPPING_NAME];
    1246312523    NetworkInterfaceInfo *primary;
    12464 
    12465     if (!set->McastTxRx)
    12466     {
    12467         LogInfo("AdvertiseInterface: Returning, not multicast capable %s", set->ifname);
    12468         return;
    12469     }
    12470 #if TARGET_OS_EMBEDDED
    12471     if (!m->AutoTargetServices)
     12524    mDNSu8 recordType;
     12525
     12526    if (m->AutoTargetServices == 0)
    1247212527    {
    1247312528        LogInfo("AdvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
    1247412529        return;
    1247512530    }
    12476 #endif
    1247712531
    1247812532    primary = FindFirstAdvertisedInterface(m);
     
    1248112535    // If interface is marked as a direct link, we can assume the address record is unique
    1248212536    // and does not need to go through the probe phase of the probe/announce packet sequence.
    12483     mDNSu8 recordType = (set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique);
     12537    recordType = (set->DirectLink ? kDNSRecordTypeKnownUnique : kDNSRecordTypeUnique);
    1248412538
    1248512539    if (set->DirectLink)
     
    1255612610mDNSlocal void DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set)
    1255712611{
    12558     NetworkInterfaceInfo *intf;
    12559 
    12560     // If we still have address records referring to this one, update them
    12561     NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
    12562     AuthRecord *A = primary ? &primary->RR_A : mDNSNULL;
    12563     for (intf = m->HostInterfaces; intf; intf = intf->next)
    12564         if (intf->RR_A.RRSet == &set->RR_A)
    12565             intf->RR_A.RRSet = A;
     12612    if (m->AutoTargetServices == 0)
     12613    {
     12614        LogInfo("DeadvertiseInterface: Returning due to AutoTargetServices zero for %s", set->ifname);
     12615        return;
     12616    }
    1256612617
    1256712618    // Unregister these records.
     
    1257012621    // Also, in the event of a name conflict, one or more of our records will have been forcibly deregistered.
    1257112622    // To avoid unnecessary and misleading warning messages, we check the RecordType before calling mDNS_Deregister_internal().
    12572     if (set->RR_A.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A,     mDNS_Dereg_normal);
    12573     if (set->RR_PTR.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR,   mDNS_Dereg_normal);
     12623    if (set->RR_A    .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_A,     mDNS_Dereg_normal);
     12624    if (set->RR_PTR  .resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_PTR,   mDNS_Dereg_normal);
    1257412625    if (set->RR_HINFO.resrec.RecordType) mDNS_Deregister_internal(m, &set->RR_HINFO, mDNS_Dereg_normal);
    1257512626
     
    1259512646mDNSlocal void DeadvertiseAllInterfaceRecords(mDNS *const m)
    1259612647{
    12597 #if TARGET_OS_EMBEDDED
    1259812648    NetworkInterfaceInfo *intf;
    1259912649    for (intf = m->HostInterfaces; intf; intf = intf->next)
     
    1260512655        }
    1260612656    }
    12607 #else
    12608     (void) m; //unused
    12609 #endif
    1261012657}
    1261112658
     
    1261312660{
    1261412661    domainname newmname;
    12615     NetworkInterfaceInfo *intf;
    1261612662    AuthRecord *rr;
    1261712663    newmname.c[0] = 0;
     
    1262612672    {
    1262712673        AssignDomainName(&m->MulticastHostname, &newmname);
    12628 
    12629         // 1. Stop advertising our address records on all interfaces
    12630         for (intf = m->HostInterfaces; intf; intf = intf->next)
    12631             if (intf->Advertise) DeadvertiseInterface(m, intf);
    12632 
    12633         // 2. Start advertising our address records using the new name
    12634         for (intf = m->HostInterfaces; intf; intf = intf->next)
    12635             if (intf->Advertise) AdvertiseInterface(m, intf);
     12674        DeadvertiseAllInterfaceRecords(m);
     12675        AdvertiseAllInterfaceRecords(m);
    1263612676    }
    1263712677
     
    1295212992    NetworkInterfaceInfo **p = &m->HostInterfaces;
    1295312993    mDNSBool revalidate = mDNSfalse;
     12994    NetworkInterfaceInfo *primary;
     12995    NetworkInterfaceInfo *intf;
     12996    AuthRecord *A;
    1295412997
    1295512998    mDNS_Lock(m);
     
    1296813011    {
    1296913012        // If this interface not the active member of its set, update the v4/v6Available flags for the active member
    12970         NetworkInterfaceInfo *intf;
    1297113013        for (intf = m->HostInterfaces; intf; intf = intf->next)
    1297213014            if (intf->InterfaceActive && intf->InterfaceID == set->InterfaceID)
     
    1297513017    else
    1297613018    {
    12977         NetworkInterfaceInfo *intf = FirstInterfaceForID(m, set->InterfaceID);
     13019        intf = FirstInterfaceForID(m, set->InterfaceID);
    1297813020        if (intf)
    1297913021        {
     
    1300813050            if (set->McastTxRx && flapping)
    1300913051            {
    13010                 LogMsg("DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
     13052                LogMsg("mDNS_DeregisterInterface: Frequent transitions for interface %s (%#a)", set->ifname, &set->ip);
    1301113053                m->mDNSStats.InterfaceDownFlap++;
    1301213054            }
     
    1304913091    }
    1305013092
     13093    // If we still have address records referring to this one, update them.
     13094    // This is safe, because this NetworkInterfaceInfo has already been unlinked from the list,
     13095    // so the call to FindFirstAdvertisedInterface() won’t accidentally find it.
     13096    primary = FindFirstAdvertisedInterface(m);
     13097    A = primary ? &primary->RR_A : mDNSNULL;
     13098    for (intf = m->HostInterfaces; intf; intf = intf->next)
     13099        if (intf->RR_A.RRSet == &set->RR_A)
     13100            intf->RR_A.RRSet = A;
     13101
    1305113102    // If we were advertising on this interface, deregister those address and reverse-lookup records now
    1305213103    if (set->Advertise) DeadvertiseInterface(m, set);
     
    1337013421    e = &sr->Extras;
    1337113422    while (*e) e = &(*e)->next;
    13372 
    13373     if (ttl == 0) ttl = kStandardTTL;
    1337413423
    1337513424    extra->r.DependentOn = &sr->RR_SRV;
     
    1402614075    {
    1402714076        const mDNSu8 *const trans = p + 14 + (pkt->v4.vlen & 0xF) * 4;
     14077        const mDNSu8 * transEnd = p + 14 + mDNSVal16(pkt->v4.totlen);
     14078        if (transEnd > end) transEnd = end;
    1402814079        debugf("Got IPv4 %02X from %.4a to %.4a", pkt->v4.protocol, &pkt->v4.src, &pkt->v4.dst);
    1402914080        src.type = mDNSAddrType_IPv4; src.ip.v4 = pkt->v4.src;
    1403014081        dst.type = mDNSAddrType_IPv4; dst.ip.v4 = pkt->v4.dst;
    14031         if (end >= trans + RequiredCapLen(pkt->v4.protocol))
    14032             mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, end, InterfaceID, 0);
     14082        if (transEnd >= trans + RequiredCapLen(pkt->v4.protocol))
     14083            mDNSCoreReceiveRawTransportPacket(m, &eth->src, &src, &dst, pkt->v4.protocol, p, (TransportLayerPacket*)trans, transEnd, InterfaceID, 0);
    1403314084    }
    1403414085    // Is IPv6? Length must be at least 14 + 28 = 42 bytes
     
    1416114212
    1416214213    m->p                             = p;
     14214    m->NetworkChanged                = 0;
    1416314215    m->CanReceiveUnicastOn5353       = mDNSfalse; // Assume we can't receive unicasts on 5353, unless platform layer tells us otherwise
    1416414216    m->AdvertiseLocalAddresses       = AdvertiseLocalAddresses;
     
    1428314335    m->WABLBrowseQueriesCount   = 0;
    1428414336    m->WABRegQueriesCount       = 0;
    14285 #if !TARGET_OS_EMBEDDED
    14286     m->mDNSOppCaching           = mDNStrue;
     14337#if TARGET_OS_EMBEDDED || TARGET_OS_WATCH
     14338    m->AutoTargetServices       = 0;
    1428714339#else
    14288     m->mDNSOppCaching           = mDNSfalse;
     14340    m->AutoTargetServices       = 1;
    1428914341#endif
    14290     m->AutoTargetServices       = 0;
    14291 
     14342#if TARGET_OS_WATCH
     14343    m->NumAllInterfaceRecords   = 0;
     14344    m->NumAllInterfaceQuestions = 0;
     14345#else
     14346    // Initialize to 1 for these targets to prevent not joining multicast group for interfaces when
     14347    // both of these values are zero.
     14348    m->NumAllInterfaceRecords   = 1;
     14349    m->NumAllInterfaceQuestions = 1;
     14350#endif
    1429214351    // NAT traversal fields
    1429314352    m->LLQNAT.clientCallback    = mDNSNULL;
     
    1452614585            NumUnicastDNSServers--;
    1452714586            ptr->flags |= DNSServer_FlagDelete;
     14587#if APPLE_OSX_mDNSResponder
     14588            if (ptr->flags & DNSServer_FlagUnreachable)
     14589                NumUnreachableDNSServers--;
     14590#endif
    1452814591        }
    1452914592        // We handle the mcast resolvers here itself as mDNSPlatformSetDNSConfig looks at
     
    1454014603            NumUnicastDNSServers++;
    1454114604            ptr->flags &= ~DNSServer_FlagDelete;
     14605#if APPLE_OSX_mDNSResponder
     14606            if (ptr->flags & DNSServer_FlagUnreachable)
     14607                NumUnreachableDNSServers++;
     14608#endif
    1454214609        }
    1454314610        for (mr = m->McastResolvers; mr; mr = mr->next)
     
    1458814655    while (*mres)
    1458914656    {
    14590         if (((*mres)->flags & DNSServer_FlagDelete) != 0)
     14657        if (((*mres)->flags & McastResolver_FlagDelete) != 0)
    1459114658        {
    1459214659            mr = *mres;
     
    1491414981mDNSexport void mDNS_StartExit(mDNS *const m)
    1491514982{
    14916     NetworkInterfaceInfo *intf;
    1491714983    AuthRecord *rr;
    1491814984
     
    1495415020#endif
    1495515021
    14956     for (intf = m->HostInterfaces; intf; intf = intf->next)
    14957         if (intf->Advertise)
    14958             DeadvertiseInterface(m, intf);
     15022    DeadvertiseAllInterfaceRecords(m);
    1495915023
    1496015024    // Shut down all our active NAT Traversals
     
    1501615080{
    1501715081    mDNSu32 rrcache_active = 0;
    15018     mDNSu32 rrcache_totalused = 0;
     15082    mDNSu32 rrcache_totalused = m->rrcache_totalused;
    1501915083    mDNSu32 slot;
    1502015084    AuthRecord *rr;
     
    1502315087    mDNSPlatformClose(m);
    1502415088
    15025     rrcache_totalused = m->rrcache_totalused;
    1502615089    for (slot = 0; slot < CACHE_HASH_SLOTS; slot++)
    1502715090    {
     
    1504215105    debugf("mDNS_FinalExit: RR Cache was using %ld records, %lu active", rrcache_totalused, rrcache_active);
    1504315106    if (rrcache_active != m->rrcache_active)
    15044         LogMsg("*** ERROR *** rrcache_active %lu != m->rrcache_active %lu", rrcache_active, m->rrcache_active);
     15107        LogMsg("*** ERROR *** rrcache_totalused %lu; rrcache_active %lu != m->rrcache_active %lu", rrcache_totalused, rrcache_active, m->rrcache_active);
    1504515108
    1504615109    for (rr = m->ResourceRecords; rr; rr = rr->next)
  • mDNSResponder/mDNSCore/mDNSDebug.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    149149#define LogMsgNoIdent LogMsg
    150150
     151#if APPLE_OSX_mDNSResponder
     152extern void LogFatalError(const char *format, ...);
     153#else
     154#define LogFatalError LogMsg
     155#endif
     156
    151157#if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING >= 1
    152158extern void *mallocL(char *msg, unsigned int size);
    153159extern void freeL(char *msg, void *x);
    154 extern void LogMemCorruption(const char *format, ...);
    155160extern void uds_validatelists(void);
    156161extern void udns_validatelists(void *const v);
     162extern void LogMemCorruption(const char *format, ...);
    157163#else
    158164#define mallocL(X,Y) malloc(Y)
  • mDNSResponder/mDNSCore/mDNSEmbeddedAPI.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2013 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    7171#if APPLE_OSX_mDNSResponder
    7272#include <uuid/uuid.h>
     73#include <TargetConditionals.h>
    7374#endif
    7475
     
    9192// In order to disable the above features pass the option to your compiler, e.g. -D UNICAST_DISABLED
    9293
    93 // Additionally, the LIMITED_RESOURCES_TARGET compile option will eliminate caching and
    94 // and reduce the maximum DNS message sizes.
     94// Additionally, the LIMITED_RESOURCES_TARGET compile option will reduce the maximum DNS message sizes.
    9595
    9696#ifdef LIMITED_RESOURCES_TARGET
    9797// Don't support jumbo frames
    98 #define AbsoluteMaxDNSMessageData       1500
    99 // By the time you add IPv6 header (40 bytes) UDP header (8 bytes) and DNS message header (12 bytes)
    100 // this makes 1560 which is 60 bytes over the standard Ethernet MTU. D'oh!
    101 
     98// 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
     99#define AbsoluteMaxDNSMessageData       1440
    102100// StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
    103101#define MaximumRDSize                           264
    104 // Don't cache anything
    105 #define AUTH_HASH_SLOTS                         1
    106 #define CACHE_HASH_SLOTS                        1
    107102#endif
    108103
     
    557552    mDNSu8 vlen;
    558553    mDNSu8 tos;
    559     mDNSu16 totlen;
     554    mDNSOpaque16 totlen;
    560555    mDNSOpaque16 id;
    561556    mDNSOpaque16 flagsfrags;
     
    13211316enum
    13221317{
    1323     DNSServer_FlagDelete = 1,
    1324     DNSServer_FlagNew    = 2
     1318    DNSServer_FlagDelete      = 0x1,
     1319    DNSServer_FlagNew         = 0x2,
     1320#if APPLE_OSX_mDNSResponder
     1321    DNSServer_FlagUnreachable = 0x4,
     1322#endif
    13251323};
    13261324
     
    14141412    const domainname *name;
    14151413    RData           *rdata;             // Pointer to storage for this rdata
    1416     DNSServer       *rDNSServer;        // Unicast DNS server authoritative for this entry;null for multicast
     1414    DNSServer       *rDNSServer;        // Unicast DNS server authoritative for this entry; null for multicast
    14171415    AnonymousInfo   *AnonInfo;          // Anonymous Information
    14181416};
     
    15031501    AuthRecord     *next;               // Next in list; first element of structure for efficiency reasons
    15041502    // Field Group 1: Common ResourceRecord fields
    1505     ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
     1503    ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
    15061504
    15071505    // Field Group 2: Persistent metadata for Authoritative Records
     
    16351633{
    16361634    CacheRecord    *next;               // Next in list; first element of structure for efficiency reasons
    1637     ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
     1635    ResourceRecord resrec;              // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
    16381636
    16391637    // Transient state for Cache Records
     
    16591657
    16601658    mDNSAddr sourceAddress;             // node from which we received this record
    1661     // Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit
     1659    // Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit (now 160 bytes for 64-bit)
    16621660    RData_small smallrdatastorage;      // Storage for small records is right here (4 bytes header + 68 bytes data = 72 bytes)
    16631661};
    16641662
    16651663// Should match the CacheGroup_struct members, except namestorage[].  Only used to calculate
    1666 // the size of the namestorage array in CacheGroup_struct so that
    1667 // sizeof(CacheGroup) == sizeof(CacheRecord)
     1664// the size of the namestorage array in CacheGroup_struct so that sizeof(CacheGroup) == sizeof(CacheRecord)
    16681665struct CacheGroup_base
    16691666{
     
    18871884// RFC 4122 defines it to be 16 bytes
    18881885#define UUID_SIZE       16
     1886
     1887#if TARGET_OS_EMBEDDED
     1888typedef struct
     1889{
     1890    domainname *    originalQName;          // Name of original A/AAAA record if this question is for a CNAME record.
     1891    mDNSu32         querySendCount;         // Number of queries that have been sent to DNS servers so far.
     1892    mDNSs32         firstQueryTime;         // The time when the first query was sent to a DNS server.
     1893    mDNSBool        answered;               // Has this question been answered?
     1894
     1895}   uDNSMetrics;
     1896#endif
    18891897
    18901898struct DNSQuestion_struct
     
    19982006    mDNSs32 pid;                            // Process ID of the client that is requesting the question
    19992007    mDNSu8  uuid[UUID_SIZE];                // Unique ID of the client that is requesting the question (valid only if pid is zero)
     2008    mDNSu32 euid;                           // Effective User Id of the client that is requesting the question
    20002009    domainname           *qnameOrig;        // Copy of the original question name if it is not fully qualified
    20012010    mDNSQuestionCallback *QuestionCallback;
    20022011    void                 *QuestionContext;
     2012#if TARGET_OS_EMBEDDED
     2013    uDNSMetrics metrics;                    // Data used for collecting unicast DNS query metrics.
     2014#endif
    20032015};
    20042016
     
    21462158    mDNSBool DirectLink;                // a direct link, indicating we can skip the probe for
    21472159                                        // address records
     2160    mDNSBool SupportsUnicastMDNSResponse;  // Indicates that the interface supports unicast responses
     2161                                        // to Bonjour queries.  Generally true for an interface. 
    21482162};
    21492163
     
    22602274    mDNSu32 WakeOnResolves;                 // Number of times we did a wake on resolve
    22612275} mDNSStatistics;
     2276
    22622277extern void LogMDNSStatistics(mDNS *const m);
    22632278
     
    22702285
    22712286    mDNS_PlatformSupport *p;            // Pointer to platform-specific data of indeterminite size
     2287    mDNSs32 NetworkChanged;
    22722288    mDNSBool CanReceiveUnicastOn5353;
    22732289    mDNSBool AdvertiseLocalAddresses;
     
    23692385    mDNSu32 NumFailedProbes;
    23702386    mDNSs32 SuppressProbes;
    2371     Platform_t mDNS_plat;
     2387    Platform_t mDNS_plat;                               // Why is this here in the “only required for mDNS Responder” section? -- SC
    23722388
    23732389    // Unicast-specific data
     
    24552471    TrustAnchor     *TrustAnchors;
    24562472    int             notifyToken;
    2457     int             uds_listener_skt;           // Listening socket for incoming UDS clients
    2458     mDNSBool        mDNSOppCaching;             // Opportunistic Caching
     2473    int             uds_listener_skt;           // Listening socket for incoming UDS clients. This should not be here -- it's private to uds_daemon.c and nothing to do with mDNSCore -- SC
    24592474    mDNSu32         AutoTargetServices;         // # of services that have AutoTarget set
     2475    mDNSu32         NumAllInterfaceRecords;             // Right now we count *all* multicast records here. Later we may want to change to count interface-specific records separately. (This count includes records on the DuplicateRecords list too.)
     2476    mDNSu32         NumAllInterfaceQuestions;   // Right now we count *all* multicast questions here. Later we may want to change to count interface-specific questions separately.
    24602477    DNSSECStatistics DNSSECStats;
    24612478    mDNSStatistics   mDNSStats;
     
    24692486
    24702487#define FORALL_CACHERECORDS(SLOT,CG,CR)                           \
    2471     for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++)                                                                   \
    2472         for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next)                                                                   \
     2488    for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++)         \
     2489        for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
    24732490            for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
    24742491
     
    25312548extern mDNSBool StrictUnicastOrdering;
    25322549extern mDNSu8 NumUnicastDNSServers;
     2550#if APPLE_OSX_mDNSResponder
     2551extern mDNSu8 NumUnreachableDNSServers;
     2552#endif
    25332553
    25342554#define localdomain           (*(const domainname *)"\x5" "local")
     
    26492669extern void    mDNS_ConfigChanged(mDNS *const m);
    26502670extern void    mDNS_GrowCache (mDNS *const m, CacheEntity *storage, mDNSu32 numrecords);
    2651 extern void    mDNS_GrowAuth (mDNS *const m, AuthEntity *storage, mDNSu32 numrecords);
    26522671extern void    mDNS_StartExit (mDNS *const m);
    26532672extern void    mDNS_FinalExit (mDNS *const m);
     
    27852804
    27862805extern mDNSOpaque16 mDNS_NewMessageID(mDNS *const m);
    2787 extern mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr, mDNSBool *myself);
     2806extern mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr);
    27882807
    27892808extern DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question);
     
    31963215
    31973216extern void       mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason);
     3217extern void       mDNSPlatformPreventSleep(mDNS *const m, mDNSu32 timeout, const char *reason);
    31983218extern void       mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration);
    31993219
     
    33183338// For now this LocalSleepProxy stuff is specific to Mac OS X.
    33193339// In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
    3320 extern mStatus ActivateLocalProxy(mDNS *const m, NetworkInterfaceInfo *const intf);
     3340extern mStatus ActivateLocalProxy(mDNS *const m, NetworkInterfaceInfo *const intf, mDNSBool *keepaliveOnly);
    33213341extern void mDNSPlatformUpdateDNSStatus(mDNS *const m, DNSQuestion *q);
    33223342extern void mDNSPlatformTriggerDNSRetry(mDNS *const m, DNSQuestion *v4q, DNSQuestion *v6q);
    33233343extern void mDNSPlatformLogToFile(int log_level, const char *buffer);
    33243344extern mDNSBool SupportsInNICProxy(NetworkInterfaceInfo *const intf);
     3345extern mStatus SymptomReporterDNSServerReachable(mDNS *const m, const mDNSAddr *addr);
     3346extern mStatus SymptomReporterDNSServerUnreachable(DNSServer *s);
    33253347#endif
    33263348
     
    33373359#endif
    33383360
    3339 extern mDNSBool mDNSPlatformAllowPID(mDNS *const m, DNSQuestion *q);
    3340 extern mDNSs32 mDNSPlatformGetServiceID(mDNS *const m, DNSQuestion *q);
     3361extern void mDNSPlatformGetDNSRoutePolicy(mDNS *const m, DNSQuestion *q, mDNSBool *isBlocked);
    33413362extern void mDNSPlatformSetuDNSSocktOpt(UDPSocket *src, const mDNSAddr *dst, DNSQuestion *q);
    33423363extern mDNSs32 mDNSPlatformGetPID(void);
    3343 
     3364extern mDNSBool mDNSValidKeepAliveRecord(AuthRecord *rr);
     3365   
    33443366// ***************************************************************************
    33453367#if 0
     
    35573579    char sizecheck_CacheRecord         [(sizeof(CacheRecord)          <=   232) ? 1 : -1];
    35583580    char sizecheck_CacheGroup          [(sizeof(CacheGroup)           <=   232) ? 1 : -1];
    3559     char sizecheck_DNSQuestion         [(sizeof(DNSQuestion)          <=   832) ? 1 : -1];
    3560 
    3561 // Checks commented out when sizeof(DNSQuestion) change cascaded into having to change yet another
    3562 // set of hardcoded size values because these structures contain one or more DNSQuestion
    3563 // instances.
    3564 //     char sizecheck_ZoneData            [(sizeof(ZoneData)             <=  1648) ? 1 : -1];
     3581    char sizecheck_DNSQuestion         [(sizeof(DNSQuestion)          <=   864) ? 1 : -1];
     3582
     3583    char sizecheck_ZoneData            [(sizeof(ZoneData)             <=  1700) ? 1 : -1];
    35653584    char sizecheck_NATTraversalInfo    [(sizeof(NATTraversalInfo)     <=   200) ? 1 : -1];
    35663585    char sizecheck_HostnameInfo        [(sizeof(HostnameInfo)         <=  3050) ? 1 : -1];
    35673586    char sizecheck_DNSServer           [(sizeof(DNSServer)            <=   340) ? 1 : -1];
    3568 //    char sizecheck_NetworkInterfaceInfo[(sizeof(NetworkInterfaceInfo) <=  6988) ? 1 : -1];
     3587    char sizecheck_NetworkInterfaceInfo[(sizeof(NetworkInterfaceInfo) <=  7184) ? 1 : -1];
    35693588    char sizecheck_ServiceRecordSet    [(sizeof(ServiceRecordSet)     <=  5540) ? 1 : -1];
    35703589    char sizecheck_DomainAuthInfo      [(sizeof(DomainAuthInfo)       <=  7888) ? 1 : -1];
    3571 //    char sizecheck_ServiceInfoQuery    [(sizeof(ServiceInfoQuery)     <=  3302) ? 1 : -1];
     3590    char sizecheck_ServiceInfoQuery    [(sizeof(ServiceInfoQuery)     <=  3488) ? 1 : -1];
    35723591#if APPLE_OSX_mDNSResponder
    3573 //    char sizecheck_ClientTunnel        [(sizeof(ClientTunnel)         <=  1160) ? 1 : -1];
     3592    char sizecheck_ClientTunnel        [(sizeof(ClientTunnel)         <=  1208) ? 1 : -1];
    35743593#endif
    35753594};
  • mDNSResponder/mDNSCore/nsec.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    612612    const domainname *oname = rr->name; // owner name
    613613
    614     if (wildcard) *wildcard = mDNSNULL;
     614    *wildcard = mDNSNULL;
    615615    // RFC 4035
    616616    //
     
    677677        if (oname->c[0] == 1 && oname->c[1] == '*')
    678678        {
    679             int r, s;
     679            int s;
    680680            const domainname *ce = SkipLeadingLabels(oname, 1);
    681681
    682             r = DNSSECCanonicalOrder(name, ce, &s);
     682            DNSSECCanonicalOrder(name, ce, &s);
    683683            if (s)
    684684            {
     
    913913        // will verify the noname nsec
    914914        dv->pendingNSEC = r;
    915         LogDNSSEC("NoDataProof: Verifying wild and noname %s", RRDisplayString(m, nsec_wild));
     915        LogDNSSEC("NoDataProof: Verifying wild and noname %s", nsec_wild ? RRDisplayString(m, nsec_wild) : "NULL");
    916916        VerifyNSEC(m, nsec_wild, mDNSNULL, dv, ncr, NoDataNSECCallback);
    917917    }
     
    919919             (dv->flags & NSEC_PROVES_NOTYPE_EXISTS))
    920920    {
    921         LogDNSSEC("NoDataProof: Verifying wild %s", RRDisplayString(m, nsec_wild));
     921        LogDNSSEC("NoDataProof: Verifying wild %s", nsec_wild ? RRDisplayString(m, nsec_wild) : "NULL");
    922922        VerifyNSEC(m, nsec_wild, mDNSNULL, dv, ncr, mDNSNULL);
    923923    }
    924924    else if (dv->flags & NSEC_PROVES_NONAME_EXISTS)
    925925    {
    926         LogDNSSEC("NoDataProof: Verifying noname %s", RRDisplayString(m, nsec_noname));
     926        LogDNSSEC("NoDataProof: Verifying noname %s", nsec_noname ? RRDisplayString(m, nsec_noname) : "NULL");
    927927        VerifyNSEC(m, nsec_noname, mDNSNULL, dv, ncr, mDNSNULL);
    928928    }
  • mDNSResponder/mDNSCore/nsec.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#ifndef __NSEC_H
    1819#define __NSEC_H
  • mDNSResponder/mDNSCore/nsec3.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    333333            }
    334334
    335             if ((val == NSEC3Covers || val == NSEC3CEProof) && !(*closerEncloser))
     335            if ((val == NSEC3Covers || val == NSEC3CEProof) && (!closerEncloser || !(*closerEncloser)))
    336336            {
    337337                if (NSEC3CoversName(m, cr, hashName, hlen, b32Name, b32len))
     
    350350        // was set, then the proof is complete, and SNAME is the closest
    351351        // encloser.
    352         if (val == NSEC3CEProof)
    353         {
    354             if (*closestEncloser && *closerEncloser)
     352        if (val == NSEC3CEProof && closestEncloser && *closestEncloser)
     353        {
     354            if (closerEncloser && *closerEncloser)
    355355            {
    356356                LogDNSSEC("NSEC3Find: Found closest and closer encloser");
    357357                return mDNStrue;
    358358            }
    359 
    360             // 2.4) If there is a matching NSEC3 RR in the response, but the flag
    361             // is not set, then the response is bogus.
    362             //
    363             // Note: We don't have to wait till we finish trying all the names. If the matchName
    364             // happens, we found the closest encloser which means we should have found the closer
    365             // encloser before.
    366 
    367             if (*closestEncloser && !(*closerEncloser))
    368             {
     359            else
     360            {
     361                // 2.4) If there is a matching NSEC3 RR in the response, but the flag
     362                // is not set, then the response is bogus.
     363                //
     364                // Note: We don't have to wait till we finish trying all the names. If the matchName
     365                // happens, we found the closest encloser which means we should have found the closer
     366                // encloser before.
     367
    369368                LogDNSSEC("NSEC3Find: Found closest, but not closer encloser");
    370369                return mDNSfalse;
     
    389388    if (!closestEncloser || !closerEncloser || !ce)
    390389    {
    391         LogMsg("NSEC3ClosestEncloserProof: ClosestEncloser %p or CloserEncloser %p ce %p, something is NULL", *closestEncloser,
    392             *closerEncloser, *ce);
     390        LogMsg("NSEC3ClosestEncloserProof: ClosestEncloser %p or CloserEncloser %p ce %p, something is NULL", closestEncloser, closerEncloser, ce);
    393391        return mDNSfalse;
    394392    }
  • mDNSResponder/mDNSCore/nsec3.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSCore/uDNS.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2013 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    5252mDNSu8 NumUnicastDNSServers = 0;
    5353#define MAX_UNICAST_DNS_SERVERS 64
     54#if APPLE_OSX_mDNSResponder
     55mDNSu8 NumUnreachableDNSServers = 0;
     56#endif
    5457
    5558#define SetNextuDNSEvent(m, rr) { \
     
    165168    if (tmp)
    166169    {
     170#if APPLE_OSX_mDNSResponder
     171        if (tmp->flags & DNSServer_FlagDelete)
     172        {
     173            tmp->flags &= ~DNSServer_FlagUnreachable;
     174        }
     175#endif
    167176        tmp->flags &= ~DNSServer_FlagDelete;
    168177        *p = tmp; // move to end of list, to ensure ordering from platform layer
     
    215224    DNSServer *new;
    216225    DNSServer *orig = q->qDNSServer;
    217 
     226    mDNSu8 rcode = '\0';
     227   
    218228    mDNS_CheckLock(m);
    219229
     
    225235    if (mDNSOpaque16IsZero(q->responseFlags))
    226236        q->responseFlags = responseFlags;
     237   
     238    rcode = (mDNSu8)(responseFlags.b[1] & kDNSFlag1_RC_Mask);
    227239
    228240    // After we reset the qDNSServer to NULL, we could get more SERV_FAILS that might end up
    229241    // peanlizing again.
    230     if (!q->qDNSServer) goto end;
     242    if (!q->qDNSServer)
     243        goto end;
    231244
    232245    // If strict ordering of unicast servers needs to be preserved, we just lookup
     
    246259        {
    247260            LogInfo("PenalizeDNSServer: Not Penalizing PTR question");
     261        }
     262        else if ((rcode == kDNSFlag1_RC_FormErr) || (rcode == kDNSFlag1_RC_ServFail) || (rcode == kDNSFlag1_RC_NotImpl) || (rcode == kDNSFlag1_RC_Refused))
     263        {
     264            LogInfo("PenalizeDNSServer: Not Penalizing DNS Server since it at least responded with rcode %d", rcode);
    248265        }
    249266        else
     
    813830        if (traversal == *n)
    814831        {
    815             LogMsg("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
     832            LogFatalError("Error! Tried to add a NAT traversal that's already in the active list: request %p Prot %d Int %d TTL %d",
    816833                   traversal, traversal->Protocol, mDNSVal16(traversal->IntPort), traversal->NATLease);
    817             #if ForceAlerts
    818             *(long*)0 = 0;
    819             #endif
    820834            return(mStatus_AlreadyRegistered);
    821835        }
     
    18951909    zd->question.AnonInfo            = mDNSNULL;
    18961910    zd->question.pid                 = mDNSPlatformGetPID();
     1911    zd->question.euid                = 0;
    18971912    zd->question.QuestionCallback    = GetZoneData_QuestionCallback;
    18981913    zd->question.QuestionContext     = zd;
     
    25842599    q->AnonInfo         = mDNSNULL;
    25852600    q->pid              = mDNSPlatformGetPID();
     2601    q->euid             = 0;
    25862602    q->QuestionCallback = FoundStaticHostname;
    25872603    q->QuestionContext  = mDNSNULL;
     
    39924008           msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y,  " : "ies,",
    39934009           msg->h.numAdditionals, msg->h.numAdditionals == 1 ? ""     : "s", end - msg->data);
     4010#if APPLE_OSX_mDNSResponder
     4011    if (NumUnreachableDNSServers > 0)
     4012        SymptomReporterDNSServerReachable(m, srcaddr);
     4013#endif
    39944014
    39954015    if (QR_OP == StdR)
     
    41424162    q->servPort = zeroIPPort;
    41434163
    4144     if (!err && zoneInfo && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
     4164    if (!err && !mDNSIPPortIsZero(zoneInfo->Port) && !mDNSAddressIsZero(&zoneInfo->Addr) && zoneInfo->Host.c[0])
    41454165    {
    41464166        q->servAddr = zoneInfo->Addr;
     
    42394259mDNSexport void RecordRegistrationGotZoneData(mDNS *const m, mStatus err, const ZoneData *zoneData)
    42404260{
    4241     AuthRecord *newRR = (AuthRecord*)zoneData->ZoneDataContext;
     4261    AuthRecord *newRR;
    42424262    AuthRecord *ptr;
    42434263    int c1, c2;
     4264
     4265    if (!zoneData) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
     4266   
     4267    newRR = (AuthRecord*)zoneData->ZoneDataContext;
    42444268
    42454269    if (newRR->nta != zoneData)
     
    42674291        return;
    42684292    }
    4269 
    4270     if (!zoneData) { LogMsg("ERROR: RecordRegistrationGotZoneData invoked with NULL result and no error"); return; }
    42714293
    42724294    if (newRR->resrec.rrclass != zoneData->ZoneClass)
     
    46574679        // DNSSEC_VALIDATION_SECURE questions ignores req_DO.
    46584680
    4659         if (q->qDNSServer && !q->qDNSServer->DNSSECAware && q->qDNSServer->req_DO)
     4681        if (!q->qDNSServer->DNSSECAware && q->qDNSServer->req_DO)
    46604682        {
    46614683            q->qDNSServer->retransDO++;
     
    47154737                        q->unansweredQueries, q->qname.c, DNSTypeName(q->qtype), &orig->addr, mDNSVal16(orig->port), orig->domain.c);
    47164738
     4739#if APPLE_OSX_mDNSResponder
     4740            SymptomReporterDNSServerUnreachable(orig);
     4741#endif
    47174742            PenalizeDNSServer(m, q, zeroID);
    47184743            q->noServerResponse = 1;
     
    47994824                    }
    48004825                    if (!q->LocalSocket) err = mStatus_NoMemoryErr; // If failed to make socket (should be very rare), we'll try again next time
    4801                     else err = mDNSSendDNSMessage(m, &m->omsg, end, q->qDNSServer->interface, q->LocalSocket, &q->qDNSServer->addr, q->qDNSServer->port, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
     4826                    else
     4827                    {
     4828                        err = mDNSSendDNSMessage(m, &m->omsg, end, q->qDNSServer->interface, q->LocalSocket, &q->qDNSServer->addr, q->qDNSServer->port, mDNSNULL, mDNSNULL, q->UseBackgroundTrafficClass);
     4829#if TARGET_OS_EMBEDDED
     4830                        if (!err)
     4831                        {
     4832                            if (q->metrics.querySendCount++ == 0)
     4833                            {
     4834                                q->metrics.firstQueryTime = m->timenow;
     4835                            }
     4836                        }
     4837#endif
     4838                    }
    48024839                }
    48034840            }
     
    49174954mDNSexport void CheckNATMappings(mDNS *m)
    49184955{
    4919     mStatus err = mStatus_NoError;
    49204956    mDNSBool rfc1918 = mDNSv4AddrIsRFC1918(&m->AdvertisedV4.ip.v4);
    49214957    mDNSBool HaveRoutable = !rfc1918 && !mDNSIPv4AddressIsZero(m->AdvertisedV4.ip.v4);
     
    49755011                }
    49765012
    4977                 err = uDNS_SendNATMsg(m, cur, mDNStrue); // Will also do UPnP discovery for us, if necessary
     5013                uDNS_SendNATMsg(m, cur, mDNStrue); // Will also do UPnP discovery for us, if necessary
    49785014
    49795015                if (cur->ExpiryTime)                        // If have active mapping then set next renewal time halfway to expiry
  • mDNSResponder/mDNSMacOSX/BonjourEvents.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2010 Apple Inc. All rights reserved.
     3 * Copyright (c) 2010-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    292292    BonjourUserEventsPlugin * result = NULL;
    293293
    294     if (typeID && CFEqual(typeID, kUserEventAgentTypeID)) {
     294    if (typeID && CFEqual(typeID, kUserEventAgentTypeID))
     295    {
    295296        result = Alloc(kUserEventAgentFactoryID);
    296297    }
     
    604605        // Add the dictionary to the browsers dictionary.
    605606        CFDictionarySetValue(plugin->_browsers, browser, browserDict);
    606 
    607         NetBrowserInfoRelease(NULL, browser);
    608607
    609608        // Release Memory
  • mDNSResponder/mDNSMacOSX/CryptoSupport.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    351351mDNSlocal SecKeyRef rfc3110_import(const mDNSu8 *data, const mDNSu32 len)
    352352{
    353     static const int max_key_bytes = 4096 / 8;                // max DNSSEC supported modulus is 4096 bits
    354     static const int max_exp_bytes = 3;                       // DNSSEC supports 1 or 3 bytes for exponent
    355     static const int asn1_cmd_bytes = 3;                      // since there is an ASN1 SEQ and two INTs
    356     //static const int asn1_max_len_bytes = asn1_cmd_bytes * 3; // capped at 3 due to max payload size
    357     static const int asn1_max_len_bytes = 3 * 3; // capped at 3 due to max payload size
    358     unsigned char asn1[max_key_bytes + 1 + max_exp_bytes + asn1_cmd_bytes + asn1_max_len_bytes]; // +1 is for leading 0 for non negative asn1 number
     353    static const int max_modulus_bytes = 512;    // Modulus is limited to 4096 bits (512 octets) in length.
     354    static const int max_exp_bytes = 512;        // Exponent is limited to 4096 bits (512 octets) in length.
     355    static const int asn1_type_bytes = 3;        // Since there is an ASN1 SEQ and two INTs.
     356    static const int asn1_max_len_bytes = 3 * 3; // Capped at 3 due to max payload size.
     357    unsigned char asn1[max_modulus_bytes + 1 + max_exp_bytes + asn1_type_bytes + asn1_max_len_bytes]; // +1 is for leading 0 for non negative asn1 number
    359358    const mDNSu8 *modulus;
    360359    unsigned int modulus_length;
     360    const mDNSu8 *exponent;
    361361    unsigned int exp_length;
     362    unsigned int num_length_bytes;
    362363    mDNSu32 index = 0;
    363364    mDNSu32 asn1_length = 0;
    364     unsigned int i;
    365365
    366366    // Validate Input
     
    373373
    374374    // Parse Modulus and Exponent
    375     exp_length = data[0];
    376 
    377     // we have to have at least len byte + size of exponent
    378     if (len < 1+exp_length)
    379         return NULL;
    380 
    381     // -1 is for the exp_length byte
    382     modulus_length = len - 1 - exp_length;
    383 
    384     // rfc3110 limits modulus to 4096 bits
     375
     376    // If the first byte is zero, then the exponent length is in the three-byte format, otherwise the length is in the first byte.
     377    if (data[0] == 0)
     378    {
     379        if (len < 3)
     380            return NULL;
     381        exp_length = (data[1] << 8) | data[2];
     382        num_length_bytes = 3;
     383    }
     384    else
     385    {
     386        exp_length = data[0];
     387        num_length_bytes = 1;
     388    }
     389
     390    // RFC3110 limits the exponent length to 4096 bits (512 octets).
     391    if (exp_length > 512)
     392        return NULL;
     393
     394    // We have to have at least len bytes + size of exponent.
     395    if (len < (num_length_bytes + exp_length))
     396        return NULL;
     397
     398    // The modulus is the remaining space.
     399    modulus_length = len - (num_length_bytes + exp_length);
     400
     401    // RFC3110 limits the modulus length to 4096 bits (512 octets).
    385402    if (modulus_length > 512)
    386403        return NULL;
     
    392409    ++modulus_length;
    393410
    394     // 1 is to skip exp_length byte
    395     modulus = &data[1+exp_length];
     411    exponent = &data[num_length_bytes];
     412    modulus = &data[num_length_bytes + exp_length];
    396413
    397414    // 2 bytes for commands since first doesn't count
     
    399416    asn1_length = modulus_length + exp_length + 2 + 2;
    400417
    401     // account for modulus length causing INT length field to grow
    402     if (modulus_length > 0xFF)
    403         asn1_length += 2;
    404     else if (modulus_length >= 128)
    405         ++asn1_length;
     418    // Account for modulus length causing INT length field to grow.
     419    if (modulus_length >= 128)
     420    {
     421        if (modulus_length > 255)
     422            asn1_length += 2;
     423        else
     424            asn1_length += 1;
     425    }
     426
     427    // Account for exponent length causing INT length field to grow.
     428    if (exp_length >= 128)
     429    {
     430        if (exp_length > 255)
     431            asn1_length += 2;
     432        else
     433            asn1_length += 1;
     434    }
    406435
    407436    // Construct ASN1 formatted public key
     
    416445    else
    417446    {
    418         asn1[index++] = (0x80 | ((asn1_length & 0xFF00) ? 2 : 1));
    419         if (asn1_length & 0xFF00)
     447        asn1[index++] = (0x80 | ((asn1_length > 255) ? 2 : 1));
     448        if (asn1_length > 255)
    420449            asn1[index++] = (asn1_length & 0xFF00) >> 8;
    421450        asn1[index++] = asn1_length & 0xFF;
     
    427456    if (modulus_length < 128)
    428457    {
    429         asn1[index++] = asn1_length & 0xFF;
     458        asn1[index++] = modulus_length & 0xFF;
    430459    }
    431460    else
    432461    {
    433         asn1[index++] = 0x80 | ((modulus_length & 0xFF00) ? 2 : 1);
    434         if (modulus_length & 0xFF00)
     462        asn1[index++] = 0x80 | ((modulus_length > 255) ? 2 : 1);
     463        if (modulus_length > 255)
    435464            asn1[index++] = (modulus_length & 0xFF00) >> 8;
    436465        asn1[index++] = modulus_length & 0xFF;
     
    440469    asn1[index++] = 0x00;
    441470    // Write actual modulus (-1 for preceding 0)
    442     memcpy(&asn1[index], (void *)modulus, modulus_length-1);
    443     index += modulus_length-1;
     471    memcpy(&asn1[index], modulus, modulus_length - 1);
     472    index += (modulus_length - 1);
    444473
    445474    // Write ASN1 INT for exponent
    446475    asn1[index++] = 0x02;
    447476    // Write ASN1 length for INT
    448     asn1[index++] = exp_length & 0xFF;
     477    if (exp_length < 128)
     478    {
     479        asn1[index++] = exp_length & 0xFF;
     480    }
     481    else
     482    {
     483        asn1[index++] = 0x80 | ((exp_length > 255) ? 2 : 1);
     484        if (exp_length > 255)
     485            asn1[index++] = (exp_length & 0xFF00) >> 8;
     486        asn1[index++] = exp_length & 0xFF;
     487    }
    449488    // Write exponent bytes
    450     for (i = 1; i <= exp_length; i++)
    451         asn1[index++] = data[i];
     489    memcpy(&asn1[index], exponent, exp_length);
     490    index += exp_length;
    452491
    453492#if TARGET_OS_IPHONE
     
    606645   
    607646    CFBooleanRef boolRef = SecTransformExecute(verifyXForm, &error);
     647    ret = boolRef ? CFBooleanGetValue(boolRef) : false;
     648    if (boolRef) CFRelease(boolRef);
    608649    CFRelease(verifyXForm);
    609650
     
    619660                LogMsg("VerifyData: CFStringGetCString failed");
    620661            }
     662            CFRelease(errStr);
    621663        }
    622664        LogMsg("VerifyData: SecTransformExecute failed with %s", errorbuf);
    623665        return false;
    624666    }
    625     return CFEqual(boolRef, kCFBooleanTrue);   
     667    return ret;
    626668err:
    627669    CFRelease(verifyXForm);
  • mDNSResponder/mDNSMacOSX/CryptoSupport.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#ifndef __CRYPTO_SUPPORT_H
    1819#define __CRYPTO_SUPPORT_H
  • mDNSResponder/mDNSMacOSX/DNSProxySupport.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2011 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2011-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    1515 * limitations under the License.
    1616 */
     17
    1718#include "mDNSEmbeddedAPI.h"
    1819#include "mDNSMacOSX.h"
     
    262263    KQueueEntry *k        = (sa_family == AF_INET) ? &cp->kqsv4 : &cp->kqsv6;
    263264    const int on = 1;
    264     mDNSIPPort port;
    265265    mStatus err = mStatus_NoError;
    266266
    267267    cp->m = m;
    268     port = cp->port;
    269268    cp->closeFlag = mDNSNULL;
    270269
     
    340339    int         *s        = (sa_family == AF_INET) ? &cp->sktv4 : &cp->sktv6;
    341340    KQueueEntry *k        = (sa_family == AF_INET) ? &cp->kqsv4 : &cp->kqsv6;
    342     mDNSIPPort port;
    343341    mStatus err;
    344342
    345343    cp->m = m;
    346     port = cp->port;
    347344    // XXX may not be used by the TCP codepath
    348345    cp->closeFlag = mDNSNULL;
     
    385382        err = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
    386383        if (err < 0)
    387             LogMsg("BindDPSocket: setsockopt SO_REUSEPORT failed for V4 %d errno %d (%s)", fd, errno, strerror(errno));
     384            LogMsg("BindDPSocket: setsockopt SO_REUSEPORT failed for IPv4 %d errno %d (%s)", fd, errno, strerror(errno));
    388385
    389386        memset(&addr, 0, sizeof(addr));
  • mDNSResponder/mDNSMacOSX/DNSSECSupport.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2012-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    450450    }
    451451
     452#pragma clang diagnostic push
     453#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    452454    // If we can't fetch the XML file e.g., network problems, trigger a timer. All other failures
    453455    // should hardly happen in practice for which schedule the normal interval to refetch the TA.
    454     if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, url, &xmlData, NULL, NULL, NULL))
     456    Boolean success = CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, url, &xmlData, NULL, NULL, NULL);
     457#pragma clang diagnostic pop
     458    if (!success)
    455459    {
    456460        LogInfo("FetchRootTA: CFURLCreateDataAndPropertiesFromResource error");
     
    480484        (int)CFDataGetLength(xmlData), xmlFileName, NULL, 0);       
    481485
    482     CFRelease(fileRef);
     486    if (fileRef)
     487        CFRelease(fileRef);
    483488    CFRelease(url);
    484489    CFRelease(xmlData);
  • mDNSResponder/mDNSMacOSX/DNSSECSupport.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2012-2013 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSMacOSX/DNSServiceDiscovery.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2012 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    454454void DNSServiceDiscovery_handleReply(void *replyMsg)
    455455{
    456     unsigned long result = 0xFFFFFFFF;
    457456    mach_msg_header_t *     msgSendBufPtr;
    458457    mach_msg_header_t *     receivedMessage;
     
    467466    // Call DNSServiceDiscoveryReply_server to change mig-generated message into a
    468467    // genuine mach message. It will then cause the callback to get called.
    469     result = DNSServiceDiscoveryReply_server ( receivedMessage, msgSendBufPtr );
     468    DNSServiceDiscoveryReply_server ( receivedMessage, msgSendBufPtr );
    470469    ( void ) mach_msg_send ( msgSendBufPtr );
    471470    free(msgSendBufPtr);
  • mDNSResponder/mDNSMacOSX/DNSServiceDiscovery.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002, 2004, 2006, 2011 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSMacOSX/DNSServiceDiscoveryDefines.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2003, 2006, 2009, 2011 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSMacOSX/DNSServiceDiscoveryReply.defs

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2003, 2006 Apple Computer, Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSMacOSX/DNSServiceDiscoveryRequest.defs

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2002-2004, 2006 Apple Computer, Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
  • mDNSResponder/mDNSMacOSX/LegacyNATTraversal.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2004-2013 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2004-2015 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
     
    2323
    2424#if defined( WIN32 )
     25#   include "CommonServices.h"
    2526#   include <winsock2.h>
    2627#   include <ws2tcpip.h>
     
    8384{
    8485    if (src == mDNSNULL) return;
    85     if ((*dst = mDNSPlatformMemAllocate((mDNSu32)strlen((char*)src) + 1)) == mDNSNULL)
    86     { LogMsg("AllocAndCopy: can't allocate string"); return; }
     86    if ((strlen((char*)src)) >= UINT32_MAX || (*dst = mDNSPlatformMemAllocate((mDNSu32)strlen((char*)src) + 1)) == mDNSNULL)
     87    {
     88        LogMsg("AllocAndCopy: can't allocate string");
     89        return;
     90    }
    8791    strcpy((char*)*dst, (char*)src);
    8892}
     
    280284            ptr += 8; // skip over "URLBase>"
    281285            // find the end of the URLBase element
    282             for (stop = ptr; stop < end; stop++) { if (*stop == '<') { end = stop; break; } }
     286            for (stop = ptr; stop < end; stop++) { if (stop && *stop == '<') { end = stop; break; } }
    283287            if (ParseHttpUrl(ptr, end, &m->UPnPSOAPAddressString, &m->UPnPSOAPPort, mDNSNULL) != mStatus_NoError)
    284288            {
     
    413417    static int LNTERRORcount = 0;
    414418
    415     if (tcpInfo == mDNSNULL) { LogInfo("tcpConnectionCallback: no tcpInfo context"); status = mStatus_Invalid; goto exit; }
    416    
    417419    if (tcpInfo->sock != sock)
    418420    {
     
    794796    const mDNSu8 *ptr = data;
    795797    const mDNSu8 *end = data + len;
    796     const mDNSu8 *stop = ptr;
     798    const mDNSu8 *stop;
    797799
    798800    if (!mDNSIPPortIsZero(m->UPnPRouterPort)) return; // already have the info we need
  • mDNSResponder/mDNSMacOSX/Metrics.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
     3 * Copyright (c) 2016 Apple Inc. All rights reserved.
    44 *
    55 * Licensed under the Apache License, Version 2.0 (the "License");
    66 * you may not use this file except in compliance with the License.
    77 * You may obtain a copy of the License at
    8  * 
     8 *
    99 *     http://www.apache.org/licenses/LICENSE-2.0
    10  * 
     10 *
    1111 * Unless required by applicable law or agreed to in writing, software
    1212 * distributed under the License is distributed on an "AS IS" BASIS,
     
    1616 */
    1717
    18 data 'carb' (0) { };
     18#include "mDNSEmbeddedAPI.h"
     19
     20#ifndef __Metrics_h
     21#define __Metrics_h
     22
     23#ifdef  __cplusplus
     24extern "C" {
     25#endif
     26
     27#if TARGET_OS_EMBEDDED
     28mStatus MetricsInit(void);
     29void    MetricsUpdateUDNSStats(const domainname *inQueryName, mDNSBool inAnswered, mDNSu32 inSendCount, mDNSu32 inLatencyMs, mDNSBool inForCellular);
     30void    LogMetrics(void);
     31#endif
     32
     33#ifdef  __cplusplus
     34}
     35#endif
     36
     37#endif // __Metrics_h
  • mDNSResponder/mDNSMacOSX/P2PPacketFilter.c

    r49ebc73 rf761b29  
    1 /*
     1/* -*- Mode: C; tab-width: 4 -*-
    22 *
    33 * Copyright (c) 2011 Apple Inc. All rights reserved.
     
    251251
    252252    // open inbound port for each service
    253     for (i = 0; i < count; i++) {
     253    for (i = 0; i < count; i++)
     254    {
    254255        initPortRule( &pr, interfaceName, ticket, poolTicket, anchorPath, portArray[i], protocolArray[i] );
    255256        result = addRule( devFD, &pr );
  • mDNSResponder/mDNSMacOSX/P2PPacketFilter.h

    r49ebc73 rf761b29  
    1 /*
     1/* -*- Mode: C; tab-width: 4 -*-
    22 *
    33 * Copyright (c) 2011 Apple Inc. All rights reserved.
  • mDNSResponder/mDNSMacOSX/PreferencePane/DNSServiceDiscoveryPref.m

    r49ebc73 rf761b29  
    44    Abstract: System Preference Pane for Dynamic DNS and Wide-Area DNS Service Discovery
    55
    6     Copyright: (c) Copyright 2005-2011 Apple Computer, Inc. All rights reserved.
    7 
    8     Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
     6    Copyright: (c) Copyright 2005-2011 Apple Inc. All rights reserved.
     7
     8    Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
    99    ("Apple") in consideration of your agreement to the following terms, and your
    1010    use, installation, modification or redistribution of this Apple software
     
    2020    this notice and the following text and disclaimers in all such redistributions of
    2121    the Apple Software.  Neither the name, trademarks, service marks or logos of
    22     Apple Computer, Inc. may be used to endorse or promote products derived from the
     22    Apple Inc. may be used to endorse or promote products derived from the
    2323    Apple Software without specific prior written permission from Apple.  Except as
    2424    expressly stated in this notice, no other rights or licenses, express or implied,
     
    9797    NSComboBox * domainComboBox;
    9898    NSString * domainString;
    99     NSString * currentDomain = nil;
    100         char decodedDomainString[kDNSServiceMaxDomainName] = "\0";
     99    char decodedDomainString[kDNSServiceMaxDomainName] = "\0";
    101100    char nextLabel[256] = "\0";
    102101    char * buffer = (char *)replyDomain;
     
    116115        domainArray    = [me registrationDataSource];
    117116        domainComboBox = [me regDomainsComboBox];
    118         currentDomain  = [me currentRegDomain];
    119117    } else {
    120118        domainArray    = [me browseDataSource];
     
    262260   
    263261        CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopCommonModes);
     262        CFRelease(rls);
    264263
    265264    CFRelease(keys);
     
    335334    }
    336335
    337     [origDict release];
     336    CFRelease((CFDictionaryRef)origDict);
    338337    CFRelease(store);
    339338}
     
    395394        [tableView reloadData];
    396395        [self updateApplyButtonState];
     396        [browseDomainDict release];
    397397}
    398398
     
    682682    NSString *hostNameString  = [hostName stringValue];
    683683    NSString *regDomainString = [regDomainsComboBox stringValue];
    684    
    685     NSComparisonResult hostNameResult  = [hostNameString    compare:currentHostName];
    686     NSComparisonResult regDomainResult = [regDomainString  compare:currentRegDomain];
    687 
    688     if ((currentHostName && (hostNameResult != NSOrderedSame)) ||
    689         (currentRegDomain && (regDomainResult != NSOrderedSame) && ([wideAreaCheckBox state])) ||
     684    if ((currentHostName && ([hostNameString compare:currentHostName] != NSOrderedSame)) ||
     685        (currentRegDomain && ([regDomainString compare:currentRegDomain] != NSOrderedSame) && ([wideAreaCheckBox state])) ||
    690686        (currentHostName == nil && ([hostNameString length]) > 0) ||
    691687        (currentRegDomain == nil && ([regDomainString length]) > 0) ||
     
    947943                CFRelease(itemRef);
    948944        }
    949     return keyName;
     945    return [keyName autorelease];
    950946}
    951947
     
    1001997{
    1002998    NSString      *hostNameString               = [hostName stringValue];
    1003     NSString      *browseDomainString           = [browseDomainsComboBox stringValue];
    1004999    NSString      *regDomainString              = [regDomainsComboBox stringValue];
    10051000    NSString      *tempHostNameSharedSecretName = hostNameSharedSecretName;
     
    10111006
    10121007        hostNameString                = [self trimCharactersFromDomain:hostNameString];
    1013         browseDomainString            = [self trimCharactersFromDomain:browseDomainString];
    10141008        regDomainString               = [self trimCharactersFromDomain:regDomainString];
    10151009        tempHostNameSharedSecretName  = [self trimCharactersFromDomain:tempHostNameSharedSecretName];
  • mDNSResponder/mDNSMacOSX/PreferencePane/English.lproj/InfoPlist.strings

    r49ebc73 rf761b29  
    1 /* Localized versions of Info.plist keys */
     1/* Localized versions of Info.plist keys */
    22
    33CFBundleName = "Bonjour";
    4 CFBundleGetInfoString = "Bonjour version 1.0, Copyright (c) 2005,2006, Apple Computer, Inc.";
    5 NSHumanReadableCopyright = "Copyright (c) 2005,2006, Apple Computer, Inc.";
     4CFBundleGetInfoString = "Bonjour version 1.0, Copyright (c) 2005-2015 Apple Inc.";
     5NSHumanReadableCopyright = "Copyright (c) 2005-2015 Apple Inc.";
  • mDNSResponder/mDNSMacOSX/PreferencePane/PrivilegedOperations.c

    r49ebc73 rf761b29  
    44    Abstract: Interface to "ddnswriteconfig" setuid root tool.
    55
    6     Copyright: (c) Copyright 2005 Apple Computer, Inc. All rights reserved.
    7 
    8     Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
     6    Copyright: (c) Copyright 2005-2015 Apple Inc. All rights reserved.
     7
     8    Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
    99    ("Apple") in consideration of your agreement to the following terms, and your
    1010    use, installation, modification or redistribution of this Apple software
     
    2020    this notice and the following text and disclaimers in all such redistributions of
    2121    the Apple Software.  Neither the name, trademarks, service marks or logos of
    22     Apple Computer, Inc. may be used to endorse or promote products derived from the
     22    Apple Inc. may be used to endorse or promote products derived from the
    2323    Apple Software without specific prior written permission from Apple.  Except as
    2424    expressly stated in this notice, no other rights or licenses, express or implied,
     
    4949#include <stdint.h>
    5050#include <stdlib.h>
    51 #include <unistd.h>
     51#include <spawn.h>
    5252#include <sys/wait.h>
    5353#include <AssertMacros.h>
    5454#include <Security/Security.h>
    5555
     56extern char **environ;
    5657Boolean gToolApproved = false;
    5758
    58 static pid_t    execTool(const char *args[])
    59 // fork/exec and return new pid
     59static pid_t execTool(const char *args[])
    6060{
    6161    pid_t child;
    6262
    63     child = vfork();
    64     if (child == 0)
    65     {
    66         execv(args[0], (char *const *)args);
    67         printf("exec of %s failed; errno = %d\n", args[0], errno);
    68         _exit(-1);      // exec failed
     63    int err = posix_spawn(&child, args[0], NULL, NULL, (char *const *)args, environ);
     64    if (err)
     65    {
     66        printf("exec of %s failed; err = %d\n", args[0], err);
     67        return -1;
    6968    }
    7069    else
     
    120119            char *installerargs[] = { toolSourcePath, NULL };
    121120            err = AuthorizationExecuteWithPrivileges(authRef, toolInstallerPath, 0, installerargs, (FILE**) NULL);
    122             if (err == noErr) {
     121            if (err == noErr)
     122            {
    123123                int pid = wait(&status);
    124                 if (pid > 0 && WIFEXITED(status)) {
     124                if (pid > 0 && WIFEXITED(status))
     125                {
    125126                    err = WEXITSTATUS(status);
    126                     if (err == noErr) {
     127                    if (err == noErr)
     128                    {
    127129                        gToolApproved = true;
    128130                    }
     
    182184
    183185    child = execTool(args);
    184     if (child > 0) {
     186    if (child > 0)
     187    {
    185188        int status;
    186189        waitpid(child, &status, 0);
  • mDNSResponder/mDNSMacOSX/PreferencePane/ddnswriteconfig.m

    r49ebc73 rf761b29  
    8888
    8989        origDict = SCPreferencesPathGetValue(store, scKey);
    90         if (origDict) {
     90        if (origDict)
     91        {
    9192                dict = CFDictionaryCreateMutableCopy(NULL, 0, origDict);
    9293        }
    9394   
    94         if (!dict) {
     95        if (!dict)
     96        {
    9597                dict = CFDictionaryCreateMutable(NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    9698        }
    9799        require_action( dict != NULL, NoDict, err=memFullErr;);
    98100
    99         if (CFArrayGetCount(domainArray) > 0) {
     101        if (CFArrayGetCount(domainArray) > 0)
     102        {
    100103                CFDictionarySetValue(dict, arrayKey, domainArray);
    101         } else {
     104        }
     105        else
     106        {
    102107                CFDictionaryRemoveValue(dict, arrayKey);
    103108        }
     
    139144
    140145        num = read(fd, *ppBuff, len);
    141         if (num == (ssize_t)len) {
     146        if (num == (ssize_t)len)
     147        {
    142148                *pTag = tag;
    143149                *pLen = len;
    144         } else {
     150        }
     151        else
     152        {
    145153                free(*ppBuff);
    146154                result = -1;
     
    167175        require( len == kAuthorizationExternalFormLength, ReadParamsFailed);
    168176
    169         if (gAuthRef != 0) {
     177        if (gAuthRef != 0)
     178        {
    170179                (void) AuthorizationFree(gAuthRef, kAuthorizationFlagDefaults);
    171180                gAuthRef = 0;
     
    200209        domainData = CFDataCreate(NULL, (UInt8 *)p, len);
    201210        domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
    202        
    203     if (domainType) {
     211        CFRelease(domainData);
     212        free(p);
     213       
     214    if (domainType)
     215    {
    204216        result = WriteArrayToDynDNS(SC_DYNDNS_REGDOMAINS_KEY, domainArray);
    205     } else {
     217    }
     218    else
     219    {
    206220        result = WriteArrayToDynDNS(SC_DYNDNS_BROWSEDOMAINS_KEY, domainArray);
    207221    }
     
    233247        domainArray = (CFArrayRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)domainData];
    234248        result = WriteArrayToDynDNS(SC_DYNDNS_HOSTNAMES_KEY, domainArray);
     249        CFRelease(domainData);
     250        free(p);
    235251       
    236252ReadParamsFailed:
     
    342358        secretData = CFDataCreate(NULL, (UInt8 *)p, len);
    343359        secretDictionary = (CFDictionaryRef)[NSUnarchiver unarchiveObjectWithData:(NSData *)secretData];
     360        CFRelease(secretData);
     361        free(p);
    344362
    345363        keyNameString = (CFStringRef)CFDictionaryGetValue(secretDictionary, SC_DYNDNS_KEYNAME_KEY);
     
    357375
    358376        result = SecKeychainSetPreferenceDomain(kSecPreferencesDomainSystem);
    359         if (result == noErr) {
     377        if (result == noErr)
     378        {
    360379                result = SecKeychainFindGenericPassword(NULL, strlen(domain), domain, 0, NULL, 0, NULL, &item);
    361                 if (result == noErr) {
     380                if (result == noErr)
     381                {
    362382                        result = SecKeychainItemDelete(item);
    363383                        if (result != noErr) fprintf(stderr, "SecKeychainItemDelete returned %d\n", result);
  • mDNSResponder/mDNSMacOSX/Private/dns_services.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Inc. All rights reserved.
     3 * Copyright (c) 2012-2015 Apple Inc. All rights reserved.
    44 *
    55 * PRIVATE DNSX CLIENT LIBRARY --FOR Apple Platforms ONLY OSX/iOS--
     
    1111#include <xpc/xpc.h>
    1212#include <Block.h>
    13 #include <stdio.h>
    14 #include <stdlib.h>
    1513#include <syslog.h>
     14
     15#define LOG_NOW LOG_INFO
    1616
    1717//*************************************************************************************************************
     
    2323{
    2424    connection_t      conn_ref;      // xpc_connection between client and daemon
    25     dispatch_queue_t  lib_q;         // internal queue created in library itself   
     25    dispatch_queue_t  lib_q;         // internal queue created in library itself
    2626    void              *AppCallBack;  // Callback function ptr for Client
    2727    dispatch_queue_t  client_q;      // Queue specified by client for scheduling its Callback
     
    3838static void LogDebug(const char *prefix, xpc_object_t o)
    3939{
    40     if (!LogDebugEnabled()) 
     40    if (!LogDebugEnabled())
    4141        return;
    4242   
    4343    char *desc = xpc_copy_description(o);
    44     syslog(LOG_INFO, "%s: %s", prefix, desc);
     44    syslog(LOG_NOW, "%s: %s", prefix, desc);
    4545    free(desc);
    4646}
     
    5050void DNSXRefDeAlloc(DNSXConnRef connRef)
    5151{
    52     if (!connRef)
    53     {
    54         syslog(LOG_WARNING, "dns_services: DNSXRefDeAlloc called with NULL DNSXConnRef");
     52    if (connRef == NULL)
     53    {
     54        syslog(LOG_WARNING, "dns_services DD: DNSXRefDeAlloc called with NULL DNSXConnRef");
    5555        return;
    5656    }
    57 
     57   
    5858    // Schedule this work on the internal library queue
    5959    dispatch_sync(connRef->lib_q, ^{
    60 
     60        xpc_connection_set_event_handler((connRef)->conn_ref, ^(__unused xpc_object_t event){}); // ignore any more events
    6161        xpc_release(connRef->conn_ref);
     62        connRef->conn_ref = NULL;
     63        dispatch_release(connRef->lib_q);
     64        connRef->lib_q = NULL;
    6265        connRef->AppCallBack = NULL;
    63         dispatch_release(connRef->client_q);
    64 
     66        syslog(LOG_NOW, "dns_services DD: DNSXRefDeAlloc successfully DeAllocated conn_ref & lib_q");
     67       
     68        dispatch_async((connRef)->client_q, ^{
     69            dispatch_release(connRef->client_q);
     70            connRef->client_q = NULL;
     71            free(connRef);
     72            syslog(LOG_NOW, "dns_services DD: DNSXRefDeAlloc successfully DeAllocated client_q & freed connRef");
     73        });
    6574    });
    66 
    67     dispatch_release(connRef->lib_q);
    68     free(connRef);
    69 
    70     syslog(LOG_INFO, "dns_services: DNSXRefDeAlloc successfully DeAllocated connRef");
    71 
    72 }
    73 
    74 // Sends the Msg(Dictionary) to the Server
    75 static DNSXErrorType SendMsgToServer(DNSXConnRef *connRef, xpc_object_t msg, bool old_conn)
     75   
     76    // DO NOT reference connRef after this comment, as it may have been freed
     77    syslog(LOG_NOW, "dns_services DD: DNSXRefDeAlloc successfully DeAllocated connRef");
     78   
     79}
     80
     81// Sends the Msg(Dictionary) to the Server Daemon
     82static DNSXErrorType SendMsgToServer(DNSXConnRef connRef, xpc_object_t msg)
    7683{
    7784    DNSXErrorType errx = kDNSX_NoError;
    78 
    79     LogDebug("dns_services: SendMsgToServer", msg);
    80    
    81     xpc_connection_set_event_handler((*connRef)->conn_ref, ^(xpc_object_t recv_msg)
     85   
     86    LogDebug("dns_services DD: SendMsgToServer Sending msg to Daemon", msg);
     87   
     88    xpc_connection_send_message_with_reply((connRef)->conn_ref, msg, (connRef)->lib_q, ^(xpc_object_t recv_msg)
    8289    {
    8390        xpc_type_t type = xpc_get_type(recv_msg);
    84 
     91                                               
    8592        if (type == XPC_TYPE_DICTIONARY)
    8693        {
    87             LogDebug("dns_services: SendMsgToServer SUCCESS CALLBACK FROM SERVER", recv_msg);
    88             syslog(LOG_INFO, "dns_services: Successfully Sent Msg to the Daemon");
     94            LogDebug("dns_services DD: SendMsgToServer Received reply msg from Daemon", recv_msg);
    8995            uint64_t daemon_status = xpc_dictionary_get_uint64(recv_msg, kDNSDaemonReply);
    90  
    91             // Schedule the AppCallBacks on the Client Specified Queue
    92             switch (daemon_status)
    93             {   
    94                 case kDNSDaemonEngaged:
    95                         dispatch_async((*connRef)->client_q, ^{ 
    96                                         ((DNSXEnableProxyReply)(*connRef)->AppCallBack)((*connRef), kDNSX_Engaged);
    97                                         });
    98                                         break;
    99                 case kDNSMsgReceived:
    100                         dispatch_async((*connRef)->client_q, ^{
    101                                         ((DNSXEnableProxyReply)(*connRef)->AppCallBack)((*connRef), kDNSX_NoError);
    102                                         });
    103                                         break;
    104                 default:
    105                         dispatch_async((*connRef)->client_q, ^{
    106                                         ((DNSXEnableProxyReply)(*connRef)->AppCallBack)((*connRef), kDNSX_UnknownErr);
    107                                         });
    108                                         break;
    109             }   
    110 
     96                                                   
     97            if (connRef == NULL || connRef->client_q == NULL || connRef->AppCallBack == NULL)
     98            {
     99                // If connRef is bad, do not schedule any callbacks to the client
     100                syslog(LOG_WARNING, "dns_services DD: SendMsgToServer: connRef is BAD Daemon status code [%llu]", daemon_status);
     101            }
     102            else
     103            {
     104                switch (daemon_status)
     105                {
     106                    case kDNSMsg_NoError:
     107                        dispatch_async((connRef)->client_q, ^{
     108                        if (connRef->AppCallBack != NULL)
     109                            ((DNSXEnableProxyReply)connRef->AppCallBack)(connRef, kDNSX_NoError);
     110                        });
     111                        break;
     112                                                             
     113                    case kDNSMsg_BadArg:
     114                        dispatch_async((connRef)->client_q, ^{
     115                        if (connRef->AppCallBack != NULL)
     116                            ((DNSXEnableProxyReply)connRef->AppCallBack)(connRef, kDNSX_BadParam);
     117                        });
     118                        break;
     119                                                               
     120                    default:
     121                        dispatch_async((connRef)->client_q, ^{
     122                        if (connRef->AppCallBack != NULL)
     123                            ((DNSXEnableProxyReply)connRef->AppCallBack)(connRef, kDNSX_UnknownErr);
     124                        });
     125                        break;
     126                }
     127            }
    111128        }
    112129        else
    113130        {
    114             LogDebug("dns_services: SendMsgToServer UNEXPECTED CALLBACK FROM SERVER", recv_msg);
    115             syslog(LOG_WARNING, "dns_services: Connection failed since NO privileges to access service OR Daemon NOT Running");
    116             dispatch_async((*connRef)->client_q, ^{
    117                             ((DNSXEnableProxyReply)(*connRef)->AppCallBack)((*connRef), kDNSX_DaemonNotRunning);
    118                             });
     131            syslog(LOG_WARNING, "dns_services DD: SendMsgToServer Received unexpected reply from daemon [%s]",
     132                                xpc_dictionary_get_string(recv_msg, XPC_ERROR_KEY_DESCRIPTION));
     133            LogDebug("dns_services DD: SendMsgToServer Unexpected Reply contents", recv_msg);
    119134        }
    120135    });
    121136   
    122     // To prevent Over-Resume of a connection
    123     if (!old_conn)
    124         xpc_connection_resume((*connRef)->conn_ref);
    125     xpc_connection_send_message((*connRef)->conn_ref, msg);
    126     if (!errx)
    127         syslog(LOG_INFO, "dns_services: SendMSgToServer sent Msg Dict successfully to Daemon");
    128137    return errx;
    129138}
    130139
    131 // Creates a new DNSX Connection Reference(DNSXConnRef).
    132 // If DNSXConnRef exists, you may want to use that depending on the use case
    133 static DNSXErrorType InitConnection(DNSXConnRef *connRef, const char *servname, dispatch_queue_t clientq, void *AppCallBack)
    134 {
    135     if (!connRef)
    136     {
    137         syslog(LOG_WARNING, "dns_services: InitConnection() called with NULL DNSXConnRef");
    138         return kDNSX_BadParam;   
    139     }
    140 
    141     *connRef = malloc(sizeof(struct _DNSXConnRef_t));
    142     if (!(*connRef))
    143     {
    144         syslog(LOG_WARNING, "dns_services: InitConnection() No memory to allocate");
     140// Creates a new DNSX Connection Reference(DNSXConnRef)
     141static DNSXErrorType InitConnection(DNSXConnRef *connRefOut, const char *servname, dispatch_queue_t clientq, void *AppCallBack)
     142{
     143    if (connRefOut == NULL)
     144        return kDNSX_BadParam;
     145   
     146    // Use a DNSXConnRef on the stack to be captured in the blocks below, rather than capturing the DNSXConnRef* owned by the client
     147    DNSXConnRef connRef = malloc(sizeof(struct _DNSXConnRef_t));
     148    if (connRef == NULL)
     149    {
     150        syslog(LOG_WARNING, "dns_services DD: InitConnection() No memory to allocate!");
    145151        return kDNSX_NoMem;
    146152    }
    147 
    148     // Initialize the DNSXConnRef 
     153   
     154    // Initialize the DNSXConnRef
    149155    dispatch_retain(clientq);
    150     (*connRef)->client_q     = clientq;
    151     (*connRef)->AppCallBack  = AppCallBack;   
    152     (*connRef)->lib_q        = dispatch_queue_create("com.apple.mDNSResponder.libdns_services.q", NULL);
    153     (*connRef)->conn_ref     = xpc_connection_create_mach_service(servname, (*connRef)->lib_q, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
    154 
    155     syslog(LOG_INFO, "dns_services: InitConnection() successfully create a new DNSXConnRef");
     156    connRef->client_q     = clientq;
     157    connRef->AppCallBack  = AppCallBack;
     158    connRef->lib_q        = dispatch_queue_create("com.apple.mDNSResponder.libdns_services.q", DISPATCH_QUEUE_SERIAL);
     159    connRef->conn_ref     = xpc_connection_create_mach_service(servname, connRef->lib_q, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
     160   
     161    if (connRef->conn_ref == NULL || connRef->lib_q == NULL)
     162    {
     163        syslog(LOG_WARNING, "dns_services DD: InitConnection() conn_ref/lib_q is NULL");
     164        if (connRef != NULL)
     165            free(connRef);
     166        return kDNSX_NoMem;
     167    }
     168   
     169    xpc_connection_set_event_handler(connRef->conn_ref, ^(xpc_object_t event)
     170    {
     171        if (connRef == NULL || connRef->client_q == NULL || connRef->AppCallBack == NULL)
     172        {
     173            // If connRef is bad, do not schedule any callbacks to the client
     174            syslog(LOG_WARNING, "dns_services DD: InitConnection: connRef is BAD Unexpected Connection Error [%s]",
     175                                xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
     176        }
     177        else
     178        {
     179            syslog(LOG_WARNING, "dns_services DD: InitConnection: Unexpected Connection Error [%s] Ping the client",
     180                                 xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
     181            dispatch_async(connRef->client_q, ^{
     182            if (connRef->AppCallBack != NULL)
     183                ((DNSXEnableProxyReply)connRef->AppCallBack)(connRef, kDNSX_DaemonNotRunning);
     184            });
     185        }
     186                                         
     187    });
     188    xpc_connection_resume(connRef->conn_ref);
     189   
     190    *connRefOut = connRef;
     191   
    156192    return kDNSX_NoError;
    157193}
    158194
    159 DNSXErrorType DNSXEnableProxy(DNSXConnRef *connRef, DNSProxyParameters proxyparam, IfIndex inIfindexArr[MaxInputIf], 
    160                                IfIndex outIfindex, dispatch_queue_t clientq, DNSXEnableProxyReply callBack)
    161 {
    162 
     195DNSXErrorType DNSXEnableProxy(DNSXConnRef *connRef, DNSProxyParameters proxyparam, IfIndex inIfindexArr[MaxInputIf],
     196                              IfIndex outIfindex, dispatch_queue_t clientq, DNSXEnableProxyReply callBack)
     197{
     198   
    163199    DNSXErrorType errx = kDNSX_NoError;
    164     bool old_conn = false;   
    165 
     200   
    166201    // Sanity Checks
    167     if (!connRef || !callBack || !clientq)
    168     {
    169         syslog(LOG_WARNING, "dns_services: DNSXEnableProxy called with NULL DNSXConnRef OR Callback OR ClientQ parameter");
     202    if (connRef == NULL || callBack == NULL || clientq == NULL)
     203    {
     204        syslog(LOG_WARNING, "dns_services DD: DNSXEnableProxy called with NULL DNSXConnRef OR Callback OR ClientQ parameter");
    170205        return kDNSX_BadParam;
    171     }   
    172 
    173     // If no connRef, get it from InitConnection()
    174     if (!*connRef)
     206    }
     207   
     208    // Get connRef from InitConnection()
     209    if (*connRef == NULL)
    175210    {
    176211        errx = InitConnection(connRef, kDNSProxyService, clientq, callBack);
    177212        if (errx) // On error InitConnection() leaves *connRef set to NULL
    178213        {
    179             syslog(LOG_WARNING, "dns_services: Since InitConnection() returned %d error returning w/o sending msg", errx);
     214            syslog(LOG_WARNING, "dns_services DD: Since InitConnection() returned %d error returning w/o sending msg", errx);
    180215            return errx;
    181216        }
    182217    }
    183     else // Client already has a valid connRef
    184     {
    185         old_conn = true;
    186     }
    187 
     218    else // Client already has a connRef and this is not valid use for this SPI
     219    {
     220        syslog(LOG_WARNING, "dns_services DD: Client already has a valid connRef! This is incorrect usage from the client");
     221        return kDNSX_BadParam;
     222    }
     223   
    188224    // Create Dictionary To Send
    189     xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); 
    190     if (!dict)
    191     {
    192         syslog(LOG_WARNING, "dns_services: DNSXEnableProxy could not create the Msg Dict To Send!");
     225    xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0);
     226    if (dict == NULL)
     227    {
     228        syslog(LOG_WARNING, "dns_services DD: DNSXEnableProxy could not create the Msg Dict To Send!");
    193229        DNSXRefDeAlloc(*connRef);
    194         return kDNSX_DictError;
    195     }
    196 
     230        return kDNSX_NoMem;
     231    }
     232   
    197233    xpc_dictionary_set_uint64(dict, kDNSProxyParameters, proxyparam);
    198 
     234   
    199235    xpc_dictionary_set_uint64(dict, kDNSInIfindex0,      inIfindexArr[0]);
    200236    xpc_dictionary_set_uint64(dict, kDNSInIfindex1,      inIfindexArr[1]);
    201     xpc_dictionary_set_uint64(dict, kDNSInIfindex2,      inIfindexArr[2]); 
     237    xpc_dictionary_set_uint64(dict, kDNSInIfindex2,      inIfindexArr[2]);
    202238    xpc_dictionary_set_uint64(dict, kDNSInIfindex3,      inIfindexArr[3]);
    203239    xpc_dictionary_set_uint64(dict, kDNSInIfindex4,      inIfindexArr[4]);
    204 
     240   
    205241    xpc_dictionary_set_uint64(dict, kDNSOutIfindex,      outIfindex);
    206  
    207     errx = SendMsgToServer(connRef, dict, old_conn);
     242    
     243    errx = SendMsgToServer(*connRef, dict);
    208244    xpc_release(dict);
    209 
    210     return errx;
    211 }
    212 
     245    dict = NULL;
     246   
     247    return errx;
     248}
     249
  • mDNSResponder/mDNSMacOSX/Private/dns_services.h

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Inc. All rights reserved.
     3 * Copyright (c) 2012-2015 Apple Inc. All rights reserved.
    44 *
    55 *
     
    2222    kDNSX_NoError                   =  0,
    2323    kDNSX_UnknownErr                = -65537,   /* 0xFFFE FFFF */
    24     kDNSX_NoMem                     = -65539,
    25     kDNSX_BadParam                  = -65540,
    26     kDNSX_DaemonNotRunning          = -65563,   /* Background daemon not running */
    27     kDNSX_DictError                 = -65565,   /* Dictionary Error */
    28     kDNSX_Engaged                   = -65566,   /* DNS Proxy is in use by another client */
    29     kDNSX_Timeout                   = -65568   
     24    kDNSX_NoMem                     = -65539,   /* No Memory   */
     25    kDNSX_BadParam                  = -65540,   /* Client passes invalid arg/Bad use of SPI */
     26    kDNSX_DaemonNotRunning          = -65563    /* Daemon not running */
    3027} DNSXErrorType;
    3128
    32 // A max of 5 input interfaces can be processed at one time
     29// A max of 5 input interfaces can be processed
    3330#define MaxInputIf 5
    3431#define IfIndex uint64_t
     
    4340
    4441/*********************************************************************************************
    45 *
    46 *  Enable DNS Proxy Functionality
    47 *
    48 *********************************************************************************************/
     42 *
     43 *  Enable DNS Proxy Functionality
     44 *
     45 *********************************************************************************************/
    4946
    5047/* DNSXEnableProxy : Turns ON the DNS Proxy (Details below)
     
    5451 * connRef:                  The DNSXConnRef initialized by DNSXEnableProxy().
    5552 *
    56  * errCode:                  Will be kDNSX_NoError on success, otherwise will indicate the
    57  *                           failure that occurred.  Other parameters are undefined if
    58  *                           errCode is nonzero.
     53 * errCode:                  Will be kDNSX_NoError on success, otherwise will indicate the
     54 *                           failure that occurred.
    5955 *
    6056 */
     
    6359(
    6460    DNSXConnRef           connRef,
    65     DNSXErrorType         errCode 
     61    DNSXErrorType         errCode
    6662);
    6763
    6864/* DNSXEnableProxy
    69  * 
    70  * Enables the DNS Proxy functionality which will remain ON until the client terminates explictly (or exits/crashes).
    71  * Client can turn it OFF by passing the returned DNSXConnRef to DNSXRefDeAlloc()
    72  * 
     65 *
     66 * Enables the DNS Proxy functionality which will remain ON until the client explicitly turns it OFF
     67 * by passing the returned DNSXConnRef to DNSXRefDeAlloc(), or the client exits or crashes.
     68 *
    7369 * DNSXEnableProxy() Parameters:
    7470 *
    75  * connRef:                   A pointer to DNSXConnRef that is initialized to NULL when called for the first 
    76  *                            time. If the call succeeds it will be initialized to a non-NULL value.
     71 * connRef:                   A pointer to DNSXConnRef that is initialized to NULL.
     72 *                            If the call succeeds it will be initialized to a non-NULL value.
    7773 *                            Client terminates the DNS Proxy by passing this DNSXConnRef to DNSXRefDeAlloc().
    7874 *
     
    8985 *                            Passing kDNSIfindexAny causes DNS Queries to be sent on the primary interface.
    9086 *
     87 *                            Note: It is the responsibility of the client to ensure the input/output interface
     88 *                            indexes are valid.
     89 *
    9190 * clientq:                   Queue the client wants to schedule the callBack on (Note: Must not be NULL)
    9291 *
    9392 * callBack:                  CallBack function for the client that indicates success or failure.
    94  *                            Note: callback may be invoked more than once, For eg. if enabling DNS Proxy
    95  *                            first succeeds and the daemon possibly crashes sometime later. 
     93 *                            Note: callback may be invoked more than once, For e.g. if enabling DNS Proxy
     94 *                            first succeeds and the daemon possibly crashes sometime later.
    9695 *
    9796 * return value:              Returns kDNSX_NoError when no error otherwise returns an error code indicating
    98  *                            the error that occurred. Note: A return value of kDNSX_NoError does not mean 
     97 *                            the error that occurred. Note: A return value of kDNSX_NoError does not mean
    9998 *                            that DNS Proxy was successfully enabled. The callBack may asynchronously
    100  *                            return an error (such as kDNSX_DaemonNotRunning/ kDNSX_Engaged)
     99 *                            return an error (such as kDNSX_DaemonNotRunning)
    101100 *
    102101 */
     
    110109    dispatch_queue_t         clientq,
    111110    DNSXEnableProxyReply     callBack
    112 );
     111 );
    113112
    114113/* DNSXRefDeAlloc()
     
    122121void DNSXRefDeAlloc(DNSXConnRef connRef);
    123122
    124 #endif  /* _DNS_SERVICES_H */
     123#endif
  • mDNSResponder/mDNSMacOSX/Private/dns_xpc.h

    r49ebc73 rf761b29  
    2727typedef enum
    2828{
    29     kDNSMsgReceived       =  0,
    30     kDNSDaemonEngaged
     29    kDNSMsg_NoError       =  0,
     30    kDNSMsg_BadArg
    3131} DaemonReplyStatusCodes;
    3232
  • mDNSResponder/mDNSMacOSX/Private/xpc_services.c

    r49ebc73 rf761b29  
    11/* -*- Mode: C; tab-width: 4 -*-
    22 *
    3  * Copyright (c) 2012 Apple Inc. All rights reserved.
     3 * Copyright (c) 2012-2015 Apple Inc. All rights reserved.
    44 *
    55 * xpc_services.c
     
    9191            if (reply)
    9292            {   
    93                 xpc_dictionary_set_uint64(reply, kDNSDaemonReply, kDNSDaemonEngaged);
     93                xpc_dictionary_set_uint64(reply, kDNSDaemonReply, kDNSMsg_BadArg);
    9494                xpc_connection_send_message(remote_conn, reply);
    9595                xpc_release(reply); 
     
    105105        }
    106106    }
    107    
     107 
     108 
     109    xpc_object_t response = xpc_dictionary_create_reply(req);
    108110    // Return Success Status to the client
    109     xpc_object_t response = xpc_dictionary_create(NULL, NULL, 0);
    110111    if (response)
    111112    {
    112         xpc_dictionary_set_uint64(response, kDNSDaemonReply, kDNSMsgReceived);
     113        xpc_dictionary_set_uint64(response, kDNSDaemonReply, kDNSMsg_NoError);
    113114        xpc_connection_send_message(remote_conn, response);
    114115        xpc_release(response); 
     
    156157    }
    157158   
     159    if (!entitled)
     160        LogMsg("IsEntitled: DNSProxyService Client is missing Entitlement!");
     161   
    158162    return entitled;
    159163}
     
    161165mDNSlocal void accept_dps_client(xpc_connection_t conn)
    162166{
    163     uid_t euid;
    164     euid = xpc_connection_get_euid(conn);
    165 
    166     if (euid != 0 || !IsEntitled(conn, kDNSProxyService))
     167    uid_t c_euid;
     168    int   c_pid;
     169    c_euid  = xpc_connection_get_euid(conn);
     170